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
16,822
packs.lisp
oblivia-simplex_genlin/packs.lisp
(in-package :genlin) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Pack operations ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; a pack is a list of creatures ;; we'll start with a simple control structure: the car of the pack is ;; the delegator. It delegates the decision to (elt pack (execute-sequence ;; (creature-eff (car pack))) mod (length pack)), which is then executed. ;; obviously, it is possible to develop more complicated control structures, ;; so long as provisions are made to handle the halting problem (a timer, e.g.) ;; but we'll start with these simple constructions of "star packs". (defun execute-pack (alpha-crt &key (input) (output *out-reg*)) (let ((delegator-registers ;; should store as a constant. (loop for i from 0 to (1- (expt 2 *destination-register-bits* collect i))))) ;; let the delegation task use a distinct register, if available, ;; by setting its output register to the highest available R/W reg. (execute-creature (elt (creature-pack alpha-crt) (register-vote (execute-creature alpha-crt :input input :output delegator-registers (length pack))) :input input :output output))) (defun pmutate-shuffle (pack) (shuffle pack)) (defun pmutate-shuffle-underlings (pack) (cons (car pack) (shuffle (cdr pack)))) (defun pmutate-swap-alpha (pack) (let ((tmp)) (setf tmp (car pack)) (setf (pick (cdr pack)) (car pack)) (setf (car pack) tmp) pack)) (defun pmutate-inbreed (pack) (let* ((p0 (pick pack)) (p1 (if (> (length pack) 2) (pick (remove p0 pack)) (random-mutation p0))) (cubs)) (unless (or (null p0) (null p1)) (setf cubs (mate p0 p1 :sex t))) (nsubst p0 (car cubs) pack) (nsubst p1 (cdr cubs) pack) pack)) (defun pmutate-alpha (pack) (setf #1=(creature-seq (car pack)) (random-mutation #1#)) pack) (defun pmutate-smutate (pack) (let ((mutant (pick pack))) (setf #1=(creature-seq mutant) (random-mutation #1#)) pack)) (defun pmutate-smutate-underlings (pack) (cons (car pack) (pmutate-smutate (cdr pack)))) (defun pack-mingle (pack1 pack2) "Destructively mingles the two packs, preserving alphas and size." (let ((underlings (shuffle (concatenate 'list (cdr pack1) (cdr pack2))))) (setf pack1 (cons (car pack1) (subseq underlings 0 (length pack1)))) (setf pack2 (cons (car pack2) (subseq underlings (length pack1)))) (list pack1 pack2))) ;; Note for pack mutations: do not mutate a creature without replacing it. otherwise eff, fit, cas, etc. are falsified. if not replacing, then reset these attributes. (defun pack-mate (pack1 pack2) "Nondestructively mates the two packs, pairwise, producing two new packs." (let ((offspring (loop for p1 in pack1 for p2 in pack2 collect (mate p1 p2)))) (list (mapcar #'car offspring) (mapcar #'cadr offspring)))) (defparameter *pack-mutations* (vector #'pmutate-smutate #'pmutate-inbreed #'pmutate-swap-alpha #'pmutate-shuffle-underlings #'pmutate-alpha)) (defparameter *underling-mutations* (vector #'pmutate-shuffle-underlings #'pmutate-inbreed)) ;; accidental cloning problem... ;; packs seem to collapse into pointers to identical creatures. ;; needs some tinkering. (defun random-pack-mutation (pack) (setf pack (funcall (pick *pack-mutations*) pack))) (defun pack-coverage (pack &key (ht *training-hashtable*)) (measure-population-case-coverage (cdr pack) ht)) (defun mutate-pack (pack) (cond ((= 1 (pack-coverage pack)) ;; when pack coverage complete, mutate alpha (random-mutation (car pack))) (t (
3,951
Common Lisp
.lisp
91
36.846154
167
0.622848
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
f6c7da87cdfd459a85a247fd6c906b83bd921d0c071cc6d955c62fa50cc7307c
16,822
[ -1 ]
16,823
compile.lisp
oblivia-simplex_genlin/compile.lisp
(load "~/quicklisp/setup.lisp") (ql:quickload :genlin) (sb-ext:save-lisp-and-die "GENLIN" :executable t :toplevel #'genlin::main)
130
Common Lisp
.lisp
3
42.333333
74
0.732283
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
ac2a073a49ca21ce70e36d30fd7f40a396151c6bf260e1dc5b9ae5668824243b
16,823
[ -1 ]
16,824
scratch.lisp
oblivia-simplex_genlin/scratch.lisp
;; bad code repetition here. once it's working, merge it with ;; the main evolve loop, and parameterize away the difference between ;; evolving hives and evolving individuals. (defun evolve-hives (&key (hive-ring) (h-rounds) (h-smethod #'tournement!)) ;; no real reason to use lexicase for hives (let ((h-stopwatch (make-stopwatch))) (funcall h-stopwatch 'set) (handler-case (loop for i from 1 to (* h-rounds *number-of-islands*) do (let ((hive (pop hive-ring))) (labels ((dispatcher () (when *parallel* (sb-thread:grab-mutex (hive-lock hive))) (funcall h-smethod hive) (when *parallel* (sb-thread:release-mutex (hive-lock hive)))) (dispatch () (incf (hive-era hive)) (if *parallel* (sb-thread:make-thread #'dispatcher) (dispatcher)))) (dispatch) ;; main event )))))) ;;; alternative coverage algo (defun islands->hives (island-ring) (let ((hive-ring (loop repeat *number-of-islands* collect (make-hive :lock (sb-thread:make-mutex :name "hive lock") :logger (make-logger) :best (make-creature :fit 0) :era 0 :of *number-of-islands*)))) (loop for isle in (de-ring island-ring) for hive in hive-ring do (setf (hive-workers hive) (extract-population-from-coverage isle)) (setf (hive-id hive) (island-id isle)) (setf (hive-queens hive) (loop repeat *queen-population-size* collect (spawn-creature (+ *min-len* (random *max-start-len*)))))) (circular hive-ring))) ;; (setf *stop* t) ;; (defun greedy-mutation (crt &key (fitfunc)) ;; ;; greedily searches for the single mutation that will increase fitness ;; ;; the most. ;; (let ((newseq (copy-seq seq)) ;; (scores '())) ;; (when (length (> (creature-eff crt) 0)) ;; (loop for i from 0 to (1- (length newseq)) do ;; (let ((oldinst (elt newseq i))) ;; (when (member oldinst (creature-eff seq)) ;; (loop for newinst from 0 to (1- (expt 2 *wordsize*)) do ;; (setf (elt i newseq) newinst) ;; (acons (cons (copy-seq newseq) (funcall fitfunc newseq) scores))) ;; (setf (elt newseq i) oldinst)))) ;; restore old instruction ;; ;; then sort scores by max fit and take fittest. ;; )))
3,034
Common Lisp
.lisp
63
33.142857
88
0.471807
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
a4bceeb7db66e18d8c26b3e3c7b91135359f3ac44a22ce2a149bed203ed86ae9
16,824
[ -1 ]
16,825
slomachine.lisp
oblivia-simplex_genlin/slomachine.lisp
(in-package :genlin) ;;; This copy only exists for the sake of carefree tinkering. Eventually, ;;; it will be merged with r-machine.lisp, the difference between the two ;;; coming down to a choice of parameters. (defparameter *machine* :slomachine) ;;; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ;;; SLOMACHINE (Store/LOad-machine) is an alternative architecture to be ;;; used for the genetic programming engine in GENLIN. The most signficant ;;; difference between SLOMACHINE and R-MACHINE (its predecessor) is that ;;; SLOMACHINE introduces support for STO and LOD instructions, allowing ;;; a creature to inspect its own source code and load bytes of source ;;; into its registers with LOD (giving it a nutrious, autophagic diet of ;;; fresh constants) and to rewrite its own code segment with STO. This can ;;; be used either as a simple means of storing data for later, when writing ;;; to past instructions (instructions at indicies prior to the current ;;; programme counter) or as a control structure, when it is used to write ;;; to its own future. ;;; ;;; Preliminary trials have shown GPs running on SLOMACHINE -- ;;; particularly with the tic-tac-toe data set -- to converge up to 40 ;;; times faster than they did on R-MACHINE, and result in much ;;; simpler and more compact code. (On ttt, this meant a convergence by ;;; generation 200 or so, rather than generation 5000, when running in ;;; tournement mode.) ;;; ;;; On a smaller scale, it is somewhat slower than R-MACHINE, however, ;;; and REMOVE-INTRONS is unable to streamline the code before ;;; execution, since we may need to know what the input is before we ;;; can calculate the effective registers. This isn't a totally ;;; insurmountable obstacle, however, but an improved remove-introns ;;; algorithm remains to be written. ;;; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Declaim inline functions for speed ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (declaim (inline guard-val)) (declaim (inline MOV DIV MUL XOR CNJ DIS PMD ADD SUB MUL JLE)) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; master update function for VM parameters ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; --- Operations: these can be tweaked independently of the ;; --- fields above, so long as their are at least (expt 2 *opf*) ;; --- elements in the *operations* vector. (defun MOV (&rest args) "Copy the contents in SRC to register DST." (declare (type (or null (cons rational)) args)) (the rational (coerce (car args) 'rational))) (defun DIV (&rest args) "A divide-by-zero-proof division operator." (declare (type (or null (cons rational)) args)) (the rational (if (some #'zerop args) 0 (/ (car args) (cadr args))))) (defun XOR (&rest args) ;; xor integer parts "Performs a bitwise XOR on SRC and DST, storing the result in DST." (declare (type (or null (cons rational)) args)) (check-type args (cons rational)) (the rational (coerce (logxor (floor (car args)) (floor (cadr args))) 'rational))) (defun CNJ (&rest args) "Performs a bitwise AND on SRC and DST, storing the result in DST." (declare (type (or null (cons rational)) args)) (check-type args (cons rational)) (logand (floor (car args)) (floor (cadr args)))) (defun DIS (&rest args) "Performs a bitwise OR on SRC and DST, storing the result in DST." (declare (type (or null (cons rational)) args)) (check-type args (cons rational)) (the rational (lognot (logand (lognot (floor (car args))) (lognot (floor (cadr args))))))) (defun PMD (&rest args) "Performs a protected SRC MOD DST, storing the result in DST." (declare (type (or null (cons rational)) args)) (check-type args (cons rational)) (the rational (if (some #'zerop args) (car args) (mod (car args) (cadr args))))) (defun ADD (&rest args) "Adds the rational-valued contents of SRC and DST, storing result in DST." (declare (type (or null (cons rational)) args)) (check-type args (cons rational)) (the rational (+ (car args) (cadr args)))) (defun SUB (&rest args) "Subtracts DST from SRC, storing the value in DST." (declare (type (or null (cons rational)) args)) (check-type args (cons rational)) (- (car args) (cadr args))) (defun MUL (&rest args) "Multiplies SRC and DST, storing the value in DST." (declare (type (or null (cons rational)) args)) (check-type args (cons rational)) (* (car args) (cadr args))) (defun JLE (&rest args) ;; CONDITIONAL JUMP OPERATOR "Stub. Really just here for consistent pretty printing." (declare (type (or null (cons rational)) args)) (check-type args (cons rational)) (if (<= (car args) (cadr args)) (1+ (caddr args)) (caddr args))) (defun LOD (&rest args) ;; CONDITIONAL JUMP OPERATOR "Stub. Really just here for consistent pretty printing." (declare (ignore args)) (print "You shouldn't be seeing this.") 0) (defun STO (&rest args) ;; CONDITIONAL JUMP OPERATOR "Stub. Really just here for consistent pretty printing." (declare (ignore args)) (print "You shouldn't be seeing this.") 0) (defparameter *reg-ops-list* `(,#'DIV ,#'MUL ,#'SUB ,#'ADD ,#'PMD ,#'XOR ,#'CNJ ,#'DIS ,#'MOV)) (defparameter *jump-ops-list* `(,#'JLE)) (defparameter *load-ops-list* `(,#'LOD)) (defparameter *store-ops-list* `(,#'STO)) (defparameter *operations* (concatenate 'vector (subseq *reg-ops-list* 0 5) *jump-ops-list* *load-ops-list* *store-ops-list*)) (defparameter *reg-op-keys* '(:DIV :MUL :SUB :ADD :PMD :XOR :CNJ :DIS :MOV)) (defparameter *jmp-op-keys* '(:JLE)) (defparameter *store-op-keys* '(:STO)) (defparameter *load-op-keys* '(:LOD)) (defvar *operation-keys*) (defun shuffle-operations () (setf *operations* (coerce (shuffle (coerce *operations* 'list)) 'vector))) ;; this whole thing should be refactored out of slomachine and r-machine, ;; to a more central location (defun update-dependent-machine-parameters () (setf *operation-keys* (pairlis (mapcar #'(lambda (x) (intern x :keyword)) (mapcar #'func->string (coerce *operations* 'list))) (coerce *operations* 'list))) ;; Not quite ready yet. (when *opstring* (setf *ops* (read-from-string (concatenate 'string "(" (substitute #\space #\, *opstring*) ")")))) (when *ops* (setf *ops* (sort *ops* #'(lambda (x y) (cond ((and (member x *reg-op-keys*) (member y *jmp-op-keys*)) t) ((and (member x *reg-op-keys*) (member y *load-op-keys*)) t) ((and (member x *reg-op-keys*) (member y *store-op-keys*)) t) ((and (member x *jmp-op-keys*) (member y *load-op-keys*)) t) ((and (member x *jmp-op-keys*) (member y *store-op-keys*)) t) ((and (member x *load-op-keys*) (member y *store-op-keys*)) t) (t nil))))) (setf *operations* (concatenate 'vector (mapcar #'(lambda (x) (cdr (assoc x *operation-keys*))) *ops*) (loop repeat (expt 2 *opcode-bits*) collect #'MOV)))) (setf *destination-register-bits* (max (ceiling (log (how-many-output-registers?) 2)) *destination-register-bits*)) (setf *source-register-bits* (max (ceiling (log (+ (how-many-input-registers?) (how-many-output-registers?)) 2)) *source-register-bits*)) (setf *wordsize* (+ *opcode-bits* *source-register-bits* *destination-register-bits* )) (setf *machine-fmt* (format nil "~~~D,'0b ~~a" *wordsize*)) (setf *max-inst* (expt 2 *wordsize*)) ;; upper bound on inst size (setf *opbits* (byte *opcode-bits* 0)) (setf *srcbits* (byte *source-register-bits* *opcode-bits*)) (setf *dstbits* (byte *destination-register-bits* (+ *source-register-bits* *opcode-bits*))) (setf *default-input-reg* (concatenate 'vector (loop for i from 1 to (- (expt 2 *source-register-bits*) (expt 2 *destination-register-bits*)) collect (expt -1 i)))) (setf *default-registers* (concatenate 'vector #(0) (loop for i from 2 to (expt 2 *destination-register-bits*) collect (expt -1 i)))) (setf *pc-idx* (+ (length *default-registers*) (length *default-input-reg*))) (setf *initial-register-state* (concatenate 'vector *default-registers* *default-input-reg* #(0))) ;; PROGRAMME COUNTER (setf *input-start-idx* (length *default-registers*)) (setf *input-stop-idx* (+ *input-start-idx* (length *default-input-reg*)))) ;;(update-dependent-machine-parameters) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Functions for extracting fields from the instructions ;; and other low-level machine code operations. ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (declaim (inline src? dst? op?)) (defun src? (inst) "Returns the source address." (declare (type (signed-byte 32) inst)) (declare (type (cons (signed-byte 32)) *srcbits*)) (the signed-byte (ldb *srcbits* inst))) (defun dst? (inst) "Returns the destination address." (declare (type (signed-byte 32) inst)) (declare (type (cons (signed-byte 32)) *dstbits*)) (the signed-byte (ldb *dstbits* inst))) (defun op? (inst) "Returns the actual operation, in the case of register ops, in the form of a function." (declare (type (signed-byte 32) inst)) (declare (type (cons (signed-byte 32)) *opbits*)) (declare (type (simple-array function) *operations*)) (the function (aref *operations* (ldb *opbits* inst)))) (defun opc? (inst) "Returns the numerical opcode." (declare (type (signed-byte 32) inst)) (declare (type (cons (signed-byte 32)) *opbits*)) (the signed-byte (ldb *opbits* inst))) (defun jmp? (inst) ;; ad-hoc-ish... (declare (type fixnum inst)) (the boolean (equalp (op? inst) #'JLE))) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defparameter =history= (let ((hist '())) (lambda (&optional (entry nil)) (cond ((eq entry 'CLEAR) (setf hist '())) ((eq entry 'ALL) hist) (entry (push entry hist)) (t (car hist)))))) (defun history-push-test (seq reg) (funcall =history= (cons seq reg))) (defun history-flush () (funcall =history= 'CLEAR)) (defun history-print (&optional len) (let ((h (funcall =history=))) (print (subseq h 0 len)))) (defun disassemble-history (&key (all 'all) (len 1) (static nil)) "If passed a sequence in the static field, disassemble it without any reference to register states. If not, disassemble the last len entries in the history stack, tracking changes to the registers." (let* ((history (funcall =history= all)) (story (if static (coerce static 'list) (reverse (subseq history 0 len))))) (loop for line in story do (let* ((registers (if static (copy-seq *initial-register-state*) (getf line :reg))) (inst (if static line (getf line :inst))) (addr) (data) (regnum)) (format t *machine-fmt* ;; needs to be made flexible. inst (inst->string inst)) (when (not static) (format t " (~3d ) " (getf line :pc)) (cond ((member (op? inst) *reg-ops-list*) (format t " ;; now R~d = ~f; R~d = ~f~%" (src? inst) (aref registers (src? inst)) (dst? inst) (aref registers (dst? inst)))) ((member (op? inst) *jump-ops-list*) (if (<= (aref registers (src? inst)) (aref registers (dst? inst))) (format t " ;; R~d <= R~d, so incrementing %PC~%" (src? inst) (dst? inst)) (format t " ;; R~d > R~d, no jump~%" (src? inst) (dst? inst)))) ((member (op? inst) *load-ops-list*) (setf addr (mod (floor (aref registers (src? inst))) (length (getf line :seq))) data (aref (getf line :seq) addr) regnum (dst? inst)) (format t " ;; loading ~d from @~d into R~d~%" data addr regnum)) ((member (op? inst) *store-ops-list*) (setf addr (mod (floor (aref registers (dst? inst))) (length (getf line :seq))) data (ldb (byte *wordsize* 0) (floor (aref registers (src? inst)))) regnum (src? inst)) (format t " ;; storing ~d from R~d in @~d~%" data regnum addr) (when (>= addr (getf line :pc)) (format t "*** SEQUENCE REWRITING ITSELF ***~%"))) (t (format t " WTF?")))) (if static (format t "~%")))) (if static (hrule)))) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; The engine room ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defun guard-val (val minval maxval) "Formats values for registers: guards against overflow, and type casts." (declare (type rational val minval maxval)) (let ((sign (if (< val 0) -1 1))) (declare (type rational sign)) (the rational (coerce (cond ((< (abs val) minval) (* sign minval)) ((> (abs val) maxval) (mod val maxval)) (t val)) 'rational)))) ;; Some anaphoric macros for quickly dispatching instructions ;; and clarifying code, without costly stack operations ;; ;; NB: variables prefixed with the % sigil are free, and should be bound ;; +++ in the environment into which these macros are injected (presumably, ;; just execute-sequence). (defmacro exec-reg-inst (inst) "Executes a register-manipulation instruction." `(setf (aref %reg (dst? ,inst)) (guard-val (apply (op? ,inst) (list (aref %reg (src? ,inst)) (aref %reg (dst? ,inst)))) *minval* *maxval*))) (defmacro exec-jmp-inst (inst) "Executes a jump-type instruction (anaphorically modifies %pc, according to operation (op? inst)." `(setf %pc (guard-val (apply (op? ,inst) (list (aref %reg (src? ,inst)) (aref %reg (dst? ,inst)) %pc)) *minval* *maxval*))) (defmacro exec-load-inst (inst) "Loads contents of memory at address indexed by SRC register into DST register." `(setf (aref %reg (dst? ,inst)) (aref %seq (mod (floor (aref %reg (src? ,inst))) (length %seq))))) (defmacro exec-store-inst (inst) "Stores contents of DST register into memory address indexed by SRC register -- potentially corrupting code." `(setf (aref %seq (mod (floor (aref %reg (dst? ,inst))) (length %seq))) (ldb (byte *wordsize* 0) (floor (aref %reg (src? ,inst)))))) (defun execute-sequence (seq &key (registers *initial-register-state* ) (input *default-input-reg*) (output nil) (debug nil)) "Takes a sequence of instructions, seq, and an initial register state vector, registers, and then runs the virtual machine, returning the resulting value in the registers indexed by the integers in the list parameter, output." (declare (type fixnum *input-start-idx* *pc-idx*) (inline src? dst? op?) (type (cons integer) output) (type (signed-byte 32) *regiops* *jumpops* *loadops* *storops*) (type (simple-array rational 1) input registers seq) (optimize (speed 2))) (flet ((save-state (inst reg seq pc) (declare (type (simple-array rational 1) reg) (type fixnum inst pc) (type function =history=)) (funcall =history= (list :inst inst :reg reg :seq seq :pc pc)))) (let ((%seq (copy-seq seq)) (%reg (copy-seq registers)) (%pc 0) ;; why bother putting the PC in the registers? (seqlen (length seq)) (debugger (or debug *debug*)) (%stack '())) ;; let's add a stack! and get rid of LOD/STO ;; so that we can have our junk DNA back. (declare (type (simple-array rational 1) %reg) (type fixnum seqlen %pc) (type boolean debugger)) ;; the input values will be stored in read-only %reg (setf (subseq %reg *input-start-idx* (+ *input-start-idx* (length input))) input) (unless (zerop seqlen) (loop do ;; (format t "=== ~A ===~%" %reg) ;; Fetch the next instruction (let ((inst (aref %seq %pc))) (declare (type (signed-byte 32) inst)) ;; Increment the programme counter (incf %pc) ;; Perform the operation and store the result in [dst] (cond ((member (op? inst) *reg-ops-list*) (exec-reg-inst inst)) ((member (op? inst) *jump-ops-list*) (exec-jmp-inst inst)) ((member (op? inst) *load-ops-list*) (exec-load-inst inst)) ((member (op? inst) *store-ops-list*) (exec-store-inst inst)) (t (exec-reg-inst inst))) ;; NOP or MOV ;; Save history for debugger (and debugger (save-state inst %reg %seq %pc) (disassemble-history)) ;; Halt when you've reached the end of the sequence (and (>= %pc seqlen) (return))))) (and *debug* (hrule)) ;; pretty (mapcar #'(lambda (i) (aref %reg i)) output)))) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; debugging functions ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defun print-registers (registers) (loop for i from 0 to (1- (length registers)) do (format t "R~d: ~6f ~c" i (aref registers i) #\TAB) (if (= 0 (mod (1+ i) 4)) (format t "~%"))) (format t "~%")) (defun inst->string (inst) (concatenate 'string (format nil "[~a R~d, R~d]" (func->string (op? inst)) (src? inst) (dst? inst))))
20,515
Common Lisp
.lisp
434
35.953917
84
0.519681
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
587e411ab9c6450f2dfbc6afbb1f29bd5b9527712058b637bd398adec3c1dd26
16,825
[ -1 ]
16,826
auxiliary.lisp
oblivia-simplex_genlin/auxiliary.lisp
;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; General Mathematical Helper Functions ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (in-package :genlin) (defun avg (&rest args) (divide (reduce #'+ args) (length args))) (export 'reverse-hash-table) (defun reverse-hash-table (hash-table &key (test 'eql)) (let ((newtable (make-hash-table :test test))) (loop for k being the hash-keys in hash-table do (setf (gethash (gethash k hash-table) newtable) k)) newtable)) (export 'roman) (defun roman (n) (cond ((null n) "NULL") ((= 0 n) "ZERO") (t (format nil "~@R" n)))) (export 'divide) (defun divide (&rest args) (if (some #'zerop args) 0 (reduce #'/ args))) (export 'to-gray-vec) (defun to-gray-vec (base digits value) ;; adapted from C programme found in Wikipedia's Gray Code entry (let ((gray (make-array digits)) (base-n (make-array digits)) (shift 0)) ;; put the normal base-n number into the base-n array. For ;; base 10, 109 would be stored as #(9 0 1). (loop for i from 0 to (1- digits) do (setf (aref base-n i) (mod value base) value (floor (/ value base)))) ;; convert the normal base-n number into the graycode equivalent ;; note that the loop starts at the most significant digit and goes down (loop for i from (1- digits) downto 0 do (setf (aref gray i) (mod (+ (aref base-n i) shift) base) shift (+ shift (- base (aref gray i))))) ;; subtract from base so shift is + gray)) ;; tictactoe-specific (defparameter *gray-lookup* (let ((grayhash (make-hash-table))) (loop for i from 0 to #3r222222222 do (setf (gethash i grayhash) (to-gray-vec 3 9 i))) grayhash)) (defparameter *degray-lookup* (reverse-hash-table *gray-lookup* :test 'equalp)) (export 'sub-map) (defun sub-map (seq map) "Substitutes elements in seq according to hashtable ht. Keys and vals of ht must be disjoint." (let ((el (concatenate 'list (remove-duplicates seq))) (copy (copy-seq seq)) (mapper (case (type-of map) (cons #'(lambda (x) (cdr (assoc x map)))) (hash-table #'(lambda (x) (gethash x map))) (otherwise (error "Error in sub-map."))))) (loop for e in el do (when (funcall mapper e) (setf copy (substitute (funcall mapper e) e copy)))) copy)) (export 'sub-assoc) (defun sub-assoc (seq al) (let ((el (concatenate 'list (remove-duplicates seq))) (copy (copy-seq seq))) (loop for e in el do (setf copy (substitute (assoc e al) e copy))) copy)) (export 'shuffle) (defun shuffle (seq) (sort seq #'(lambda (x y) (declare (ignore x y))(= 0 (random 2))))) (defun n-rnd (low high &key (n 4)) "Returns a list of n distinct random numbers between low and high." (let ((r '())) (declare (type fixnum low high n)) (declare (optimize speed)) (when (< (- high low) n) (error "Error in n-rnd: interval too small: infinite loop")) (loop (when (= (length r) n) (return r)) (setf r (remove-duplicates (cons (+ low (random high)) r)))))) ;; a helper: (defun sieve-of-eratosthenes (maximum) "sieve for odd numbers" ;; taken from Rosetta Code. (cons 2 (let ((maxi (ash (1- maximum) -1)) (stop (ash (isqrt maximum) -1))) (let ((sieve (make-array (1+ maxi) :element-type 'bit :initial-element 0))) (loop for i from 1 to maxi when (zerop (sbit sieve i)) collect (1+ (ash i 1)) and when (<= i stop) do (loop for j from (ash (* i (1+ i)) 1) to maxi by (1+ (ash i 1)) do (setf (sbit sieve j) 1))))))) (defun pospart (n) (if (< n 0) 0 n)) (defun ! (n) "Just like C's -- except that 0 will not be interpreted as false in CL." (if (= n 0) 1 0)) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; pretty printing (defun hrule (&optional (stream *standard-output*)) (format stream "-----------------------------------------------------------------------------~%")) (defun nil0 (n) (if (null n) 0 n)) (defun func->string (func) (flet ((nil+1 (n) (if (null n) 0 (1+ n)))) (let* ((fm (format nil "~a" func)) (i (mismatch fm "#<FUNCTION __")) (o (subseq fm i (1- (length fm)))) (plain (subseq o (nil+1 (position #\: o :from-end t))))) #+sbcl plain #+clisp (subseq plain 0 (position #\space plain))))) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; data processing tools ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defun split-at-label (str) (let ((lastcomma-idx (position #\, str :from-end t))) (cons (subseq str 0 lastcomma-idx) (subseq str (1+ lastcomma-idx))))) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; List processing ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; from Rosetta Code ;; Memoization Macro for dynamic programming (defmacro mem-defun (name args body) (let ((hash-name (gensym))) `(let ((,hash-name (make-hash-table :test 'equal))) (defun ,name ,args (or (gethash (list ,@args) ,hash-name) (setf (gethash (list ,@args) ,hash-name) ,body)))))) ;; Longest common subsequence (mem-defun lcs (xs ys) (labels ((longer (a b) (if (> (length a) (length b)) a b))) (cond ((or (null xs) (null ys)) nil) ((equal (car xs) (car ys)) (cons (car xs) (lcs (cdr xs) (cdr ys)))) (t (longer (lcs (cdr xs) ys) (lcs xs (cdr ys))))))) ;; from Paul Graham, On Lisp (defun flatten (x) (labels ((rec (x acc) (cond ((null x) acc) ((atom x) (cons x acc)) (t (rec (car x) (rec (cdr x) acc)))))) (rec x nil))) (defun circularp (list) "Checks to see if a list is circular." ;; from stackoverflow (loop for tortoise on list for hare on (cdr list) by #'cddr thereis (eq tortoise hare))) (export 'de-ring) (defun de-ring (ring) (let ((idx 0)) (loop for cell on (cdr ring) do (incf idx) (when (eq cell ring) (return))) (subseq ring 0 idx))) (defun copy-circ (circle) (circular (copy-seq (de-ring circle)))) (defun circlen (circ) (length (de-ring circ))) (defun subcirc (circ i j) (values (subseq circ i (if (< j i) (+ j (circlen circ)) j)) (subseq circ j (if (< i j) (+ i (circlen circ)) i)))) (defun circular (list) (setf *print-circle* t) (setf (cdr (last list)) list)) (defun make-iter (list) (lambda () (pop list))) (defun rnd (integer) (if (zerop integer) 0 (random integer))) (export 'pick) (defmacro pick (seq) `(elt ,seq (random (length ,seq)))) (defun timestring () (let ((day-names '("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday"))) (multiple-value-bind (second minute hour date month year day-of-week dst-p tz) (get-decoded-time) (declare (ignore dst-p)) (format nil ";; It is now ~2,'0d:~2,'0d:~2,'0d on ~a, ~d/~2,'0d/~d (GMT~@d)" hour minute second (nth day-of-week day-names) date month year (- tz))))) (defun guard-val (val minval maxval) "Formats values for registers: guards against overflow, and type casts." ;;(declare (type rational val minval maxval)) (let ((sign (if (< val 0) -1 1))) ;;(declare (type rational sign)) (the real (cond ((zerop val) val) ((< (abs val) minval) (* sign minval)) ((> (abs val) maxval) (mod val maxval)) (t val))))) (defun safemod (x y) (if (zerop y) y (mod x y))) (defun square (x) (expt x 2))
8,308
Common Lisp
.lisp
213
31.464789
100
0.514876
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
75ee58b7406241b1d1ec252c90733a6f5accc5a9a8cfad022f56754f29fce4de
16,826
[ -1 ]
16,827
genlin.lisp
oblivia-simplex_genlin/genlin.lisp
;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; ___ ___ _ _ _ ___ _ _ ;; / __| __| \| | | |_ _| \| | ;; | (_ | _|| .` | |__ | || .` | ;; \___|___|_|\_|____|___|_|\_| Linear Genetic Programming Engine ;; ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (in-package :genlin) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Execution: interface between genetic components and virtual machine ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (export 'execute-creature) (defun execute-creature (crt &key (input) (output *out-reg*) (debug nil)) (case (creature-typ crt) ((:alpha) (execute-pack crt :input input :output output :debug debug)) (otherwise (unless (creature-eff crt) (setf (creature-eff crt) (remove-introns (creature-seq crt)))) (execute-sequence (creature-eff crt) :stack () :input input :output output :debug debug)))) (defun execute-pack (alpha-crt &key (input) (output *out-reg*) (debug *debug*)) (let ((pack-reg ;; should store as a constant. (loop for i from 0 to (1- (length (creature-pack alpha-crt))) collect i)) (choice)) ;; let the delegation task use a distinct register, if available, ;; by setting its output register to the highest available R/W reg. (unless (creature-eff alpha-crt) (setf (creature-eff alpha-crt) (remove-introns (creature-seq alpha-crt) :output pack-reg))) (assert input) (setf choice (register-vote (execute-sequence (creature-eff alpha-crt) :debug debug :input input :output pack-reg))) (when debug (format t "~%<<<| DELEGATING TASK TO UNDERLING ~D |>>>~%~%" choice)) (execute-sequence (creature-eff (elt (creature-pack alpha-crt) choice)) :debug debug :input input :output output))) ;; (defun execute-queen (queen &key input ;; hive ;; (worker-output *out-reg*) ;; (queen-output '(0)) ;; (debug nil)) ;; (unless (creature-eff queen) ;; (setf (creature-eff queen) ;; (remove-introns (creature-seq queen) :output queen-output))) ;; (execute-sequence ;; workers should already have their effs sorted out ;; (creature-eff (elt (island-deme hive) ;; (mod (abs (floor ;; (car ;; (execute-sequence (creature-eff queen) ;; :input input ;; :output queen-output ;; :debug debug ;; :stack (creature-seq queen))))) ;; (length (island-deme hive)))))) ;; :input input ;; :output worker-output ;; :debug debug ;; :stack (creature-seq queen)) ;; no good. underlings are a totally chaotic arrangement. ;; far too sensitive to noise. different approach needed. packs. ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; debugging functions ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defun dbg (&optional on-off) (case on-off ((on) (setf *debug* t)) ((off) (setf *debug* nil)) (otherwise (setf *debug* (not *debug*))))) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Functions related to fitness measurement ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defun get-fitfunc () *fitfunc*) (defun get-out-reg () *out-reg*) (defun set-fitfunc (&optional (name *fitfunc-name*)) (print *fitfunc-name*) (print name) (setf *fitfunc* (case name ((:n-ary-prop-vote) #'fitness-n-ary-classifier) ((:detection-rate) #'fitness-dr) ((:worst-dr) #'fitness-worst-dr) ((:accuracy) #'fitness-acc) ((:avg-acc-dr) #'fitness-avg-acc-dr) (otherwise (error "FITFUNC NICKNAME NOT RECOGNIZED. MUST BE ONE OF THE FOLLOWING: :N-ARY-PROP-VOTE, :DETECTION-RATE, :ACCURACY, :AVG-ACC-DR."))))) (defun init-fitness-env (&key training-hashtable testing-hashtable) "Works sort of like a constructor, to initialize the fitness environment." (set-out-reg) (set-fitfunc) (setf *training-hashtable* training-hashtable) (setf *testing-hashtable* testing-hashtable)) ;; DO NOT TINKER WITH THIS ANY MORE. (defun sigmoid-error(raw goal) (let ((divisor 8)) (flet ((sigmoid (x) (tanh (/ x divisor)))) (/ (abs (+ (sigmoid raw) goal)) 2)))) ;; design a meta-gp to evolve the sigmoid function? (defun fitness-binary-classifier-1 (crt &key island (ht *training-hashtable*)) "Fitness is gauged as the output of a sigmoid function over the output in register 0 times the labelled value of the input (+1 for positive, -1 for negative." (declare (ignore island)) (if (null *out-reg*) (setf *out-reg* '(0))) ;; (unless (> 0 (length (creature-eff crt))) ;; (setf (creature-eff crt) ;; assuming eff is not set, if fit is not. ;; (remove-introns (creature-seq crt) :output '(0)))) (let ((results (loop for pattern being the hash-keys in ht collect (sigmoid-error (car (execute-creature crt :input pattern :output '(0) )) ;; raw (gethash pattern ht))))) ;; goal (/ (reduce #'+ results) (length results)))) (defun fitness-binary-classifier-2 (crt &key island (ht *training-hashtable*)) (declare (ignore island)) (if (null *out-reg*) (setf *out-reg* '(0))) ;; (unless (> 0 (length (creature-eff crt))) ;; (setf (creature-eff crt) ;; assuming eff is not set, if fit is not. ;; (remove-introns (creature-seq crt) :output *out-reg*))) (let ((hit 0) (miss 0)) (loop for pattern being the hash-keys in ht using (hash-value v) do (let ((f ;; shooting in the dark, here. (tanh (/ (car (execute-creature crt :input pattern :output *out-reg*)) 300)))) (if (> (* f v) .5) (incf hit) (incf miss)))) (if (zerop miss) 1 (/ hit (+ hit miss))))) (defun fitness-binary-classifier-3 (crt &key island (ht *training-hashtable*)) "Measures fitness as the proportion of the absolute value contained in the 'correct' register to the sum of the values in registers 0 and 1. Setting R0 for negative (-1) and R1 for positive (+1)." (declare (ignore island)) (if (null *out-reg*) (setf *out-reg* '(0 1))) ;; (unless (> 0 (length (creature-eff crt))) ;; (setf (creature-eff crt) ;; assuming eff is not set, if fit is not. ;; (remove-introns (creature-seq crt) :output '(0 1 2)))) (fitness-n-ary-classifier crt :val-transform #'(lambda (x) (if (< x 0) 0 1)) :ht ht :island island)) ;; In Linear Genetic Programming, the author suggests using the ;; sum of two fitness measures as the fitness: ;; This classifier needs a little bit of tweaking. ;; REFACTOR: use one of the per-case functions ;; try to avoid the abs thing. (defun fitness-ternary-classifier-1 (crt &key (ht *training-hashtable*) island) "Where n is the target register, measures fitness as the ratio of Rn to the sum of all output registers R0-R2 (wrt absolute value)." (declare (ignore island)) (if (null *out-reg*) (setf *out-reg* '(0 1 2))) ;; (unless (> 0 (length (creature-eff crt))) ;; (setf (creature-eff crt) ;; assuming eff is not set, if fit is not. ;; (remove-introns (creature-seq crt) :output '(0 1 2)))) (let ((acc 0)) (loop for pattern being the hash-keys in ht using (hash-value i) do (let ((output (execute-creature crt :input pattern :output *out-reg*))) (incf acc (divide (abs (nth i output)) (reduce #'+ (mapcar #'abs output)))))) (/ acc (hash-table-count *training-hashtable*)))) ;; move this up to the fitness section: ;; if lexicase individuals aren't assigned a "fitness score", this may ;; break some parts of the programme -- which should be easy enough to ;; patch, once we see what they are. (defun register-vote (output &key (comparator #'>) (pre #'abs)) "Return the index of the register with the highest or lowest value." (assert output) (reduce #'(lambda (x y) (if (funcall comparator (funcall pre (nth x output)) (funcall pre (nth y output))) x y)) *out-reg*)) ;; -- boolean returning per-cases -- (defun per-case-binary (crt case-kv &optional island) "Returns a boolean." (declare (ignorable island)) (cond ((and *case-storage* (solved? (car case-kv) crt island)) t) (:DEFAULT (let ((output (execute-creature crt :output *out-reg* :input (car case-kv)))) (cond ((> (* (car output) (cdr case-kv)) 0) T) (:DEFAULT NIL)))))) (defun per-case-n-ary (crt case-kv &optional island) "Returns a boolean." (declare (ignorable island)) (if (and *case-storage* (solved? (car case-kv) crt island)) t ;; Kludge: we shouldn't have to TEST to see if this is a number! (and (numberp (cdr case-kv)) ;; some garbage is getting in via :balanced sp (= (cdr case-kv) (register-vote (execute-creature crt :output *out-reg* :input (car case-kv)) :comparator #'> :pre #'abs))))) ;; -- real returning per-cases -- (defun per-case-n-ary-proportional (crt case-kv &key (island) (out *out-reg*)) "Case-kv is a cons of key and value from hashtable." (declare (ignorable island)) (cond ((solved? (car case-kv) crt island) 1) (t (let ((output (execute-creature crt :output out :input (car case-kv)))) (values (divide (elt output (register-vote output :comparator #'>)) (reduce #'+ (mapcar #'abs output))) (cond ((> (* (abs (nth (cdr case-kv) output)) (length output)) (reduce #'+ output)) 1) (:DEFAULT 0))))))) (defun fitness-avg-acc-dr (crt &key (ht *training-hashtable*)) (unless (creature-cm crt) (compute-cmatrix crt :ht ht)) ;; updates cm fields in crt (avg (cmatrix->accuracy (creature-cm crt)) (cmatrix->detection-rate (creature-cm crt)))) (defun fitness-dr (crt &key (ht *training-hashtable*)) (unless (creature-cm crt) (compute-cmatrix crt :ht ht)) (cmatrix->detection-rate (creature-cm crt))) (defun fitness-worst-dr (crt &key (ht *training-hashtable*)) (unless (creature-cm crt) (compute-cmatrix crt :ht ht)) (cmatrix->worst-detection-rate (creature-cm crt))) (defun fitness-acc (crt &key (ht *training-hashtable*)) (unless (creature-cm crt) (compute-cmatrix crt :ht ht)) (cmatrix->accuracy (creature-cm crt))) (defun fitness-n-ary-classifier (crt &key (ht *training-hashtable*) (val-transform #'(lambda (x) x))) "Where n is the target register measures fitness as the ratio of Rn to the sum of all output registers R0-R2 (wrt absolute value)." ;; (unless (> 0 (length (creature-eff crt))) ;; (setf (creature-eff crt) ;; assuming eff is not set, if fit is not. ;; (remove-introns (creature-seq crt) :output *out-reg*))) (let ((acc1 0) ;; proportional (acc2 0) ;; first-past-the-post (w1 0.4) (w2 0.6)) (loop for pattern being the hash-keys in ht using (hash-value i) do (multiple-value-bind (a1 a2) (per-case-n-ary-proportional crt (cons pattern (funcall val-transform i))) ;; could introduce fitness sharing here. (incf acc1 a1) (incf acc2 a2))) (+ (* w1 (/ acc1 (hash-table-count ht))) (* w2 (/ acc2 (hash-table-count ht)))))) (defun fitness (crt &key (island) (ht *training-hashtable*) (fitfunc *fitfunc*)) "Measures the fitness of a specimen, according to a specified fitness function." (refresh-sample-if-needed island) (unless (creature-fit crt) (setf (creature-fit crt) (funcall fitfunc crt :ht ht :sample (island-sample island))) (loop for parent in (creature-parents crt) do (cond ((> (creature-fit crt) (creature-fit parent)) (incf (getf *records* :fitter-than-parents))) ((< (creature-fit crt) (creature-fit parent)) (incf (getf *records* :less-fit-than-parents))) (t (incf (getf *records* :as-fit-as-parents)))))) (creature-fit crt)) ;; there needs to be an option to run the fitness functions with the testing hashtable. ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Genetic operations (variation) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defun imutate-flip (inst) "Flips a random bit in the instruction." (declare (type fixnum inst)) (logxor inst (ash 1 (random *wordsize*)))) ;; Some of these mutations are destructive, some are not, so we'll ;; rig each of them to return the mutated sequence, and we'll treat ;; them as if they were purely functional, and combine them with an ;; setf to mutate their target. (defun smutate-comp (seq) ;; smutate-insert with bias towards complementary instructions (let ((shuffle-ops (shuffle (copy-seq *complementary-ops*)))) (flet ((rnd-inst-w-op (op) (logior (ash (random (expt 2 (- *wordsize* *opcode-bits*))) *opcode-bits*) (op->opcode op)))) (loop for idx from 0 to (1- (length seq)) do (let ((inst.pair nil)) (cond ((setf inst.pair (assoc (op? (elt seq idx)) shuffle-ops)) (if (> idx 0) (setf (elt seq (random idx)) (rnd-inst-w-op (cdr inst.pair))) (setf seq (concatenate 'vector (vector (rnd-inst-w-op (cdr inst.pair))) seq))) (return)) ((setf inst.pair (rassoc (op? (elt seq idx)) shuffle-ops)) (if (= idx (1- (length seq))) (setf (elt seq (+ idx (random (- (length seq) idx)))) (rnd-inst-w-op (car inst.pair))) (setf seq (concatenate 'vector seq (vector (rnd-inst-w-op (car inst.pair)))))) (return)) (t nil)))) seq))) (defun smutate-swap (seq) "Exchanges the position of two instructions in a sequence." (declare (type (simple-array integer) seq)) (and *debug* (print "smutate-swap")) (let* ((len (length seq)) (i (random len)) (j (random len)) (tmp (elt seq i))) (setf (elt seq i) (elt seq i)) (setf (elt seq j) tmp)) seq) (defun smutate-insert (seq) "Doubles a random element of seq." (declare (type (simple-array integer) seq)) (let ((idx (random (length seq)))) (and *debug* (print "smutate-append")) (setf seq (concatenate 'vector (subseq seq 0 idx) (vector (elt seq idx)) (subseq seq idx (min ;; fixed? *max-len* (length seq))))) seq)) ;; there was an unchecked code bloat problem here. (defun smutate-grow (seq) "Doubles a random element of seq." (declare (type (simple-array integer) seq)) (and *debug* (print "smutate-append")) (setf seq (concatenate 'vector seq (vector (random (expt 2 *wordsize*))))) (subseq seq 0 (min (length seq) *max-len*))) (defun smutate-shrink (seq) "Removes a random element of seq." (declare (type (simple-array integer) seq)) (and *debug* (print "smutate-shrink")) (cond ((>= (length seq) (max 3 *min-len*)) (let* ((tocut (random (length seq))) (newseq (concatenate 'vector (subseq seq 0 tocut) (subseq seq (1+ tocut))))) newseq)) (t seq))) (defun smutate-imutate (seq) "Applies imutate-flip to a random instruction in the sequence." (declare (type (simple-array integer) seq)) (and *debug* (print "smutate-imutate")) (let ((idx (random (length seq)))) (setf (elt seq idx) (imutate-flip (elt seq idx)))) seq) (defparameter *mutations* (vector #'smutate-insert #'smutate-shrink #'smutate-imutate)) (defparameter *rare-mutations* (vector #'smutate-swap #'smutate-comp)) (defun random-mutation (seq) (declare (type (simple-array integer) seq)) (let ((mutation (if (< (random 1.0) 0.2) (pick *rare-mutations*) (pick *mutations*)))) (funcall mutation seq))) (defun maybe-mutate (seq mutation-rate) (declare (type (simple-array integer) seq)) (if (< (random 1.0) mutation-rate) (random-mutation seq) seq)) (defun shufflefuck-1pt (p0 p1) "Crossover operator. Works just like it sounds." ;; just replaced the old, two point, zero-growth crossover ;; with one-point crossover that allows growth. (declare (type creature p0 p1)) (declare (optimize (speed 1))) (let* ((mates (shuffle (list p0 p1))) (mother (creature-seq (car mates))) (father (creature-seq (cadr mates))) (idx0 (random (length mother))) (idx1 (random (length father))) (children)) (push (concatenate 'vector (subseq mother 0 idx0) (subseq father idx1)) children) (push (concatenate 'vector (subseq father 0 idx1) (subseq mother idx0)) children) (mapcar #'(lambda (genome) (make-creature :seq (subseq genome 0 (min (length genome) *max-len*)))) children))) (defun shufflefuck-2pt-constant (p0 p1) "Crossover operator. Works just like it sounds." (declare (type creature p0 p1)) (declare (optimize (speed 1))) (let* ((p00 (creature-seq p0)) (p01 (creature-seq p1)) (parents (sort (list p00 p01) #'(lambda (x y) (< (length x) (length y))))) (father (car parents)) ;; we trim off the car, which holds fitness (mother (cadr parents)) ;; let the father be the shorter of the two (r-align (random 2)) ;; 1 or 0 (offset (* r-align (- (length mother) (length father)))) (daughter (copy-seq mother)) (son (copy-seq father)) (idx0 (random (length father))) (idx1 (random (length father))) (minidx (min idx0 idx1)) (maxidx (max idx0 idx1)) (children)) (setf (subseq daughter (+ offset minidx) (+ offset maxidx)) (subseq father minidx maxidx)) (setf (subseq son minidx maxidx) (subseq mother (+ offset minidx) (+ offset maxidx))) ;; (format t "mother: ~a~%father: ~a~%daughter: ~a~%son: ~a~%" ;; mother father daughter son) (setf children (list (make-creature :seq son) (make-creature :seq daughter))))) ;; run remove-intron naively, but (a) pass seq as stack to execute-sequence and (b) have instructions like LOD, STO, etc. operate on stack? (defun metamutate (mut) (if (< (random 1.0) *metamutation-rate*) (min 1 (max 0 (+ mut (* (if (= 0 (random 2)) 1 -1) *metamutation-step*))))) mut) (defun clone (p0 &optional (p1 nil)) (declare (ignorable p1)) (let ((offspring)) (push (make-creature :seq (copy-seq (creature-seq p0))) offspring) (when p1 (push (make-creature :seq (copy-seq (creature-seq p1))) offspring)))) (defun pack-mingle (alpha1 alpha2) "Destructively mingles the two packs, preserving alphas and size." (let ((underlings (shuffle (concatenate 'list (creature-pack alpha1) (creature-pack alpha2)))) (num (length (creature-pack alpha1)))) (setf (creature-pack alpha1) (subseq underlings 0 num) (creature-pack alpha2) (subseq underlings num)))) (export 'mate) (defun mate (p0 p1 &key (island nil) (genealogy *track-genealogy*) (output-registers *out-reg*) (sex *sex*) (single nil) ;; kludge. restructure func (mingle-rate *mingle-rate*)) (declare (ignorable island) (ignorable p1)) (let* ((mating-func (case sex ((:2pt) #'shufflefuck-2pt-constant) ((:1pt) #'shufflefuck-1pt) (otherwise #'clone))) (offspring (if single (clone p0) (funcall mating-func p0 p1)))) ;; sexual reproduction ;; PACK MINGLING (when (and (eq :alpha (creature-typ p0)) (eq :alpha (creature-typ p1))) ;;(< (random 1.0) mingle-rate)) (setf (creature-pack (car offspring)) (creature-pack p0) (creature-pack (cadr offspring)) (creature-pack p1)) (when (and (< (random 1.0) mingle-rate)) ;; (< (pack-coverage p0 island) 1) ;; (< (pack-coverage p1 island) 1) (apply #'pack-mingle offspring)) ;; let there be a chance for each underling to continue to ;; mutate, but divide this chance among the underlings, to ;; reduce step size. (loop for cub in offspring do (loop for underling in (creature-pack cub) do (setf (creature-seq underling) (maybe-mutate (creature-seq underling) (/ (creature-mut underling) (length (creature-pack cub)))))))) ;; inheritance of attributes ;; (when sex (loop for child in offspring do ;; now, let the mutation rate be linked to each creature, and ;; potentially mutate, itself. (setf (creature-id child) (random-name)) (setf (creature-mut child) ;; baseline: avg of parents' muts (metamutate (/ (+ (creature-mut p0) (creature-mut p1)) 2))) (setf (creature-seq child) (maybe-mutate (creature-seq child) (creature-mut child))) (setf (creature-typ child) (creature-typ p0)) (setf (creature-eff child) (remove-introns (creature-seq child) :output output-registers));; NB (setf (creature-home child) (if island (island-id island) 666)) (loop for parent in (list p0 p1) do (when (equalp (creature-eff child) (creature-eff parent)) (setf (creature-fit child) (creature-fit parent)))) (setf (creature-gen child) (1+ (max (creature-gen p0) (creature-gen p1)))) (when genealogy (setf (creature-parents child) (list p0 p1)))) ;; if we had a reference to the island handy, here, we could update ;; island coverage as well. ;; but there's really no need, since solved? does its look-up by creature-seq ;; not by the entire creature. could quotient this by remove-introns, come to ;; think of it. offspring)) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Selection functions ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defun solved? (exemplar creature island) "Returns nil if the creature has not solved that exemplar, on this island." (and *case-storage* (gethash (creature-seq creature) (gethash exemplar (island-coverage island))))) (defun record-case (exemplar creature island) ;; can we afford to maintain a set of hashes of creatures who have solved each ;; problem, globally per island? See if this can be done more cheaply than creature-cas ;; and then get rid of any mention of creature-cas entirely. (unless (solved? exemplar creature island) (setf (gethash (creature-seq creature) (gethash exemplar (island-coverage island))) T))) ;; we're now using island-coverage as a hashtable of hashtables. ;; HT1: exemplar -> hashtable of creatures that solved that exemplar ;; HT2: creature -> T (defun fit-in-list (lst &key (comparator #'>)) (reduce #'(lambda (x y) (if (funcall comparator (nil0 (creature-fit x)) (nil0 (creature-fit y))) x y)) lst)) (defun get-a-creature-who-solved-the-hardest (isle) "A greedy parent selection function, to be used, ideally, in conjunction with a stochastic selector, like f-lexicase." (let ((seqs (loop for crt being the hash-keys in (car (sort (remove-if #'(lambda (x) (zerop (hash-table-count x))) ;; ignore empty tables (loop for crtset being the hash-values in (island-coverage isle) collect crtset)) #'(lambda (x y) (if (< (hash-table-count x) ;; sorting function (hash-table-count y)) x y)))) collect crt))) (mapcar #'(lambda (x) (find x (island-deme isle) ;; should be deme or packs :key #'creature-seq :test #'equalp)) seqs))) ;; seems inefficient. no need to sort the entire set when we just want the min (defun cmatrix->accuracy (cmatrix) (divide (loop for i below (car (array-dimensions cmatrix)) sum (aref cmatrix i i)) (loop for i below (expt (car (array-dimensions cmatrix)) 2) sum (row-major-aref cmatrix i)))) (defun cmatrix->detection-rate (cmatrix) (/ (loop for i below (car (array-dimensions cmatrix)) sum (divide (aref cmatrix i i) ;; tp (+ (loop for j below (car (array-dimensions cmatrix)) sum (aref cmatrix j i))))) (car (array-dimensions cmatrix)))) (defun cmatrix->worst-detection-rate (cmatrix) (reduce #'min (loop for i below (car (array-dimensions cmatrix)) collect (divide (aref cmatrix i i) ;; tp (+ (loop for j below (car (array-dimensions cmatrix)) sum (aref cmatrix j i))))))) (export 'compute-cmatrix) (defun compute-cmatrix (crt &key (ht *training-hashtable*) (set t)) ;; should gauge accuracy obey the sampling policy as well? ;; doing so seems to lead to premature termination of the evolution ;; in the case of iris, at least. (let ((cmatrix (build-confusion-matrix *out-reg*))) (loop for k being the hash-keys in ht using (hash-value v) do (let ((guess (register-vote (execute-creature crt :input k :output *out-reg*)))) (incf (aref cmatrix guess v)))) (when set (setf (creature-cm crt) cmatrix)) cmatrix)) (defun balanced-sample (ht nobiggerthan) ;;max-fraction) (let ((sample-alist '()) (classquota (min (reduce #'min *label-counts*) (round (/ nobiggerthan *number-of-classes*)))) (valtally (make-hash-table :test #'equalp))) (flet ((inctally (keyval) (setf (gethash (cdr keyval) valtally) (1+ (nil0 (gethash (cdr keyval) valtally))))) (okay (keyval) (< (nil0 (gethash (cdr keyval) valtally)) classquota))) (loop for kv in (shuffle (loop for k being the hash-keys in ht using (hash-value v) collect (cons k v))) do (when (okay kv) ;; (print (gethash (cdr kv) valtally)) ;; (FORMAT T "~%~A IS ~D UNDER QUOTA ~D SO ADDING.~%~%" ;; (cdr kv) (gethash (cdr kv) valtally) classquota) (push kv sample-alist) (inctally kv))) (shuffle sample-alist)))) (defun invoke-sampling-policy (ht &key (format 'alist) (policy *sampling-policy*)) (declare (ignorable format)) ;; a stub to expand on later, if needed (case policy ((:div-by-class-num-shuffle) (subseq (shuffle (loop for k being the hash-keys in ht using (hash-value v) collect (cons k v))) 0 (ceiling (/ (hash-table-count ht) *number-of-classes*)))) ((:full-shuffle) (shuffle (loop for k being the hash-keys in ht using (hash-value v) collect (cons k v)))) ((:balanced) (balanced-sample *training-hashtable* (* (hash-table-count *training-hashtable*) *sampling-ratio*))) ((:proportional) (shuffle (loop for k being the hash-keys in (car (partition-data (sb-impl::copy-hash-table *training-hashtable*) *sampling-ratio*;; why not? :first-part-only t)) using (hash-value v) collect (cons k v)))) (:otherwise (error "Request for unimplemented sampling policy.")))) (defun refresh-sample-if-needed (island &key (ht *training-hashtable*) (sp *sampling-policy*)) (when (or (not (island-sample island)) (= 0 (mod (island-era island) ;; when full gen elapsed (/ (length (or (island-packs island) (island-deme island))) 2)))) (setf (island-sample island) (invoke-sampling-policy ht :format 'alist :policy sp)))) (defun f-lexicase (island &key (per-case #'per-case-n-ary)) "Note: per-case can be any boolean-returning fitness function." (let* ((cases (copy-seq (island-sample island))) (candidates (copy-seq (or (island-packs island) (island-deme island)))) (next-candidates candidates) (worst (list (pick candidates) (pick candidates)))) (labels ((case-eval (crt cas cases-left) (declare (ignorable cases-left)) ;; kludge (cond ((funcall per-case crt cas island) (when *case-storage* (record-case (car cas) crt island)) T) (:DEFAULT NIL)))) (loop while (and (> (length next-candidates) 2) cases) do (let ((the-case (pop cases))) (setf candidates next-candidates) (setf next-candidates (remove-if-not #'(lambda (x) (case-eval x the-case cases)) candidates)) (unless (>= (length worst) 2) ;; somewhat better way to get worst (push (car (set-difference candidates next-candidates)) worst)))) ;; (when (null candidates) ;; (setf candidates ;; (list (elt (island-deme island) ;; (random (length (island-deme island))))))) (values (subseq candidates 0 2) worst)))) ;; return just one parent (export 'lexicase!) (defun lexicase! (island) ;; make elitism a probability, instead of a boolean "Selects parents by lexicase selection." ;; stub, ex (let ((per-case (if (= (length *out-reg*) 1) #'per-case-binary #'per-case-n-ary)) (population (if (island-packs island) (island-packs island) (island-deme island)))) ;; (popsize (if (island-packs island) ;; (length (island-packs island)) ;; (length (island-deme island))))) (refresh-sample-if-needed island :ht *training-hashtable* :sp *sampling-policy*) (multiple-value-bind (best-pair worst-pair) (f-lexicase island :per-case per-case) (let ((best-one (car best-pair)) (best-two (cadr best-pair)) (worst-one (car worst-pair)) (worst-two (cadr worst-pair))) ;; a bit of a kludge: lacking any reliable and efficient way of ;; extracting a fitness score from f-lexicase, we'll just measure ;; accuracy the old fashioned way, but only for the f-lex winners. ;; fitness, as such, will not be used for selection, but only for ;; gauging the success of the evolution, and the choice of (best) (loop for selected in (list best-one best-two) do (setf (creature-fit selected) (or (creature-fit selected) (funcall *fitfunc* selected)))) ;; ranking fitness by detection rate, which seems more to the point ;; than accuracy in most applications of lexicase, but this should ;; be parameterizable by the user. (update-best-if-better best-one island) (update-best-if-better best-two island) (let ((children (mate best-one best-two :island island :genealogy *track-genealogy*))) (assert (not (some #'null children))) (mapc #'(lambda (x) (setf (creature-home x) (island-id island))) children) (nsubst (car children) worst-one (island-deme island) :test #'equalp) (nsubst (cadr children) worst-two (island-deme island) :test #'equalp) ;; get rid of the creatures disposed of (when *case-storage* (loop for worst in (list worst-one worst-two) do (bury-cases worst island))) children))))) (defun update-best-if-better (crt island) ;; NB: When using lexicase selection, because island-best preserves a ;; reference to, and not just a copy of, the island's best, the fitness ;; of "best" may perplexingly fluctuate. This is to be expected. ;; But since numbers are passed by value, the logger will only record ;; the fitness of the island best at the time it was logged. (when (and (eq crt (island-best island)) (/= (creature-fit crt) (cdar (funcall (island-logger island))))) (funcall (island-logger island) (cons (island-era island) (creature-fit crt)))) (when (> (nil0 (creature-fit crt)) (nil0 (creature-fit (island-best island)))) ;; (FORMAT T "~F IS BETTER THAN ~F~%" ;; (creature-fit crt) (creature-fit (island-best island))) (if (eq :alpha (creature-typ crt)) (FORMAT T "**** PACK NEW BEST ON ISLAND ~A: FIT = ~5,2F ****~%" (roman (creature-home crt)) (creature-fit crt))) (setf (island-best island) crt) (funcall (island-logger island) (cons (island-era island) (creature-fit crt))))) (defun tournement2! (island &key (tournement-size 4)) "Tournement selction function: selects four combatants at random from the population provide, and lets the two fittest reproduce. Their children replace the two least fit of the four. Disable genealogy to facilitate garbage-collection of the dead, at the cost of losing a genealogical record." (let* ((deme (island-deme island)) (parents) (children) (thedead) (lots (sort (n-rnd 0 (length deme) :n tournement-size) #'<)) (lucky (subseq lots 0 2)) (unlucky (subseq lots (- tournement-size 2)))) (mapc #'fitness deme) (setf deme (fitsort-deme deme)) (update-best-if-better (car deme) island) (setf parents (mapcar #'(lambda (x) (elt deme x)) lucky)) (setf thedead (mapcar #'(lambda (x) (elt deme x)) unlucky)) ;; (FORMAT T "FIT OF PARENTS: ~A~%FIT OF THEDEAD: ~A~%" ;; (mapcar #'creature-fit parents) ;; (mapcar #'creature-fit thedead)) (setf children (apply #'(lambda (x y) (mate x y :island island)) parents)) (mapc #'(lambda (crt idx) (setf (elt (island-deme island) idx) crt)) children unlucky) children)) (export 'tournement!) (defun tournement! (island &key (genealogy *track-genealogy*) (fitfunc *fitfunc*)) "Tournement selction function: selects four combatants at random from the population provide, and lets the two fittest reproduce. Their children replace the two least fit of the four. Disable genealogy to facilitate garbage-collection of the dead, at the cost of losing a genealogical record." (labels ((popgetter (isle) (or (island-packs isle) (island-deme isle))) (popsetter (isle p) (if (island-packs isle) (setf (island-packs isle) p) (setf (island-deme isle) p)))) (let ((population) (combatants)) (setf (island-deme island) (shuffle (island-deme island)) population (cddddr (popgetter island)) ;;(island-deme island)) combatants (subseq (popgetter island) 0 4)) ;;(subseq (island-deme island) 0 4 )) (loop for combatant in combatants do (unless (creature-fit combatant) (fitness combatant :island island :fitfunc fitfunc))) (let* ((ranked (sort combatants #'(lambda (x y) (< (creature-fit x) (creature-fit y))))) (best-in-show (car (last ranked))) (parents (cddr ranked)) (children (apply #'(lambda (x y) (mate x y :island island :genealogy genealogy)) parents))) (update-best-if-better best-in-show island) ;; Now replace the dead with the children of the winners (mapc #'(lambda (x) (setf (creature-home x) (island-id island))) children) (loop for creature in (concatenate 'list parents children) do (push creature population)) (popsetter island population) (island-best island))))) (defun spin-wheel (wheel top) "A helper function for f-roulette." (let ((ball (if (> top 0) (random (float top)) (progn (print "*** ALERT: ZERO TOP IN SPIN-WHEEL ***") 0))) ;; hopefully this doesn't happen often. (ptr (car wheel))) (loop named spinning for slot in wheel do (when (< ball (car slot)) (return-from spinning)) (setf ptr slot)) ;; each slot is a cons pair of a float and creature (cdr ptr))) ;; extract the creature from the slot the ptr lands on (defun f-roulette (island &key (genealogy t)) "Generational selection function: assigns each individual a probability of mating that is proportionate to its fitness, and then chooses n/2 mating pairs, where n is the size of the population, and returns a list of the resulting offspring. Turn off genealogy to save on memory use, as it will prevent the dead from being garbage-collected." (let* ((population (island-deme island)) (tally 0) (popsize *population-size*) ;;(popsize (length population)) (wheel (loop for creature in population collect (progn (let ((f (float (fitness creature)))) (update-best-if-better creature island) (incf tally f) (cons tally creature))))) ;; the roulette wheel is now built (breeders (loop for i from 1 to popsize collect (spin-wheel wheel tally))) (half (/ popsize 2)) ;; what to do when island population is odd? (children) (mothers (subseq breeders 0 half)) (fathers (subseq breeders half popsize)) (broods (mapcar #'(lambda (x y) (mate x y :genealogy genealogy :island island)) mothers fathers))) (setf children (apply #'concatenate 'list broods)) (mapc #'(lambda (x) (setf (creature-home x) (island-id island))) children) children)) (export 'greedy-roulette!) (defun greedy-roulette! (island) "New and old generations compete for survival. Instead of having the new generation replace the old, the population is replaced with the fittest n members of the union of the old population and the new (as resulting from f-roulette). Changes the population in place. Takes twice as long as #'roulette!" (let ((popsize (length (island-deme island)))) (setf (island-deme island) (subseq (sort (concatenate 'list (island-deme island) (f-roulette island)) #'(lambda (x y) (> (fitness x) (fitness y)))) 0 popsize)))) (export 'roulette!) (defun roulette! (island) "Replaces the given island's population with the one generated by f-roulette." (setf (island-deme island) (f-roulette island))) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Population control ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; a more generic, and just as efficient, version is in auxiliary.lisp ;; (defun de-ring (island-ring) ;; (subseq island-ring 0 (island-of (car island-ring)))) (defun bury (crt island) (bury-cases crt island) (bury-parents crt)) (defun bury-cases (crt island) "Free some memory when burying a creature." (loop for crtset being the hash-values in (island-coverage island) do (remhash crt crtset))) (defun bury-parents (crt) (setf (creature-parents crt) nil)) (defun extract-seqs-from-island-ring (island-ring) "Returns lists of instruction-vectors representing each creature on each island. Creatures dwelling on the same island share a list." (mapcar #'(lambda (x) (mapcar #'(lambda (y) (creature-seq y)) (island-deme x))) (de-ring island-ring))) (defun fitsort-deme (deme &key (fraction 1)) (flet ((nil0 (n) (if (null n) 0 n))) (let* ((ratio (if (rationalp fraction) fraction 1/1)) (population (if (< ratio 1) (shuffle (copy-seq deme)) (copy-seq deme))) (num (floor (* ratio (length population)))) (to-sort (subseq deme 0 num)) (not-to-sort (subseq deme num))) (concatenate 'list (sort to-sort #'(lambda (x y) (> (nil0 (creature-fit x)) (nil0 (creature-fit y))))) not-to-sort)))) (defun reorder-demes (island-ring &key (greedy t)) "Shuffles the demes of each island in the ring, or fitsorts a fraction of the deme and places the fittest at the top." (loop for isle in (de-ring island-ring) do (with-mutex ((island-lock isle)) (setf (island-deme isle) (if greedy (fitsort-deme (island-deme isle) :fraction greedy) (shuffle (island-deme isle))))))) ;; now chalk-full of locks. (defun migrate (island-ring &key (emigrant-fraction 1/10) (greedy *greedy-migration*)) "Migrates a randomly-populated percentage of each island to the preceding island in the island-ring. The demes of each island are shuffled in the process." (let* ((island-pop (length (island-deme (car island-ring)))) (emigrant-count (floor (* island-pop emigrant-fraction))) (buffer)) (reorder-demes island-ring :greedy greedy) (setf buffer (subseq (island-deme (car island-ring)) 0 emigrant-count)) (loop ;; migrate the emigrants counterclockwise around the island-ring for (isle-1 isle-2) on island-ring for i from 1 to (1- (island-of (car island-ring))) do (with-mutex ((island-lock isle-1)) (with-mutex ((island-lock isle-2)) ;; (sb-thread:grab-mutex (island-lock isle-1)) ;; (sb-thread:grab-mutex (island-lock isle-2)) (setf (subseq (island-deme isle-1) 0 emigrant-count) (subseq (island-deme isle-2) 0 emigrant-count))))) ;; (sb-thread:release-mutex (island-lock isle-1)) ;; (sb-thread:release-mutex (island-lock isle-2))) ;; (sb-thread:grab-mutex (island-lock (elt island-ring (1- (island-of (car island-ring)))))) (with-mutex ((island-lock (elt island-ring (1- (island-of (car island-ring)))))) (setf (subseq (island-deme (elt island-ring (1- (island-of (car island-ring))))) 0 emigrant-count) buffer)) (sb-ext:gc :full t) ;; maybe this will help? island-ring)) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defstruct pier crowd lock) (export '*pier*) (defparameter *pier* (make-pier :crowd '() :lock (sb-thread:make-mutex :name "pier-lock"))) (defparameter *island-capacity* (floor (/ *population-size* *number-of-islands*))) (defparameter *m-counter* 0) ;; not ready for deployment yet. figure out what's meant by CASable places. (export 'migrate-freely) (defun migrate-freely (island &key (pier *pier*) (emigrant-fraction *migration-size*) (greedy *greedy-migration*)) (assert (listp (island-deme island))) (with-mutex ((pier-lock pier) :wait-p t :timeout 1) (cond ((and (>= (length (island-deme island)) *island-capacity*) (= 0 (mod (island-era island) *migration-rate*))) (setf (island-deme island) (fitsort-deme (island-deme island) :fraction greedy)) (loop repeat (* (length (island-deme island)) emigrant-fraction) do (incf *m-counter*) (push (pop (island-deme island)) (pier-crowd pier))) (setf (pier-crowd pier) (shuffle (copy-seq (pier-crowd pier))))) ((= (floor (/ *migration-rate* 2)) (mod (island-era island) *migration-rate*)) (loop while pier while (< (length (island-deme island)) *island-capacity*) do (incf *m-counter*) (and ;;*debug* (FORMAT T "== MIGRATING CREATURE FROM ISLAND ~A TO ISLAND ~A ==~%" (roman (creature-home (car (pier-crowd pier)))) (roman (island-id island)))) (push (pop (pier-crowd pier)) (island-deme island))))))) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defun init-cases-covered (ht) (let ((cov (make-hash-table :test #'equalp))) (loop for k being the hash-keys in ht do (setf (gethash k cov) (make-hash-table :test #'equalp))) cov)) (defun population->islands (population number-of-islands) "Takes a population list and returns a circular list of 'islands' -- structs that contain portions of the initial population in 'demes', along with a handful of other attributes. Note that this list is circular, and so it must be cut with the de-ring function before applying, say, mapcar or length to it, in most cases." (let ((i 0) (islands (loop for i from 0 to (1- number-of-islands) collect (make-island :id i :of number-of-islands :era 0 ;; stave off <,> errors w null crt :best (make-creature :fit 0) :coverage (if *case-storage* (init-cases-covered *training-hashtable*)) :logger (make-logger) :lock (sb-thread:make-mutex :name (format nil "isle-~d-lock" i)))))) (loop for creature in population do ;; allocate pop to the islands (unless (null creature) ;; shouldn't be an issue, but is, so: hack (let ((home-isle (mod i number-of-islands))) (setf (creature-home creature) home-isle) (push creature (island-deme (elt islands home-isle))) (incf i)))) (circular islands))) ;; circular is defined in auxiliary.lisp ;; it forms the list (here, islands) into a circular linked list, by ;; setting the cdr of its last element as a pointer to its car. (defun islands->population (island-ring) (apply #'concatenate 'list (mapcar #'(lambda (x) (island-deme x)) (de-ring island-ring)))) (export 'random-name) (defun random-name () "produces a random symbol, to be used as an identifier, following a vaguely Urbit-like naming scheme." (let ((consonants "BCDFGHJKLMNPQRSTVWXZ") (vowels "AEIOUY")) (labels ((syl () (concatenate 'string (list (pick consonants) (pick vowels) (pick consonants))))) (intern (concatenate 'string (syl) "-" (syl) (syl)))))) (defun spawn-sequence (len) (concatenate 'vector (loop repeat len collect (random *max-inst*)))) (defun spawn-creature (len) (make-creature :seq (spawn-sequence len) :gen 0 :id (random-name) :mut *mutation-rate*)) (export 'init-population) (defun init-population (popsize slen &key (number-of-islands 4)) (let ((adjusted-popsize (+ popsize (mod popsize (* 2 number-of-islands))))) ;; we need to adjust the population size so that there exists an integer ;; number of mating pairs on each island -- so long as we want roulette to ;; work without a hitch. (population->islands (loop for i from 0 to (1- adjusted-popsize) collect (spawn-creature (+ *min-len* (random slen)))) number-of-islands))) (export 'release-all-locks) (defun release-all-locks (island-ring) "Mostly for running from the REPL after aborting the programme." (sb-thread:release-mutex -migration-lock-) (loop for island in (de-ring island-ring) do (sb-thread:release-mutex (island-lock island)))) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Data gathering and reporting ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; (defun best-of-all (island-ring) ;; (let ((best-so-far (make-creature :fit 0))) ;; (loop for isle in (de-ring island-ring) do ;; (if (> (nil0 (creature-fit (island-best isle))) ;; (creature-fit best-so-far)) ;; (setf best-so-far (island-best isle)))) ;; ;; you could insert a validation routine here ;; ;; (setf *best* best-so-far) ;; cause of race condition? ;; best-so-far)) (export 'best) (defun best () (island-best (reduce #'(lambda (x y) (if (> (creature-fit (island-best x)) (creature-fit (island-best y))) x y)) (de-ring +island-ring+)))) (defun make-stopwatch () (let ((start-time 0)) (lambda (&optional arg) (case arg ((set) (setf start-time (get-universal-time))) (otherwise (- (get-universal-time) start-time)))))) (defun make-logger () (let ((log (list (cons 0 0)))) ;; prevents a "nil is not a number" error (lambda (&optional (entry nil)) (cond ((eq entry 'CLEAR) (setf log '())) (entry (push entry log)) (t log))))) (defparameter *records* '()) (defun reset-records () (setf *records* '(:fitter-than-parents 0 :less-fit-than-parents 0 :as-fit-as-parents 0))) (defun print-params2 () "Prints major global parameters, and some statistics, too." (hrule) (format t "[+] STAT INTERVAL: ~D~%" *stat-interval*) (format t "[+] VIRTUAL MACHINE: ~A~%" *machine*) (format t "[+] INSTRUCTION SIZE: ~d bits~%" *wordsize*) (format t "[+] # of RW REGISTERS: ~d~%" (expt 2 *destination-register-bits*)) (format t "[+] # of RO REGISTERS: ~d~%" (expt 2 *source-register-bits*)) (format t "[+] PRIMITIVE OPERATIONS: ") (loop for i from 0 to (1- (expt 2 *opcode-bits*)) do (format t "~a " (func->string (elt *operations* i)))) (format t "~%[+] POPULATION SIZE: ~d~%" *population-size*) (format t "[+] NUMBER OF ISLANDS: ~d~%" (island-of (car +island-ring+))) (format t "[+] MIGRATION RATE: ONCE EVERY ~D CYCLES~%" *migration-rate*) (format t "[+] MIGRATION SIZE: ~D~%" *migration-size*) (format t "[+] MIGRATION ELITISM: ~D~%" *greedy-migration*) (format t "[+] REPRODUCTION: ~A (~A)~%" (if *sex* :sexual :asexual) *sex*) (format t "[+] MUTATION RATE: ~d~%" *mutation-rate*) (format t "[+] METAMUTATION RATE: ~d~%" *metamutation-rate*) (format t "[+] PACK FORMATION: ~A~%" (if *packs* "YES" "NO")) (format t "[+] MAX SEQUENCE LENGTH: ~d~%" *max-len*) (format t "[+] MAX STARTING LENGTH: ~d~%" *max-start-len*) (format t "[+] # of TRAINING CASES: ~d~%" (hash-table-count *training-hashtable*)) (format t "[+] # of TEST CASES: ~d~%" (hash-table-count *testing-hashtable*)) ;; (format t "[+] FITNESS FUNCTION: ~s~%" (get-fitfunc)) (format t "[+] NUMBER OF CLASSES: ~D~%" (funcall =label-scanner= 'count)) (format t "[+] SELECTION FUNCTION: ~s~%" *method*) (format t "[+] OUTPUT REGISTERS: ~a~%" *out-reg*) (hrule)) (defun print-params (&optional (stream *standard-output*)) (hrule stream) (loop for tweakable in *tweakables* do (format stream "[+] ~A: ~A~%" tweakable (symbol-value tweakable))) (format stream "[+] *FITFUNC*: ~A~%" *fitfunc*) (hrule stream)) (defun print-fitness-by-gen (logger &key (stream *standard-output*)) (flet ((.*. (x y) (if (numberp y) (* x y) NIL))) (let ((l (funcall logger))) (loop for (e1 e2) on l by #'cddr for i from 1 to 5 do (format stream "~c~d:~c~5,4f %~c~c~d:~c~5,4f %~%" #\tab (car e1) #\tab (.*. 100 (cdr e1)) #\tab #\tab (car e2) #\tab (.*. 100 (cdr e2))))))) (defun opcode-census (population &key (stream *standard-output*)) (let* ((buckets (make-array (expt 2 *opcode-bits*))) (instructions (reduce #'(lambda (x y) (concatenate 'list x y)) (mapcar #'creature-seq population))) (sum (length instructions))) (loop for inst in instructions do (incf (elt buckets (ldb (byte *opcode-bits* 0) inst)))) (loop repeat (/ (length buckets) 2) for x = 0 then (+ x 2) for y = 1 then (+ y 2) do (format stream "~C~A: ~4D~C(~5,2f %)~C" #\tab (func->string (elt *operations* x)) (elt buckets x) #\tab (* 100 (divide (elt buckets x) sum)) #\tab) (format stream "~C~A: ~4D~c(~5,2f %)~%" #\tab (func->string (elt *operations* y)) (elt buckets y) #\tab (* 100 (divide (elt buckets y) sum)))))) (defun percent-introns (crt) (if (null crt) 0 (float (* (divide (length (remove-if-not #'intron? (creature-eff crt))) (length (creature-eff crt))) 100)))) ;; start using this instead, for statistics (defun avg-property-population (population prop-p) (apply #'avg (mapcar prop-p population))) (defun average-intron-rate (population) (avg-property-population (remove-if-not #'creature-eff population) #'percent-introns)) (defun get-total-population (island-ring) (apply #'concatenate 'list (mapcar #'island-deme (de-ring island-ring)))) (defun proportion-native-population (island) (flet ((native-p (x) (= (nil0 (creature-home x)) (nil0 (island-id island))))) (divide (length (remove-if-not #'native-p (island-deme island))) (length (island-deme island))))) (defun print-statistics (island-ring &key (stream *standard-output*) (stopwatch #'(lambda () :inactive))) (mapc #'(lambda (x) (print-statistics-for-island x :stream stream)) (de-ring island-ring)) (hrule stream) (format stream "BEST: ~F % FROM ISLE ~A ~A * ~D SEC. INTO ~A ON ~A~%" (* 100 (creature-fit (best))) (roman (creature-home (best))) (if (creature-pack (best)) (format nil "(PACK)") "") (funcall stopwatch) (func->string *method*) *dataset*) (hrule stream) ;; (unless (creature-cm (best)) ;; (compute-cmatrix (best))) (when (creature-cm (best)) (print-confusion-matrix (creature-cm (best)) stream) (hrule stream))) (defun print-statistics-for-island (island &key (stream *standard-output*)) ;; eventually, we should change *best* to list of bests, per deme. ;; same goes for logger. (hrule stream) (let ((intron-rate (average-intron-rate (island-deme island))) (alpha-intron-rate (average-intron-rate (island-packs island))) (average-length (divide (reduce #'+ (mapcar #'(lambda (x) (length (creature-seq x))) (island-deme island))) (length (island-deme island)))) (average-length-of-alphas (if (island-packs island) (apply #'avg (mapcar #'(lambda (x) (length (creature-seq x))) (island-packs island))) 0))) (format stream " *** STATISTICS FOR ISLAND ~A AT ERA ~D ***~%" (roman (island-id island)) (island-era island)) (hrule stream) (format stream "[*] DEVELOPMENTAL STAGE: ~A~%" (if (island-packs island) "PACKS" "INDIVIDUALS")) (format stream "[*] PERCENT NATIVE: ~5,2F %~%" (* 100 (proportion-native-population island))) (format stream "[*] SELECTION METHOD ON ISLAND: ~A~%" (func->string (island-method island))) (format stream "[*] BEST FITNESS SCORE ACHIEVED ON ISLAND: ~5,4f %~%" (* 100 (creature-fit (island-best island)))) (format stream "[*] AVERAGE FITNESS~A ON ISLAND: ~5,2f %~%" (if (island-packs island) " OF UNDERLINGS" "") (* 100 (apply #'avg (remove-if #'null (mapcar #'creature-fit (island-deme island)))))) (when (island-packs island) (format stream "[*] AVERAGE FITNESS OF PACKS ON ISLAND: ~5,2f %~%" (* 100 (apply #'avg (remove-if #'null (mapcar #'creature-fit (island-packs island))))))) (format stream "[*] BEST FITNESS BY GENERATION: ~%") (print-fitness-by-gen (island-logger island) :stream stream) (format stream "[*] AVERAGE SIMILARITY TO BEST: ~5,2f %~%" (* 100 (likeness-to-specimen (island-deme island) (island-best island)))) (format stream "[*] STRUCTURAL INTRON FREQUENCY: ~5,2f %~%" intron-rate) (when *case-storage* (let ((numcases (hash-table-count *training-hashtable*))) (format stream "[*] CREATURES TO SOLVE HARDEST CASE OF ~D: ~D~%" numcases (difficulty-check island :reducer #'min) ) (format stream "[*] CREATURES TO SOLVE EASIEST CASE OF ~D: ~D~%" numcases (difficulty-check island :reducer #'max) ) (format stream "[*] AVERAGE NUMBER OF CREATURES TO SOLVE EACH CASE: ~5,2F~%" (divide (difficulty-check island :reducer #'+) numcases)))) (format stream "[*] AVERAGE LENGTH: ~5,2F INSTRUCTIONS (~5,2F EFFECTIVE)~%" average-length (- average-length (* average-length intron-rate 1/100))) (when (island-packs island) (format stream "[*] AVERAGE LENGTH OF ALPHAS: ~5,2F INSTRUCTIONS (~5,2F EFFECTIVE)~%" average-length-of-alphas (- average-length-of-alphas (* average-length-of-alphas alpha-intron-rate 1/100)))) (format stream "[*] OPCODE CENSUS~A:~%" (if (island-packs island) " OF UNDERLINGS" "")) (if (< *population-size* 2000) (opcode-census (island-deme island) :stream stream) (format stream " POPULATION TOO LARGE TO SURVEY EFFICIENTLY.~%")) (when (island-packs island) (format stream "[*] OPCODE CENSUS OF ALPHAS:~%") (if (< *population-size* 2000) (opcode-census (island-packs island) :stream stream) (format stream " POPULATION TOO LARGE TO SURVEY EFFICIENTLY.~%"))))) (defun difficulty-check (island &key (reducer #'min)) (reduce reducer (loop for v being the hash-value in (island-coverage island) collect (hash-table-count v)))) (defun plot-fitness (island) (hrule) (format t " PLOT OF BEST FITNESS OVER GENERATIONS FOR ISLAND ~A~%" (roman (island-id island))) (hrule) (let* ((fitlog (funcall (island-logger island))) (lastgen (caar fitlog)) (row #\newline) (divisor 35) (interval (max 1 (floor (divide (nil0 lastgen) divisor)))) (scale 128) (bar-char #\X)) ;; (end-char #\x)) (format t "~A~%" fitlog) (dotimes (i (+ lastgen interval)) (when (assoc i fitlog) (setf row (format nil "~v@{~c~:*~}" (ceiling (* (- (cdr (assoc i fitlog)) .5) scale)) bar-char))) (when (= (mod i interval) 0) (format t "~5d || ~a~%" i row))) (hrule) (format t " ") (let ((x-axis 50)) (dotimes (i (floor (divide scale 2))) (if (= (safemod i (floor (divide scale 10.5))) 0) (progn (format t "~d" x-axis) (when (>= x-axis 100) (return)) (incf x-axis 10)) (format t " ")))) (format t "~%") (hrule))) (defun avg-mutation-rate (island) (divide (reduce #'+ (mapcar #'creature-mut (island-deme island))) (length (island-deme island)))) (defun print-creature (crt) (flet ((nil0 (n) (if (null n) 0 n))) (format t "FIT: ~F~%SEQ: ~A~%EFF: ~A~%MUT: ~F~%HOME: ISLAND #~D~%GEN: ~D~%" (nil0 (creature-fit crt)) (creature-seq crt) (creature-eff crt) (creature-mut crt) (nil0 (creature-home crt)) (nil0 (creature-gen crt))) (when (creature-parents crt) (format t "FITNESS OF PARENTS: ~F, ~F~%" (creature-fit (car (creature-parents crt))) (creature-fit (cadr (creature-parents crt)))) (format t "HOMES OF PARENTS: ISLAND ~D, ISLAND ~D~%" (creature-home (car (creature-parents crt))) (creature-home (car (creature-parents crt))))) (when (creature-pack crt) (format t "PACK: ~%") (hrule) (loop for c in (creature-pack crt) for i from 0 do (format t "[~D] FIT: ~F~% SEQ: ~A~%" i (creature-fit c) (creature-seq c))))) (hrule) (format t "DISASSEMBLY OF EFFECTIVE CODE:~%~%") (disassemble-sequence (creature-eff crt) :static t)) (defun genealogical-fitness-stats () (let ((sum 0)) (mapc #'(lambda (x) (if (numberp x) (incf sum x))) *records*) (loop for (entry stat) on *records* by #'cddr do (format t "~A: ~5,2F%~%" (substitute #\space #\- (symbol-name entry)) (* 100 (divide stat sum)))))) (defun print-new-best-update (island) ;; (hrule) (sb-thread:grab-mutex -print-lock-) (format t "****************** NEW BEST ON ISLAND #~d AT GENERATION ~d ******************~%" (island-id island) (island-era island)) (print-creature (island-best island)) (sb-thread:release-mutex -print-lock-)) (defun classification-report (crt dataset &key (testing t) (ht *testing-hashtable*)) (if testing (setf ht *testing-hashtable*) (setf ht *training-hashtable*)) (case dataset (:tictactoe (ttt-classification-report :crt crt :ht ht :out *out-reg*)) (otherwise (data-classification-report :crt crt :ht ht :out *out-reg*)))) (defun inst-schema-match (&rest instructions) "Returns a Holland-style schema that matches all of the instructions passed in as arguments. This will be a bitvector (an integer) with a 1 for every bit that represents a match, and a 0 for every bit that represents a clash." (ldb (byte *wordsize* 0) (apply #'logeqv instructions))) (defun seq-schema-match (seq1 seq2) (map 'list #'inst-schema-match seq1 seq2)) (defun allonesp (inst) (= inst (ldb (byte *wordsize* 0) (lognot 0)))) (defun boolean-seq-schema-match (seq1 seq2) (mapcar #'allonesp (seq-schema-match seq1 seq2))) (defun likeness (seq1 seq2) (divide (length (remove-if #'null (boolean-seq-schema-match seq1 seq2))) (max (length seq1) (length seq2)))) (defun likeness-to-specimen (population specimen) "A weak, but often informative, likeness gauge. Assumes gene alignment, for the sake of a quick algorithm that can be dispatched at runtime without incurring delays." (float (divide (reduce #'+ (mapcar #'(lambda (x) (likeness (creature-eff specimen) (creature-eff x))) (remove-if #'(lambda (x) (or (null x) (equalp #() (creature-eff x)))) population))) (length population)))) ;;(setf *stop* t) ;; (defun check-cas (exemplar crt) ;; (cond ((null (creature-cas crt)) ;; (setf (creature-cas crt) ;; (make-hash-table :test #'equalp ;; :size (hash-table-count *training-hashtable*))) ;; nil) ;; (t (gethash exemplar (creature-cas crt))))) ;; gauge-accuracy isn't a good measure, as it stands. ;; instead, go by the size of creature-cas, in lexicase. ;; but creature-cas needs to be debugged, first ;; more efficient technique: maintain a list of unsolved cases, and remove ;; them as they're solved. (defun case-coverage-helper (crt island) ;; inefficient, but let's try not to use this function ;; O(n) for n = (hash-table-count *training-hashtable*) (let ((tally (loop for v being the hash-values in (island-coverage island) collect (gethash (creature-seq crt) v)))) tally)) (defun case-coverage (crt island) (let ((tally (case-coverage-helper crt island))) ;; (find (creature-home crt) ;; +ISLAND-RING+ ;; :key #'island-id)))) (divide (length (remove-if #'null tally)) (length tally)))) ;; (defun pack-coverage (alpha island) ;; ;; a bit expensive. don't use too often, or optimize. ;; ;; it would be nice to just mapcar #'or over the case-coverage ;; (let ((tally (mapcar #' ;; (print (map 'list #'(lambda (x) (case-coverage-helper x island)) ;; (creature-pack alpha)))))) ;; (print tally) ;; (divide (length (remove-if #'null tally)) (length tally)))) (defun populate-island-with-packs (isle) ;; (loop for isle in (de-ring island-ring) do ;; (sb-thread:grab-mutex (island-lock isle)) (with-mutex ((island-lock isle)) (let ((pack-size (1- (expt 2 *destination-register-bits*)))) ;; (setf *sex* nil) (format t "ISLAND ~A IS BEING POPULATED WITH PACKS...~%" (roman (island-id isle))) (setf (island-packs isle) (loop repeat *pack-count* collect (make-creature :seq (spawn-sequence (+ *min-len* (random *max-start-len*))) :typ :alpha :gen 0 :home (island-id isle) :mut *mutation-rate* :pack (loop repeat pack-size collect (pick (island-deme isle)))))) (setf (island-method isle) *pack-method*)))) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Functions only intended to facilitate experimentation and development ;; in the REPL ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; extra ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defun grab-specimen (&key island) (let* ((isle (if island island (elt +island-ring+ (random *number-of-islands*)))) (crt (elt (island-deme isle) (random (length (island-deme isle)))))) crt)) (defun params-for-shuttle () (setf *parallel* nil) (setf *rounds* 10000) (setf *target* 1) (setf *track-genealogy* nil) (setf *stat-interval* 100) (setf *dataset* :shuttle) (setf *data-path* #p"~/Projects/genlin/datasets/shuttle/shuttle.csv") (setf *destination-register-bits* 3) (setf *source-register-bits* 4) (setf *selection-method* :lexicase)) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; The main event ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defun time-for-packs (isle) (and *packs* (not (island-packs isle)) (or (< *pack-thresh-by-fitness* (creature-fit (island-best isle))) (and *case-storage* (< *pack-thresh-by-difficulty* (difficulty-check isle :reducer #'min))) (< *pack-thresh-by-era* (island-era isle)) (have-i-plateaued? isle :span *pack-thresh-by-plateau*)))) (defun max-era (island-ring) (reduce #'max (mapcar #'island-era (de-ring island-ring)))) (defun avg-era (island-ring) (floor (reduce #'avg (mapcar #'island-era (de-ring island-ring))))) (defun sum-era (island-ring) (reduce #'+ (mapcar #'island-era (de-ring island-ring)))) (defvar -save-lock- (make-mutex :name "save-lock")) (defparameter *saved-at* 0) (defun evolve (&key (method *method*) (dataset *dataset*) (rounds *rounds*) (target *target*) (stat-interval *stat-interval*) (island-ring +island-ring+) (migration-rate *migration-rate*) (migration-size *migration-size*) (parallelize *parallel*)) ;; adjustments needed to add fitfunc param here. (setf *STOP* nil) (setf *parallel* parallelize) (mapc #'(lambda (x) (setf (island-method x) method)) (de-ring island-ring)) (let ((stopwatch (make-stopwatch)) (timereport "") (use-migration t) (correct+incorrect)) (funcall stopwatch 'set) ;;; Just putting this here temporarily: (setf timereport (with-output-to-string (*trace-output*) (time (block evolver (handler-case (loop for isle in island-ring do ;; island-ring is circular, so pop ;; will cycle & not exhaust it (labels ((time-for (interval) (= 0 (mod (sum-era +island-ring+) (* *number-of-islands* interval)))) (parallel-dispatcher () ;; (when (<= (island-era isle) ;; *rounds*) (handler-case (with-mutex ((island-lock isle) :wait-p nil) (incf (island-era isle)) (funcall (island-method isle) isle) (when (eq *migration-method* :free) (migrate-freely isle)) (sb-ext:gc)) (sb-sys:memory-fault-error () (progn (format t "ENCOUNTERED MEMORY FAULT. WILL TRY TO EXIT GRACEFULLY.~%") (setf *STOP* t))))) (serial-dispatcher () (incf (island-era isle)) (funcall (island-method isle) isle) (when (eq *migration-method* :free) (migrate-freely isle)) (sb-ext:gc)) (dispatch () (if *parallel* (sb-thread:make-thread #'parallel-dispatcher) (serial-dispatcher)))) (dispatch) (when *gc* (sb-ext:gc :full t)) ;; see if this helps with heap exhaustion (when (and (eq *migration-method* :cyclic) (time-for migration-rate)) (with-mutex (-migration-lock- :wait-p t) (princ ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") (princ " MIGRATION EVENT ") (migrate island-ring :emigrant-fraction migration-size) (format t "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~%"))) (when (time-for stat-interval) ;;(best-of-all +island-ring+) (print-statistics island-ring :stopwatch stopwatch)) (when (time-for-packs isle) (populate-island-with-packs isle) (setf use-migration nil)) (when (and (time-for *save-every*) (not (= (sum-era island-ring) *saved-at*))) (with-mutex (-save-lock- :wait-p nil) (setf *saved-at* (sum-era +island-ring+)) (format t "~%~%--- SAVING ISLAND-RING AND PARAMETERS ---~%~%") (save-all +ISLAND-RING+))) (when (or (> (creature-fit (island-best isle)) target) (time-for rounds) *STOP*) (format t "~%TARGET OF ~f REACHED AFTER ~d ROUNDS~%" target (max-era island-ring)) (return-from evolver)))) (sb-sys:interactive-interrupt () (setf *STOP* t))))))) (print-statistics +island-ring+) ;;(best-of-all island-ring) (loop for isle in (de-ring island-ring) do (plot-fitness isle)) (setf correct+incorrect (classification-report (best) dataset)) (when *track-genealogy* (genealogical-fitness-stats)) (hrule) (when (not (zerop (creature-fit (best)))) (format t " -oO( BEST SPECIMEN )Oo-~%") (hrule) (if (creature-pack (best)) (format t "PACK OF ISLAND ~A~%" (roman (creature-home (best)))) (format t "DENIZEN OF ISLAND ~A AT ERA ~D~%" (roman (creature-home (best))) (island-era (find (creature-home (best)) (de-ring +island-ring+) :key #'island-id)))) (format t "~D TESTS CLASSIFIED CORRECTLY, ~D INCORRECTLY.~%" (car correct+incorrect) (cdr correct+incorrect)) (hrule) (print-creature (best))) (format t "~%~A" timereport)) (hrule)) ;; case storage is really hard on the heap for large datasets. but we ;; don't need to store the entire exemplar. we could easily get by ;; with a unique hash of it, using a cheap hashing algo. are ;; hash-tables necessary, as opposed to sets? (I mean, hash tables ;; consisting only of keys?) ;; the problem is that there's such a huge, almost exponential maybe, ;; redundancy of data. we need a new, different data structure for ;; case storage. ;; (defun reset-best () ;; (setf *best* (make-creature :fit 0))) (defun stop () (setf *stop* t)) (defun have-i-plateaued? (island &key (span 1000)) (if (funcall (island-logger island)) (> (- (island-era island) (caar (funcall (island-logger island)))) span))) (stop) ;; Start distinguishing between true positives, false positives, true ;; negatives, false negatives in the data-classification-report ;; section. ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; tests ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defun test-execution-constancy (n) (loop for i below n do (let ((seq (spawn-sequence 30)) (result1) (result2)) (hrule) (format t "[~D] TESTING FOR SEQ = ~A~%" i seq) (setf result1 (execute-sequence seq :input #(3 4 5 6) :output '(0))) (loop repeat 10 do (setf result2 (execute-sequence seq :input #(3 4 5 6) :output '(0))) (format t "~A = ~A~%" result1 result2) (assert (equalp result1 result2)))))) (defun thyroid-params () (setf *dataset* :thyroid *data-path* "./datasets/thyroid/ann-train.lbl.csv" *testing-data-path* "./datasets/thyroid/ann-test.lbl.csv" *selection-method* :lexicase *mutation-rate* 95/100 *sex* nil *sampling-policy* :balanced *sampling-ratio* 1/3 )) (defun matrix-sum (&rest matrices) (let ((accumulator (make-array (array-dimensions (car matrices)) :initial-element 0))) (loop for m in matrices do (loop for i below (apply #'* (array-dimensions accumulator)) do (incf (row-major-aref accumulator i) (row-major-aref m i)))) accumulator)) (defun cmatrix-sum (island) (apply #'matrix-sum (mapcar #'(lambda (x) (compute-cmatrix x :ht *testing-hashtable*)) (island-deme island)))) (defun cmatrix-sum-of-island-ring (island-ring) (apply #'matrix-sum (mapcar #'cmatrix-sum (de-ring island-ring))))
83,400
Common Lisp
.lisp
1,695
36.709735
156
0.522329
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
5968f60a88b5c83bc4db6b11d75e6be882460b2ee7aacbeb8f1a284b259fdf60
16,827
[ -1 ]
16,828
stackmachine.lisp
oblivia-simplex_genlin/stackmachine.lisp
(in-package :genlin) ;;; This copy only exists for the sake of carefree tinkering. Eventually, ;;; it will be merged with r-machine.lisp, the difference between the two ;;; coming down to a choice of parameters. (defparameter *machine* :stackmachine) ;;; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ;;; STACKMACHINE differs from SLOMACHINE primarily in programme design. ;;; I've switched back from arrays to lists as the canonical code-sequence ;;; representation. I've also redesigned the way in which machine code ;;; instructions are formalized. Each instruction is now, again, a function, ;;; but a function that only takes one argument: the instruction itself, ;;; from which it extracts the necessary information using dst? src? and ;;; so on. This lets me be much more versatile with the way in which ;;; instructions operate, without having to reduce everything to the same ;;; procrustean signature, or wrap every call in an ugly, ad hoc case or ;;; cond table. Use of external lexical variables is made possible by ;;; incorporating a few free variables into these functions -- marked with ;;; the sigil '%', for easy reading. These include, at present, %seq, %reg ;;; and %stk. In order to run any of these functions, they need to be ;;; enclosed in a lexical environment in which these variables are bound, ;;; and bound to values of the expected types (%reg is an array, while ;;; %seq and %stk are lists). (Note: there's also %skip, which is a boolean. ;;; It's set to T when a jump instruction prompts a jump, and nil otherwise.) ;;; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Declaim inline functions for speed ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (declaim (inline guard-val)) (declaim (inline HLT JMP PSH PRG PEX PIN CMP LOD STO MOV DIV MUL XOR CNJ IOR PMD ADD SUB MUL JLE)) (declaim (inline exec)) ;;(declaim (inline execute-sequence)) ;; ballsy. can't believe it worked. ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defvar *operations*) (defmacro src? (inst) "Returns the source address." `(ldb *srcbits* ,inst)) (defmacro dst? (inst) "Returns the destination address." `(ldb *dstbits* ,inst)) (defmacro op? (inst) "Returns the actual operation, in the case of register ops, in the form of a function." `(aref *operations* (ldb *opbits* ,inst ))) (defmacro opc? (inst) "Returns the numerical opcode." `(ldb *opbits* ,inst)) (defmacro jmp? (inst) ;; ad-hoc-ish... ;;(declare (type (unsigned-byte 64) inst)) `(member (op? ,inst) *jump-ops-list*)) (defmacro nop? (inst) `(eq (op? ,inst) #'NOP)) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; master update function for VM parameters ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; --- Operations: these can be tweaked independently of the ;; --- fields above, so long as their are at least (expt 2 *opf*) ;; --- elements in the *operations* vector. ;; NEW STRATEGY: USE FREE VARIABLES. USE THEM LIKE YOU STOLE THEM (defvar %seq) (defvar %reg) (defvar %stk) (defvar %pc) (defvar %bin) (defvar %skip) (defvar %jmpflag) (defvar %halt) (defvar %ttl) ;;(defvar %pexflag) (defvar %cal-depth) (defmacro grd* (expr) `(guard-val ,expr *minval* *maxval*)) ;; (defun exec (inst) ;; (declare (type (unsigned-byte 64) inst)) ;; (declare (optimize (speed 3))) ;; (declare (type (vector function) *operations*)) ;; (let ((opfunc (op? inst))) ;; (declare (type function opfunc)) ;; (funcall opfunc inst))) (defmacro exec (inst) `(funcall (op? ,inst) ,inst)) (defun test-exec (inst) (let ((%reg *initial-register-state*) (%seq `(,inst)) (%stk '())) (format t "SRC: R~D = ~F~%DST: R~D = ~F~%OP: ~A~%" (src? inst) (elt %reg (src? inst)) (dst? inst) (elt %reg (dst? inst)) (func->string (op? inst))) (exec inst))) (defun MOV (inst) "Copy the contents in SRC to register DST." (declare (type (unsigned-byte 64) inst)) (setf (elt %reg (dst? inst)) (elt %reg (src? inst)))) (defun LEA (inst) "Load the SRC address argument directly into DST register." (declare (type (unsigned-byte 64) inst)) (setf (elt %reg (dst? inst)) (src? inst))) (defun DIV (inst) (declare (type (unsigned-byte 64) inst)) (setf (elt %reg (dst? inst)) (grd* (divide (elt %reg (dst? inst)) (elt %reg (src? inst)))))) (defun XOR (inst) ;; xor integer parts "Performs a bitwise XOR on SRC and DST, storing the result in DST." (declare (type (unsigned-byte 64) inst)) (setf (elt %reg (dst? inst)) (logxor (floor (elt %reg (dst? inst))) (floor (elt %reg (src? inst)))))) (defun CNJ (inst) "Performs a bitwise AND on SRC and DST, storing the result in DST." (declare (type (unsigned-byte 64) inst)) (setf (elt %reg (dst? inst)) (logand (floor (elt %reg (dst? inst))) (floor (elt %reg (src? inst)))))) (defun IOR (inst) "Performs a bitwise OR on SRC and DST, storing the result in DST." (declare (type (unsigned-byte 64) inst)) (setf (elt %reg (dst? inst)) (logior (floor (elt %reg (dst? inst))) (floor (elt %reg (src? inst)))))) (defun PMD (inst) "Performs a protected SRC MOD DST, storing the result in DST." (declare (type (unsigned-byte 64) inst)) (setf (elt %reg (dst? inst)) (if (zerop (elt %reg (dst? inst))) 0 (mod (elt %reg (src? inst)) (elt %reg (dst? inst)))))) (defun ADD (inst) "Adds the rational-valued contents of SRC and DST, storing result in DST." (declare (type (unsigned-byte 64) inst)) (setf (elt %reg (dst? inst)) (+ (elt %reg (src? inst)) (elt %reg (dst? inst))))) (defun EPT (inst) ;; unstable "Raises DST to SRC and stores in DST." (declare (type (unsigned-byte 64) inst)) (setf (elt %reg (dst? inst)) (grd* (expt (elt %reg (dst? inst)) (elt %reg (src? inst)))))) (defun LUG (inst) "LOG. But that name's taken." (declare (type (unsigned-byte 64) inst)) (setf (elt %reg (dst? inst)) (grd* (log (max 2 (elt %reg (dst? inst))) (max 2 (elt %reg (src? inst))))))) (defun SUB (inst) "Subtracts DST from SRC, storing the value in DST." (declare (type (unsigned-byte 64) inst)) (setf (elt %reg (dst? inst)) (grd* (- (elt %reg (src? inst)) (elt %reg (dst? inst)))))) (defun HLT (inst) (declare (ignore inst)) (setf %ttl 0)) (defun MUL (inst) "Multiplies SRC and DST, storing the value in DST." (declare (type (unsigned-byte 64) inst)) (setf (elt %reg (dst? inst)) (grd* (* (elt %reg (src? inst)) (elt %reg (dst? inst)))))) (defun CMP (inst) "Skip the next instruction if val in first reg <= val in second." (declare (type (unsigned-byte 64) inst)) (if (<= (elt %reg (src? inst)) (elt %reg (dst? inst))) (setf %jmpflag T))) (defun JLE (inst) "Skip the next instruction if val in first reg <= val in second." (declare (type (unsigned-byte 64) inst)) (if (<= (elt %reg (src? inst)) (elt %reg (dst? inst))) (setf %skip T))) ;; New jumping instructions (defun JMP (inst) "If %jmpflag is set, then jump forwards or backwards n lines." (let ((n (ldb (byte *wordsize* 0) (ash inst (- (1+ *opcode-bits*))))) (d (expt -1 (logand 1 (ash inst (- *opcode-bits*)))))) (when %jmpflag (setf %pc (mod (+ (* n d) %pc) (length %seq))) (setf %jmpflag nil)))) ;; changing lod/sto so that they operate on the stack instead ;; of on the code segment, so that we can recover intron detection (defun LOD (inst) "Stub. Really just here for consistent pretty printing." (declare (type (unsigned-byte 64) inst)) (setf (elt %reg (dst? inst)) (if (null %seq) 0 (elt %seq (safemod (floor (elt %reg (src? inst))) (length %stk)))))) (defun STO (inst) "Store the contents of the SRC register at the specified location in %seq" (declare (type (unsigned-byte 64) inst)) (setf (elt %seq (safemod (floor (elt %reg (dst? inst))) (length %seq))) (ldb (byte *wordsize* 0) (floor (elt %reg (src? inst)))))) (defun PRG (inst) ;; pop to register (declare (type (unsigned-byte 64) inst)) (setf (elt %reg (dst? inst)) (nil0 (pop %stk)))) (defun PSH (inst) (declare (type (unsigned-byte 64) inst)) (push (elt %reg (src? inst)) %stk)) ;; but PEX still introduces arbitrary code execution, which ;; prevents any sort of definitive intron detection -- but then, ;; does it matter? Is anything lost if introns are only approximately ;; introns, potentially activated by epigenetic factors? ;; Biology got away with it. (defun PEX (inst) ;; pop to execute (declare (ignore inst)) ;; (setf %pexflag t) (exec (floor (abs (nil0 (pop %stk)))))) (defun PIN (inst) (declare (type (unsigned-byte 64) inst)) (push (elt %seq (safemod (floor (elt %reg (src? inst))) (length %seq))) %stk)) ;; module building instructions. Focussing on using just ONE module for ;; now, but this could be extended to a linked list or array of modules. (defun BIN (inst) "Grabs an instruction (+/-) n steps away and pushes it into %bin. Fetching mechanism is relative, like JMP's jumping mechanism, as opposed to LOD and STO's absolute instruction location mechanism." (declare (type (unsigned-byte 64) inst)) (let ((n (floor (elt %reg (src? inst))))) ;; (let ((n (ldb (byte *wordsize* 0) (ash inst (- (1+ *opcode-bits*))))) ;; (d (expt -1 ;; (logand 1 (ash inst (- *opcode-bits*)))))) (unless %bin (push '() %bin)) (push (elt %seq (mod (+ n %pc) (length %seq))) (elt %bin (mod (dst? inst) (length %bin)))))) (defun NIB (inst) "Pops the top item in %bin into the DST register." (declare (type (unsigned-byte 64) inst)) (let ((thebin (when %bin (elt %bin (safemod (src? inst) (length %bin)))))) (when thebin (setf (elt %reg (dst? inst)) (pop thebin))) (setf %bin (remove-if #'null %bin)))) (defun NBN (inst) "Create a new bin, if there is room for one to be allocated (i.e. if the number of bins has not yet exceeded the maximum DST index), and push the instruction indexed by the SRC register into the bin." (declare (type (unsigned-byte 64) inst)) (let ((n (floor (elt %reg (src? inst))))) (unless (>= (length %bin) (expt 2 *destination-register-bits*)) (push '() %bin)) (push (elt %seq (mod (+ n %pc) (length %seq))) (car %bin)))) (defun CLR (inst) "Delete the topmost bin." (declare (ignore inst)) (pop %bin)) (defun CAL (inst) "Call a function that has been composed with BIN." (when %bin (incf %cal-depth) (loop for m-inst in (elt %bin (safemod (dst? inst) (length %bin))) while (and (< 0 %ttl) (not *stop*)) do ;; (print %cal-depth) (unless (or (<= %ttl 0) (> %cal-depth *max-cal-depth*) (eq (op? inst) #'BIN) (eq (op? inst) #'NIB) (eq (op? inst) #'CLR) (eq (op? inst) #'NBN)) (decf %ttl) ;; since loops can form in modules, via bin (exec m-inst))) (decf %cal-depth))) (defun NOP (inst) (declare (ignore inst))) ;; just go ahead and use free variables ;; (defun PPR (&rest args) ;; " (defun SNE (inst) (setf (elt %reg (dst? inst)) (sin (elt %reg (src? inst))))) (defun CSN (inst) (setf (elt %reg (dst? inst)) (cos (elt %reg (src? inst))))) (defun TNN (inst) (setf (elt %reg (dst? inst)) (tan (elt %reg (src? inst))))) (defun LGS (inst) (setf (elt %reg (dst? inst)) (if (zerop (elt %reg (src? inst))) 0 (log (abs (elt %reg (src? inst))))))) (defparameter *reg-ops-list* `(,#'ADD ,#'MUL ,#'SUB ,#'DIV ,#'EPT ,#'PMD ,#'XOR ,#'CNJ ,#'IOR ,#'MOV)) (defparameter *imm-ops-list* `(,#'LEA)) (defparameter *jump-ops-list* `(,#'JLE ,#'JMP ,#'CMP)) (defparameter *load-ops-list* `(,#'LOD)) (defparameter *store-ops-list* `(,#'STO)) (defparameter *absolute-ops-list* `(,#'HLT)) (defparameter *module-ops-list* `(,#'BIN ,#'NIB ,#'CLR ,#'CAL ,#'NBN)) (defparameter *stack-ops-list* `(,#'PSH ,#'PEX ,#'PRG ,#'PIN)) ;; suggestion: prepare some combos that can be selected from at runtime. ;; (using command line options, e.g.) (defparameter *slomachine-ops-list* (concatenate 'vector (subseq *reg-ops-list* 0 5) *jump-ops-list* *load-ops-list* *store-ops-list*)) (defparameter *NOP-INST* 0) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; SET THE INSTRUCTION SET HERE. ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defparameter *preferred-8bit-ops* (vector #'ADD #'SUB #'DIV #'MUL #'BIN #'CAL #'LOD #'STO)) (defparameter *operations* (vector #'ADD #'SUB #'DIV #'MUL ;; basic arithmetic #'SNE #'COS #'TNN #'LGS #'BIN #'CAL #'NBN #'CLR ;; module construction and invocation #'MOV #'STO #'LOD #'LEA ;; loading, storing, moving #'XOR #'IOR #'CNJ #'PMD ;; logical operations & bit arithmetic #'CMP #'JMP #'JLE #'HLT ;; halting and jumping #'PSH #'PRG #'PEX #'PIN ;; stack operations #'NOP #'NOP #'NOP #'NOP ;; destructive ops: clear module, halt #'NOP #'NOP #'NOP #'NOP)) ;; the rest is NOP (defun op->opcode (op) (position op *operations*)) (defparameter *complementary-ops* (list (cons #'CAL #'BIN) (cons #'LOD #'STO) ;; (cons #'CAL #'NBN) (cons #'JMP #'CMP) (cons #'PRG #'PSH) (cons #'PEX #'PIN))) (defparameter *suggested-ops-list* `(,#'ADD ,#'MUL ,#'SUB ,#'DIV ,#'LOD ,#'CAL ,#'NBN ,#'BIN ,#'PMD ,#'NIB ,#'XOR ,#'LEA ,#'PRG ,#'PSH ,#'HLT ,#'MOV)) ;; (setf *operations* ;; (remove-if #'null (concatenate 'vector ;; `(,#'NOP) ;; *reg-ops-list* ;; ;; *load-ops-list* ;; ;; *store-ops-list* ;; *stack-ops-list* ;; *jump-ops-list* ;; *imm-ops-list* ;; (loop repeat (expt 2 *opcode-bits*) ;; collect #'NOP)))) ;;(setf *operations* (coerce *suggested-ops-list* 'vector)) ;;*jump-ops-list* ;;*load-ops-list* ;;*store-ops-list*))) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defun shuffle-operations () (setf *operations* (coerce (shuffle (coerce *operations* 'list)) 'vector))) (defvar *intron-flag*) ;; this whole thing should be refactored out of slomachine and r-machine, ;; to a more central location (defun update-dependent-machine-parameters () ;; Not quite ready yet. (unless *ttl* (setf *ttl* *max-len*)) (setf *destination-register-bits* (max (ceiling (log (how-many-output-registers?) 2)) *destination-register-bits*)) (setf *source-register-bits* (max (ceiling (log (+ (how-many-input-registers?) (how-many-output-registers?)) 2)) *source-register-bits*)) (setf *wordsize* (+ *opcode-bits* *source-register-bits* *destination-register-bits*)) ;; NB: there is one extra bit past the wordsize, where the intron flag ;; is stored. we leave it outside the wordsize range so that randomly ;; generated instructions aren't marked as introns in mutations or ;; spawning functions. but double check where wordsize is used. (setf *intron-flag* (ash 1 *wordsize*)) (setf *machine-fmt* (format nil "~~~D,'0b ~~a" *wordsize*)) (setf *max-inst* (expt 2 *wordsize*)) ;; upper bound on inst size (setf *opbits* (byte *opcode-bits* 0)) (setf *srcbits* (byte *source-register-bits* *opcode-bits*)) (setf *dstbits* (byte *destination-register-bits* (+ *source-register-bits* *opcode-bits*))) (setf *default-input-reg* (concatenate 'vector (loop for i from 1 to (- (expt 2 *source-register-bits*) (expt 2 *destination-register-bits*)) collect (expt -1 i)))) (setf *default-registers* (concatenate 'vector #(0) (loop for i from 2 to (expt 2 *destination-register-bits*) collect 0 )));; (expt -1 i)))) (setf *pc-idx* (+ (length *default-registers*) (length *default-input-reg*))) (setf *initial-register-state* (concatenate 'vector *default-registers* *default-input-reg* #(0))) ;; PROGRAMME COUNTER (setf *input-start-idx* (length *default-registers*)) (setf *input-stop-idx* (+ *input-start-idx* (length *default-input-reg*)))) ;;(update-dependent-machine-parameters) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Functions for extracting fields from the instructions ;; and other low-level machine code operations. ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; history is not threadsafe. does it matter? not much, since it's ;; only used in debugging mode, when *parallel* is set to nil. (defparameter =history= (let ((hist '()) (warning t)) (lambda (&optional (entry nil)) (when (and *parallel* warning) (format t "*** WARNING: HISTORY IS NOT THREADSAFE ***~%") (format t "*** SET *PARALLEL* TO NIL WHEN DEBUGGING ***~%") (setf warning nil)) (cond ((eq entry 'FLUSH) (setf hist '())) ((eq entry 'ALL) hist) (entry (push entry hist)) (t (car hist)))))) (defun history-push-test (seq reg) (funcall =history= (cons seq reg))) (defun history-flush () (funcall =history= 'FLUSH)) (defun history-print (&optional len) (let ((h (funcall =history=))) (print (subseq h 0 len)))) (defparameter *comments* t) (defun disassemble-history (&key (all 'all) (len 1) (static nil) (comments *comments*)) "If passed a sequence in the static field, disassemble it without any reference to register states. If not, disassemble the last len entries in the history stack, tracking changes to the registers." (labels ((strip-parens (str) (remove #\( (remove #\) str))) (reg-op-comment (inst line) (format t " ;; R~D = ~F; R~D = ~F~%" (src? inst) (elt (getf line :reg) (src? inst)) (dst? inst) (elt (getf line :reg) (dst? inst)))) (jmp-op-comment (inst line) (format t " ;; R~D = ~5,2F R~D = ~5,2F, FLAG = ~A, PC = ~D~%" (src? inst) (elt (getf line :reg) (src? inst)) (dst? inst) (elt (getf line :reg) (dst? inst)) (getf line :jmpflag) (getf line :pc))) (lod-op-comment (inst line) (let* ((addr (mod (floor (elt (getf line :reg) (src? inst))) (length (getf line :seq)))) (data (elt (getf line :seq) addr)) (regnum (dst? inst))) (format t " ;; loading ~d from @~d into R~d~%" data addr regnum))) (sto-op-comment (inst line) (let* ((addr (mod (floor (elt (getf line :reg) (dst? inst))) (length (getf line :seq)))) (data (ldb (byte *wordsize* 0) (floor (elt (getf line :reg) (src? inst))))) (regnum (src? inst))) (format t " ;; STORING ~D FROM R~D IN @~D~%" data regnum addr) (when (>= addr (getf line :pc)) (format t "*** SEQUENCE REWRITING ITSELF ***~%")))) (bin-op-comment (inst line) (let ((bin (getf line :bin))) (cond ((eq #'BIN (op? inst)) (format t " ;; BINNING ~A -> ~A~%" (inst->string (car (elt %bin (safemod (dst? inst) (length bin))))) bin)) ((eq #'CAL (op? inst)) (terpri) (when bin (loop for b-inst in (elt bin (safemod (src? inst) (length bin))) do (format t "|-BIN ~D-| ~A~%" (mod (src? inst) (length bin)) (inst->string b-inst))))) ((eq #'NBN (op? inst)) (format t " ;; NEW BIN: ~A~%" bin)) (:DEFAULT (format t " ;; BIN: ~A~%" bin))))) (stk-op-comment (inst line) (let* ((stack (getf line :stk))) ;; (stack (if (null stk) '(0) stk))) (format t " ;; STACK TOP: ~A~A~%" (strip-parens (format nil "~A" (mapcar #'(lambda (x) (float (nil0 x))) (subseq stack 0 (min (length stack) 5))))) (if (> (length stack) 5) "..." "")) (when (and (not (null (car stack))) (equalp (op? inst) #'PEX)) (format t "PEX >> ~A~%" (inst->string (floor (car stack))))))) (imm-op-comment (inst line) (declare (ignore line)) (format t " ;; LOADING ~D IN R~D~%" (src? inst) (dst? inst)))) (let* ((history (funcall =history= all)) (story (if static (coerce static 'list) (reverse (subseq history 0 len))))) (loop for line in story do (let ((inst (if static line (getf line :inst)))) (format t *machine-fmt* ;; needs to be made flexible. inst (inst->string inst)) (when (and comments (not static)) (format t " (~d) " (getf line :pc)) (cond ((member (op? inst) *reg-ops-list*) (reg-op-comment inst line)) ((member (op? inst) *jump-ops-list*) (jmp-op-comment inst line)) ((member (op? inst) *load-ops-list*) (lod-op-comment inst line)) ((member (op? inst) *store-ops-list*) (sto-op-comment inst line)) ((member (op? inst) *stack-ops-list*) (stk-op-comment inst line)) ((member (op? inst) *imm-ops-list*) (imm-op-comment inst line)) ((member (op? inst) *module-ops-list*) (bin-op-comment inst line)) (t (format t " ;; ¯\_(ツ)_/¯~%")))) (if (or static (not comments)) (format t "~%")))) (if static (hrule))))) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; The engine room ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defun execute-sequence (seq &key (registers *initial-register-state* ) (input *default-input-reg*) (stack nil) (output nil) (debug nil)) "Takes a sequence of instructions, seq, and an initial register state vector, registers, and then runs the virtual machine, returning the resulting value in the registers indexed by the integers in the list parameter, output." (declare (type fixnum *input-start-idx* *pc-idx*) (type (cons integer) output) (type (simple-array integer) seq) ;;(type (or null (cons (unsigned-byte 64))) seq) (type (or null cons) stack) (type (simple-array real 1) input registers)) ;; (optimize (speed 3))) (flet ((save-state (inst &key reg seq stk bin skip pc jmpflag) (declare (type (simple-array real 1) reg) (type boolean skip) (type function =history=)) (funcall =history= (list :inst inst :reg reg :seq seq :skip skip :stk stk :bin bin :jmpflag jmpflag :pc pc)))) (let ((%seq (copy-seq seq)) ;; shouldn't be more pricey than copy (%reg (copy-seq registers)) (%pc 0) ;; why bother putting the PC in the registers? (%ttl *ttl*) (%jmpflag nil) (%skip nil) (%bin nil) (%cal-depth 0) (inst) ;; (%pexflag t) (%stk (copy-seq stack)) ;;; (seqlen (length seq)) (debugger (or debug *debug*))) ;; so that we can have our junk DNA back. (declare (type (simple-array real 1) %reg) (type boolean debugger) (ignorable %jmpflag) (type fixnum %pc)) ;; the input values will be stored in read-only %reg (setf (subseq %reg *input-start-idx* (+ *input-start-idx* (length input))) input) (loop while (< %pc (length %seq)) while (> %ttl 0) do (setf inst (aref %seq %pc)) (incf %pc) ;; not truly necessary. may suppress for speed. (decf %ttl) (cond ((or %skip (intron? inst)) (setf %skip nil)) (:DEFAULT (exec inst) (and debugger (save-state inst :reg %reg :seq %seq :bin %bin :skip %skip ;;:pexflag %pexflag :jmpflag %jmpflag :stk %stk :pc %pc) (disassemble-history))))) (mapcar #'(lambda (x) (setf x nil)) (list %bin %stk %pc %seq %reg)) (and *debug* (hrule) (history-flush)) (mapcar #'(lambda (i) (aref %reg i)) output)))) ;; :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ;; Intron Removal ;; :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: (defun mark-intron-bit (inst) (ldb (byte (1+ *wordsize*) 0) (logior inst *intron-flag*))) (defun intron? (inst) (= 1 (ash inst (- *wordsize*)))) (defun remove-introns (seq &key (output '(0))) "Filters out non-effective instructions from a sequence -- instructions that have no bearing on the final value(s) contained in the output register(s)." ;; NB: When code is r/w w LOD, STO, then remove-introns cannot be expected ;; to return reliable results. ;; we can test sensitivity of LOD/STO instructions to input. If there are ;; either no LOD/STO instructions, or if the LOD/STO instructions are in- ;; sensitive to input, then EFF can be extracted in the usual fashion. ;; Creatures whose control flow is contingent on input via LOD/STO should be ;; flagged or logged, just out of curiosity, and to gather statistics on ;; their frequency. (let ((efr output) (nopops nil) (nocmps nil) (efseq '())) ;; Until I code up a good, efficient way of finding entrons in ;; a piece of potentially self-modifying code, this will have to do: (cond (*remove-introns* (loop for i from (1- (length seq)) downto 0 do (let ((inst (elt seq i))) (cond ((and (not (nop? inst)) (or (member (dst? inst) efr) (jmp? inst))) (push (src? inst) efr) (push inst efseq)) (:DEFAULT (push (mark-intron-bit inst) efseq))))) ;; if no CMP instructions, mark all JMP instructions as introns (setf nocmps (not (some #'(lambda (x) (eq (op? x) #'CMP)) efseq))) (setf nopops (not (some #'(lambda (x) (member (op? x) `(,#'PEX ,#'PRG))) efseq))) (when (or nocmps nopops) (loop for inst in efseq do (when (and nocmps (jmp? inst)) (nsubst (mark-intron-bit inst) inst efseq)) (when (and nopops (eq (op? inst) #'PSH)) (nsubst (mark-intron-bit inst) inst efseq))))) (:DEFAULT (setf efseq seq))) (coerce efseq 'vector))) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; debugging functions ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defun print-registers (registers) (loop for i from 0 to (1- (length registers)) do (format t "R~d: ~6f ~c" i (aref registers i) #\TAB) (if (= 0 (mod (1+ i) 4)) (format t "~%"))) (format t "~%")) (defun inst->string (inst) (concatenate 'string (format nil "[~a R~d, R~d]" (func->string (op? inst)) (src? inst) (dst? inst)))) (defun disassemble-sequence (seq &key (registers *initial-register-state*) (input *default-input-reg*) (static nil)) (if static (disassemble-history :static seq) (execute-sequence seq :debug t :input input :registers registers))) (setf *stop* t)
30,915
Common Lisp
.lisp
680
35.545588
99
0.508294
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
396438bbd3df6b58fbf9d5f1251bacb5094cf856f3cd12011c84e1590f411413
16,828
[ -1 ]
16,829
r-machine.lisp
oblivia-simplex_genlin/r-machine.lisp
(in-package :genlin) (defparameter *machine* :r-machine) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; INSTRUCTION FIELDS ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; --- Adjust these 3 parameters to tweak the instruction set. --- ;; --- The rest of the parameters will respond automatically --- ;; --- but due to use of inlining for optimization, it may --- ;; --- be necessary to recompile the rest of the programme. --- ;; see if you can put the entire virtual machine in its own environment (defparameter *opcode-bits* 3 "The number of bits in an instruction used to determine the operation. Can be set to 1, 2, or 3.") ;; size (defparameter *source-register-bits* 3 "The number of bits used to calculate the source register in each instruction. 2^n readable registers will be allocated where n is the value of this parameter." ) (defparameter *destination-register-bits* 2 "The number of bits used to calculate the destination register. If left smaller than *source-register-bits* then there will be 2^(n-m) read-only registers, where n is the value of *source-register-bits* and m is the value of this parameter." ) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Declaim inline functions for speed ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (declaim (inline guard-val)) (declaim (inline MOV DIV MUL XOR CNJ DIS PMD ADD SUB MUL JLE)) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; master update function for VM parameters ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; --- Operations: these can be tweaked independently of the ;; --- fields above, so long as their are at least (expt 2 *opf*) ;; --- elements in the *operations* vector. (defun MOV (&rest args) "Copy the contents in SRC to register DST." (declare (type (or null (cons rational)) args)) (the rational (coerce (car args) 'rational))) (defun DIV (&rest args) "A divide-by-zero-proof division operator." (declare (type (or null (cons rational)) args)) (the rational (if (some #'zerop args) 0 (/ (car args) (cadr args))))) (defun XOR (&rest args) ;; xor integer parts "Performs a bitwise XOR on SRC and DST, storing the result in DST." (declare (type (or null (cons rational)) args)) (check-type args (cons rational)) (the rational (coerce (logxor (floor (car args)) (floor (cadr args))) 'rational))) (defun CNJ (&rest args) "Performs a bitwise AND on SRC and DST, storing the result in DST." (declare (type (or null (cons rational)) args)) (check-type args (cons rational)) (logand (floor (car args)) (floor (cadr args)))) (defun DIS (&rest args) "Performs a bitwise OR on SRC and DST, storing the result in DST." (declare (type (or null (cons rational)) args)) (check-type args (cons rational)) (the rational (lognot (logand (lognot (floor (car args))) (lognot (floor (cadr args))))))) (defun PMD (&rest args) "Performs a protected SRC MOD DST, storing the result in DST." (declare (type (or null (cons rational)) args)) (check-type args (cons rational)) (the rational (if (some #'zerop args) (car args) (mod (car args) (cadr args))))) (defun ADD (&rest args) "Adds the rational-valued contents of SRC and DST, storing result in DST." (declare (type (or null (cons rational)) args)) (check-type args (cons rational)) (the rational (+ (car args) (cadr args)))) (defun SUB (&rest args) "Subtracts DST from SRC, storing the value in DST." (declare (type (or null (cons rational)) args)) (check-type args (cons rational)) (- (car args) (cadr args))) (defun MUL (&rest args) "Multiplies SRC and DST, storing the value in DST." (declare (type (or null (cons rational)) args)) (check-type args (cons rational)) (* (car args) (cadr args))) (defun JLE (&rest args) ;; CONDITIONAL JUMP OPERATOR "Increments the programme counter iff X < Y." (declare (type (or null (cons rational)) args)) (check-type args (cons rational)) (if (<= (car args) (cadr args)) (1+ (caddr args)) (caddr args))) (defparameter *operations* (vector #'DIV #'MUL #'SUB #'ADD ;; basic operations (2bit opcode) #'XOR #'PMD #'CNJ #'JLE ;; extended operations (3bit opcode) #'MOV #'DIS) ;; extras, unused by default. "Instruction set for the virtual machine. Only the first 2^*opcode-bits* will be used." ) (defun shuffle-operations () (setf *operations* (coerce (shuffle (coerce *operations* 'list)) 'vector))) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Parameters for register configuration. ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defparameter *output-reg* '()) (defparameter *maxval* (expt 2 16)) ;; max val that can be stored in reg (defparameter *minval* (expt 2 -16)) ;; floor this to 0 ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Dependent Virtual Machine Vars ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defvar *default-input-reg*) (defvar *default-registers*) (defvar *pc-idx*) (defvar *initial-register-state*) (defvar *input-start-idx*) (defvar *input-stop-idx*) (defvar *wordsize*) (defvar *max-inst*) (defvar *opbits*) (defvar *srcbits*) (defvar *dstbits*) (defvar *machine-fmt*) (defun update-dependent-machine-parameters () (setf *wordsize* (+ *opcode-bits* *source-register-bits* *destination-register-bits*)) (setf *machine-fmt* (format nil "~~~D,'0b ~~a" *wordsize*)) (setf *max-inst* (expt 2 *wordsize*)) ;; upper bound on inst size (setf *opbits* (byte *opcode-bits* 0)) (setf *srcbits* (byte *source-register-bits* *opcode-bits*)) (setf *dstbits* (byte *destination-register-bits* (+ *source-register-bits* *opcode-bits*))) (setf *default-input-reg* (concatenate 'vector (loop for i from 1 to (- (expt 2 *source-register-bits*) (expt 2 *destination-register-bits*)) collect (expt -1 i)))) (setf *default-registers* (concatenate 'vector #(0) (loop for i from 2 to (expt 2 *destination-register-bits*) collect (expt -1 i)))) (setf *pc-idx* (+ (length *default-registers*) (length *default-input-reg*))) (setf *initial-register-state* (concatenate 'vector *default-registers* *default-input-reg* #(0))) ;; PROGRAMME COUNTER (setf *input-start-idx* (length *default-registers*)) (setf *input-stop-idx* (+ *input-start-idx* (length *default-input-reg*)))) (update-dependent-machine-parameters) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Functions for extracting fields from the instructions ;; and other low-level machine code operations. ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (declaim (inline src? dst? op?)) (defun src? (inst) (declare (type fixnum inst)) (declare (type (cons integer) *srcbits*)) (the unsigned-byte (ldb *srcbits* inst))) (defun dst? (inst) (declare (type fixnum inst)) (declare (type (cons integer) *dstbits*)) (the unsigned-byte (ldb *dstbits* inst))) (defun op? (inst) (declare (type fixnum inst)) (declare (type (cons integer) *opbits*)) (declare (type (simple-array function) *operations*)) (the function (aref *operations* (ldb *opbits* inst)))) (defun jmp? (inst) ;; ad-hoc-ish... (declare (type fixnum inst)) (the boolean (equalp (op? inst) #'JLE))) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defun enter-input (registers input) (let ((copy (copy-seq registers))) (setf (subseq copy *input-start-idx* (+ *input-start-idx* (length input))) input) copy)) (defun print-registers (registers) (loop for i from 0 to (1- (length registers)) do (format t "R~d: ~6f ~c" i (aref registers i) #\TAB) (if (= 0 (mod (1+ i) 4)) (format t "~%"))) (format t "~%")) (defun inst->string (inst) (concatenate 'string (format nil "[~a R~d, R~d]" (func->string (op? inst)) (src? inst) (dst? inst)))) (defun disassemble-sequence (seq &key (registers *initial-register-state*) (input *default-input-reg*) (static nil)) (hrule) (if static (disassemble-history :static seq) (execute-sequence seq :debug t :input input :registers registers)) (hrule)) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Execution procedure ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; encapsulate in its own let environment? ;; MESSY, and TOO SLOW. Try to delegate debugging output elsewhere. ;; Thoughts on how to add a stack: ;; - the tricky part is getting the stack instructions (push, pop) and ;; the stack structure to communicate. We don't want the stack to get ;; corrupted by multithreaded activity, so we should enclose it in the ;; execute-sequence environment, you'd think, but then our operations ;; can't be defined where they are now. We'd have to find a way of treating ;; the ops as macros --- macros that may inject a free stack variable ;; into the execute-sequence environment -- but then we hae to change the ;; that that they're currently called. ;; another possibility is to let each "creature" maintain its own stack, ;; as a field in its struct. This is actually pretty close to the idea of ;; each process/thread having a stack of its own. ;; Almost certainly not threadsafe. ;; the problem is sidestepped, though, by restricting its use to ;; either debugging mode (which should be single-threaded) or ;; to print jobs that are wrapped in mutexes. (defparameter =history= (let ((hist '())) (lambda (&optional (entry nil)) (cond ((eq entry 'CLEAR) (setf hist '())) (entry (push entry hist)) (t hist))))) (defun history-push-test (seq reg) (funcall =history= (cons seq reg))) (defun history-flush () (funcall =history= 'CLEAR)) (defun history-print (&optional len) (let ((h (funcall =history=))) (print (subseq h 0 len)))) (defun disassemble-history (&key (len 0) (all t) (static nil)) "If passed a sequence in the static field, disassemble it without any reference to register states. If not, disassemble the last len entries in the history stack, tracking changes to the registers." (let* ((history (funcall =history=)) (len (if all (length history) len)) (story (if static (coerce static 'list) (reverse (subseq history 0 len))))) (loop for couplet in story do (let* ((registers (if static (copy-seq *initial-register-state*) (cdr couplet))) (inst (if static couplet (car couplet)))) (format t *machine-fmt* ;; needs to be made flexible. inst (inst->string inst)) (if (not static) (format t ";; now R~d = ~f ;; PC = ~d~%" (dst? inst) (aref registers (dst? inst)) (aref registers *pc-idx*)) (format t "~%"))))) (if static (hrule))) (defun guard-val (val minval maxval) "Formats values for registers: guards against overflow, and type casts." (declare (type rational val minval maxval)) (let ((sign (if (< val 0) -1 1))) (declare (type fixnum sign)) (the rational (coerce (cond ((< (abs val) minval) (* sign minval)) ((> (abs val) maxval) (* sign maxval)) (t val)) 'rational)))) (defun execute-sequence (seq &key (registers *initial-register-state* ) (input *default-input-reg*) (output nil) (debug nil)) "Takes a sequence of instructions, seq, and an initial register state vector, registers, and then runs the virtual machine, returning the resulting value in the registers indexed by the integers in the list parameter, output." (declare (type fixnum *input-start-idx* *pc-idx*)) (declare (inline src? dst? op?)) (declare (type (cons integer) output)) (declare (type (simple-array rational 1) input registers seq)) (declare (optimize (speed 2))) (flet ((save-state (inst regs) (declare (type (simple-array *) regs)) (declare (type integer inst)) (declare (type function =history=)) (funcall =history= (cons inst regs)))) (let ((regs (copy-seq registers)) (seqlen (length seq)) (debugger (or debug *debug*))) (declare (type (simple-array rational 1) regs)) (declare (type fixnum seqlen)) (declare (type boolean debugger)) ;; the input values will be stored in read-only regs (setf (subseq regs *input-start-idx* (+ *input-start-idx* (length input))) input) ;; (PRINT INPUT) ;; (PRINT REGS) (unless (zerop seqlen) (loop do ;; (format t "=== ~A ===~%" regs) ;; Fetch the next instruction (let* ((inst (aref seq (aref regs *pc-idx*))) ;; Determine the target register (D (if (jmp? inst) *pc-idx* (dst? inst)))) ;; Increment the programme counter (incf (aref regs *pc-idx*)) ;; Perform the operation and store the result in [dst] (setf (aref regs D) (guard-val (apply (op? inst) (list (aref regs (src? inst)) (aref regs (dst? inst)) (aref regs *pc-idx*))) *minval* *maxval*)) ;; Save history for debugger (and debugger (save-state inst regs) (disassemble-history :len 1 :all nil)) (and (>= (aref regs *pc-idx*) seqlen) (return))))) (and *debug* (hrule)) (mapcar #'(lambda (i) (aref regs i)) output))))
14,732
Common Lisp
.lisp
311
39.88746
84
0.566989
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
6273cca84a503eda7d5748fb129b3868c13b0a657288be6b603e7e06eafb30d7
16,829
[ -1 ]
16,830
params.lisp
oblivia-simplex_genlin/params.lisp
(in-package #:genlin) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; types and structs ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (export 'creature) (defstruct creature id fit cm seq eff gen mut typ home parents pack) (export 'island-id) (export 'island-of) (export 'island-deme) (export 'island-best) (defstruct island id of deme packs best era logger lock coverage method sample) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defparameter *project-path* "./") (defparameter *tictactoe-path* (concatenate 'string *project-path* "datasets/TicTacToe/tic-tac-toe.data")) (defparameter *iris-path* (concatenate 'string *project-path* "datasets/Iris/iris.data")) (defvar *number-of-classes*) (defparameter *STOP* nil) (defparameter *best* nil) (defparameter *DEBUG* nil "The debugging flag. If set to T, then you will be treated to a very verbose, live disassembly of the instructions being excuted in the virtual machine, along with a few other pieces of information. Do not use in conjunction with *parallel.*") (defparameter *parallel* nil "Enables multithreading when set to T, allotting the evolutionary process on each island its own thread.") (defparameter *VERBOSE* nil) (defparameter *stat-interval* 500 "Number of cycles per verbose update on the evolutionary process.") (defparameter *dataset* :iris "Just the name for your dataset. Mostly used for labelling output, with the exception of :tictactoe, which tells the programme to use a particular data-processing module. More a hook for customizaiton than anything else.") (defparameter *data-path* (if (eq *dataset* :tictactoe) *tictactoe-path* *iris-path*) "Path to the data file. Mismatching *data-path* and *dataset* will almost certainly break something, at the moment.") ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Genetic Parameters ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (export '+ISLAND-RING+) (defvar +ISLAND-RING+) ;;(defvar +HIVE-RING+) (setf +ISLAND-RING+ '()) (export '*training-ht*) (defvar *training-ht* (make-hash-table :test 'equalp)) (export '*testing-ht*) (defvar *testing-ht* (make-hash-table :test 'equalp)) (defvar -print-lock- (sb-thread:make-mutex :name "print lock")) (defvar -migration-lock- (sb-thread:make-mutex :name "migration lock")) ;; ...................................................................... ;; Tweakables ;; ...................................................................... (defparameter *number-of-islands* 8 "Islands are relatively isolated pockets in the population, linked in a ring structure and bridged by occasional migration. Can be set to any integer > 0.") (defparameter *population-size* 800 "Remains constant throughout the evolution. Should be > 40.") (defparameter *specimens* '()) (defparameter *migration-size* 1/10 "Fraction of population that leaves one deme for the next, per migration event.") ;; percent (defparameter *migration-rate* 200 "Frequency of migrations, measured in generations.") (defparameter *migration-method* :free "Can be :FREE or :CYCLIC.") ;; stub, explain (defparameter *greedy-migration* 1 "If set to 1, migrants are always the fittest in their deme. If set to a fraction lesser than 1, then migrants will be the top *migration-size* percent of a randomly-selected *greedy-migration* fraction of the deme.") (defparameter *track-genealogy* nil "If set to T, then genealogical lineage and statistics are computed at runtime. Informative, but increases overhead.") (defparameter *min-len* 2 "The minimum creature length, measured in instructions.") ;; we want to prevent seqs shrinking to nil (defparameter *max-len* 256 "The maximum creature length, measured in instructions.") ;; max instruction length (defparameter *max-start-len* 25 "The maximum length of creatures in the initial population.") ;; max initial instruction length (defparameter *training-ratio* 4/5 "The ratio of training cases to total cases (the remainder being reserved for testing.") (defparameter *rounds* 10000 "The evolution will run until either a total number of mating events have elapsed on each island, or a pre-established fitness target has been reached. This determines the former.") (defparameter *target* 0.95 "The evolution will run until either a total number of mating events have elapsed on each island, or a pre-established fitness target has been reached. This determines the latter.") (defparameter *selection-method* :lexicase "Determines which selection method will be used to select the parents of each subsequent generation. Accepts as values the keywords: :tournement, :roulette, :greedy-roulette, or :lexicase.") (defparameter *method* nil);; #'tournement!) (defparameter *menu* nil "Set to t if you would like to see a menu, from which the parameters can be set.") ;; Things whose presence here reflects a want of refactoring. (defvar *fitfunc* nil) (defvar *training-hashtable* (make-hash-table :test #'equalp)) (defvar *testing-hashtable* (make-hash-table :test #'equalp)) (defvar *out-reg* '()) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Virtual Machine Parameters (Generic) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; INSTRUCTION FIELDS ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; --- Adjust these 3 parameters to tweak the instruction set. --- ;; --- The rest of the parameters will respond automatically --- ;; --- but due to use of inlining for optimization, it may --- ;; --- be necessary to recompile the rest of the programme. --- ;; see if you can put the entire virtual machine in its own environment (defparameter *opcode-bits* 3 "The number of bits in an instruction used to determine the operation. Can be set to 1, 2, 3, or 4.") ;; size (defparameter *source-register-bits* 3 "The number of bits used to calculate the source register in each instruction. 2^n readable registers will be allocated where n is the value of this parameter." ) (defparameter *destination-register-bits* 2 "The number of bits used to calculate the destination register. If left smaller than *source-register-bits* then there will be 2^(n-m) read-only registers, where n is the value of *source-register-bits* and m is the value of this parameter." ) ;;(defparameter *flag-bits* 2) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Parameters for register configuration. ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defparameter *output-reg* '()) (defparameter *maxval* (expt 2 16)) ;; max val that can be stored in reg (defparameter *minval* (expt 2 -16)) ;; floor this to 0 ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Dependent Virtual Machine Vars ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defvar *default-input-reg*) (defvar *default-registers*) (defvar *pc-idx*) (defvar *initial-register-state*) (defvar *input-start-idx*) (defvar *input-stop-idx*) (defvar *wordsize*) (defvar *max-inst*) (defvar *opbits*) (defvar *srcbits*) (defvar *dstbits*) (defvar *flgbits*) (defvar *machine-fmt*) ;; where should these functions live? With data? With params? (defun how-many-input-registers? () (let ((num 0)) (loop for k being the hash-keys in *training-hashtable* do (setf num (length k)) (return)) num)) (defun how-many-output-registers? () ;; a bit hackish, but the idea here is that if an n-ary dataset is used ;; then label-scanner will have a list to return; if it's a binary set ;; then label-scanner will have a null list (let ((s (funcall =label-scanner= 'get))) (if s (length (funcall =label-scanner= 'get)) 1))) ;; =label-scanner= lives in data-filer (defvar *ops* '(:DIV :MUL :SUB :ADD :PMD :JLE :LOD :STO) "The user may supply a list of opcode mnemonics if to reconfigure the virtual machine's primitive instruction set.") (defvar *opstring* nil "The user may supply a list of opcode mnemonics to reconfigure the virtual machine's primitive instruction set. These operations should be entered as keywords, separated by commas, with no spaces. (UNSTABLE.)") (defvar *testing-data-path* nil "Specify an independent testing dataset. If left as nil, then the main dataset will be partitioned according to --training-ratio.") (defparameter *mutation-rate* 3/10 "Chance of mutation per spawning event, expressed as percentage.") (defparameter *metamutation-rate* 1/10 "If over 0, then the rate of mutation is localized for each creature, and is itself susceptible to mutation.") (defparameter *metamutation-step* 1/50) (defparameter *split-data* t "Set to nil to use the same dataset for both training and testing. I won't judge. *TRAINING-RATIO* is ignored if this is to set to nil.") (defparameter *case-storage* nil "For efficiency at the cost of memory allocation, set to T and have creatures store hash-tables of the testing cases they are able to correctly classify. Principally for use with the Lexicase selection method.") ;; NOTE: adjustable lexicase population pool. easy to implement. may speed up ;; lexicase selection for large populations ;; could also do so with datasets, but benefits unclear ;; lexicase is doing quite badly right now. (defparameter *sex* nil ;;:1pt "One-point crossover when set to :1pt, two-point/fixed-length when set to :2pt. Asexual reproduction (cloning, with certain mutation) when set to nil.") (defparameter *mating-func* nil) (defparameter *max-pack-size* 8) (defparameter *lexicase-combatant-ratio* 1) (defparameter *params-path* nil "An parameter file can be supplied, if desired. It should consist of a series of Lisp S-expressions of the form (setf *PARAMETER-NAME* parameter-value)") (defparameter *last-params-path* "LAST-PARAMS.SAV" "File in which to store the parameters used on the last run.") (defparameter *lexicase-pool-ratio* 1) (defparameter *scale-data* nil "Apply scaling function to keys in the hashtable, when using numeric data. Accepts a keyword value of: :linear-transform, or :mean-variance. Data used as-is if set to nil.") (defparameter *verbose-report* t "Print a thorough report of GP results on the testing set. You might want to disable this for very large datasets.") (defparameter *monitor-coverage* t) (defparameter *pack-count* 100 "The number of packs to establish on an island, once pack-formation begins.") (defparameter *pack-thresh-by-era* 2000 "If *PACKS* is T, then pack-formation will begin on an island once it surpasses this era.") (defparameter *pack-thresh-by-difficulty* 100 "If *PACKS* and *CASE-STORAGE* are both set to T, then pack formation will begin on an island when it has witnessed *PACK-THRESH-BY-DIFFICULTY* successful classifications of its most difficult (least-often-correctly-classified) case.") (defparameter *pack-thresh-by-fitness* .9 "If *PACKS* is set to T, then pack formation will begin on an island when its best fitness score surpasses *PACK-THRESH-BY-FITNESS*.") (defparameter *pack-thresh-by-plateau* 1000 "If *PACKS* is T, then pack formation will begin once an island hits a fitness plateau, understood as a span of n consecutive eras without an increase it its best fitness.") (defparameter *packs* nil) (defvar *pack-method*) (defparameter *pack-selection-method* :lexicase) (defparameter *mingle-rate* 2/3) (defparameter *lexicase-elitism* 3/4) (defparameter *remove-introns* :youbetyourass) (defparameter *records* '()) (defvar *ttl* *max-len* "How many instructions can be executed in a sequence before the execution halts? Typically set to a multiple of *max-len* ((* *max-len* 1), for example).)") (defvar *gc* nil) (defvar *max-cal-depth* 1 "Determines how many nested function calls are permitted, though CAL and BIN, in the virtual machine. What is gained in expressive power is paid for in time and island desynchronization.") (defvar *save-every* 1000 "Save the island ring every *SAVE-EVERY* rounds. Not a bad idea, so long as memory fault bugs persist.") (defparameter *restore-island-ring* nil "Loads a saved island ring from supplied path name.") (defparameter *sampling-policy* :balanced "Currently only implemented for lexicase. Accepts: :balanced, :proportional, :div-by-class-num-shuffle, :full-shuffle [STUB]") ;; (defparameter *fitness-by-detection-rate* t ;; "If set to T, then fitness will be measured in terms of detection ;; rate instead of accuracy. Currently only implemented for lexicase ;; selection.") (defparameter *fitfunc-name* :n-ary-prop-vote "Accepted values: :n-ary-prop-vote, :detection-rate, :accuracy, :avg-acc-dr.") (defparameter *sampling-ratio* 1/8) (defparameter *sampling-freq* 50) (defparameter *tweakables* '(*menu* *debug* *gc* *stat-interval* *parallel* *dataset* *data-path* *testing-data-path* *split-data* *scale-data* *fitfunc-name* *sampling-policy* *training-ratio* *sampling-ratio* *selection-method* *lexicase-combatant-ratio* *lexicase-elitism* *case-storage* ;;; case storage is buggy right now *number-of-islands* *population-size* *packs* *pack-count* *pack-thresh-by-fitness* *pack-thresh-by-era* *pack-thresh-by-difficulty* *pack-selection-method* *sex* *mutation-rate* *mingle-rate* *metamutation-rate* *migration-rate* *migration-size* *greedy-migration* *max-pack-size* *track-genealogy* *min-len* *max-len* *ttl* *max-start-len* *remove-introns* *maxval* *opstring* *opcode-bits* *operations* *source-register-bits* *destination-register-bits* *max-cal-depth* *rounds* *target* *verbose-report* *save-every* *restore-island-ring* *params-path* *last-params-path*)) (loop for tweakable in *tweakables* do (export tweakable)) ;;; IDEA: replace registers with stacks ;;; always hold at least one "anchor" element ;;; register instruction set operates on cars or pops ;;; new instruction: execstack, which executes a register ;;; advantages: intron detection?
14,876
Common Lisp
.lisp
336
40.702381
116
0.674453
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
7bb087238a30dd9526f5d414d18fe1cae48e20bcb8b53e3afa5e73fccc5c546f
16,830
[ -1 ]
16,831
rcompile.lisp
oblivia-simplex_genlin/rcompile.lisp
(load "genlin.lisp") (in-package :genlin) (setf *machine* :r-machine) (load-other-files) (sb-ext:save-lisp-and-die "R-GENLIN" :executable t :toplevel #'main)
158
Common Lisp
.lisp
5
30.6
68
0.72549
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
50b7b2159d191d464f771472df704b8c0aa253d9ba8749eb47ba8f52a89c2a74
16,831
[ -1 ]
16,832
tictactoe.lisp
oblivia-simplex_genlin/tictactoe.lisp
;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Data reading functions ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; (defpackage :genlin ;; (:use :common-lisp)) (in-package #:genlin) (defparameter *01vs+-* t) ;; -- Tic-Tac-Toe Environment) (let* ((.tictactoe-path. "/home/oblivia/Projects/genetic-exercises/genetic-linear/datasets/TicTacToe/tic-tac-toe-balanced.data") (.xob-digits. '((#\x . 2) (#\o . 1) (#\b . 0))) (.digits-xob. (mapcar #'(lambda (x) (cons (cdr x) (car x))) .xob-digits.))) (defun xobstring->numvec (xobstring) (let* ((stripped (remove-if #'(lambda (x) (char= #\, x)) xobstring)) (vec (sub-map (concatenate 'vector stripped) .xob-digits.))) vec)) (defun tictactoe->int (xobstring &key (gray t)) "Reads a csv string represenation of a tictactoe board, and returns an integer that uniquely represents that board. The integer is just the board read as a base-3 numeral, with b = 0, x = 1, o = 2." (let ((vec (xobstring->numvec xobstring))) (if gray (gethash vec *degray-lookup*) (read-from-string (concatenate 'string "#3r" (coerce (mapcar #'(lambda (x) (code-char (+ (char-code #\0) x))) (coerce vec 'list)) 'string)))))) (defun int->tictactoe (int &key (gray t)) (flet ((convert (n) (if gray (gethash n *gray-lookup*) (coerce (mapcar #'(lambda (x) (- (char-code x) (char-code #\0))) (coerce (format nil "~3r" n) 'list)) 'vector)))) (coerce (sub-map (convert int) .digits-xob.) 'string))) (defun fmt-board (string) (let* ((row " ~c | ~c | ~c ~%") (lin "---+---+---~%") (str (substitute #\space #\b string)) (board (concatenate 'string row lin row lin row))) (format nil board (char str 0) (char str 1) (char str 2) (char str 3) (char str 4) (char str 5) (char str 6) (char str 7) (char str 8)))) (defun int->board (int &key (gray t)) (format nil "~a" (fmt-board (int->tictactoe int :gray gray)))) (defun grayvec->board (vec) (int->board (aref vec 0))) (defun list->board (lis) (fmt-board (concatenate 'string (substitute #\x -1 (substitute #\b 0 (substitute #\o 1 lis)))))) (defun draw-board (key) (grayvec->board key)) (defun tictactoe-val (str) (funcall =label-scanner= str)) ;; (if (equalp str "positive") 1 ;; (if *01vs+-* 0 -1))) (defun tictactoe-hash-int (str hashtable &key (gray t)) "Converts the tictactoe string into a base-3 number, and enters it into the hashtable." (let ((keyval (split-at-label str))) (setf (gethash (vector (tictactoe->int (car keyval) :gray gray)) hashtable) (tictactoe-val (cdr keyval))))) (defun tictactoe-hash-vec (str hashtable) "Converts the tictactoe string into a list of integers over -1,0,1 and enters them into the hashtable." (let ((k (car (split-at-label str))) (v (cdr (split-at-label str)))) (setf (gethash (coerce (mapcar #'1- (eval (read-from-string (concatenate 'string "'(" (substitute #\1 #\b (substitute #\0 #\x (substitute #\2 #\o (substitute #\space #\, k)))) ")")))) 'vector) hashtable) (tictactoe-val v)))) (defun ttt-datafile->hashtable (&key (filename .tictactoe-path.) (int t) (gray t)) (format t "FILENAME: ~a~%" filename) (let ((ht (make-hash-table :test 'equalp)) (in (open filename :if-does-not-exist nil))) (when in (loop for line = (read-line in nil) while line do (if int (tictactoe-hash-int line ht :gray gray) (tictactoe-hash-vec line ht)) (and *debug* (format t "READ| ~a~%" line))) (close in)) ht)) (defun show-all-boards (&optional (int 0)) (when (<= int #3r222222222) (format t "~d = ~3r ~%~a~%" int int (int->board int)) (show-all-boards (1+ int)))) (defun ttt-classification-report (&key (crt *best*) (ht) (out '(0 1))) (data-classification-report :crt crt :ht ht :out out :artfunc #'draw-board)) ;; ;; this report function is turning into an awful piece of spaghetti code! ;; (defun ttt-classification-report (&key (crt *best*) (ht) (out '(0 1))) ;; (print-creature crt) ;; (let ((correct 0) ;; (incorrect 0) ;; (failures '()) ;; (fitf (if (equalp '(0) out) ;; 'FB1 ;; 'FB3))) ;; (labels ((deneg (n) ;; (abs n)) ;; sometimes I just drop negative numbers. ;; (val-idx (v) ;; (if (< v 0) 0 1)) ;; (fb3-correct (o v) ;; (< (deneg (elt o (val-idx v))) ;; (deneg (elt o (! (val-idx v)))))) ;; (fb1-correct (o v) ;; (> (* v (car o)) 0))) ;; (loop for k being the hash-keys in ht using (hash-value v) do ;; (let* ((i (elt k 0)) ;; (output (execute-creature crt ;; :input k ;; :output out ;; :debug t)) ;; (sum (reduce #'+ (mapcar #'deneg output))) ;; (certainties ;; (mapcar #'(lambda (x) (* (divide x sum) 100)) output))) ;; (format t "~%~a~%" (int->board i)) ;; (cond ((eq fitf 'FB1) ;; (cond ((per-case-binary crt (cons k v)) ;; (format t "CORRECTLY CLASSIFIED ~a -> ~f~%~%" ;; i (car output)) ;; (incf correct)) ;; (t ;; (format t "INCORRECTLY CLASSIFIED ~a -> ~f~%~%" ;; i (car output)) ;; (incf incorrect) ;; (push k failures)))) ;; ((eq fitf 'FB3) ;; (format t "X WINS: ~f%~%X LOSES: ~f%~%" ;; (car certainties) (cadr certainties)) ;; (cond ((fb3-correct output v) ;; (incf correct) ;; (format t "CORRECTLY CLASSIFIED~%")) ;; (t (incf incorrect) ;; (format t "INCORRECTLY CLASSIFIED: X ~s~%" ;; (if (< v 0) 'LOST 'WON)) ;; (push k failures)))))))) ;; (hrule) ;; (format t "FAILURES:~%") ;; (hrule) ;; (loop for fail in failures do ;; (format t "~%CODE ~d~%~a~%" fail (int->board (aref fail 0)))) ;; (hrule) ;; (format t "TOTAL CORRECT: ~d~%TOTAL INCORRECT: ~d~%" ;; correct incorrect) ;; (hrule) ;; (values (cons correct incorrect) ;; failures))) ;; returns failures, as a convenience for retraining (defun show-search-space (ht &key (upto #3r222222222)) (let ((y #\@) (n #\.)) (dotimes (i upto) (if (and (gethash (vector i) ht) (= (gethash (vector i) ht) 1)) (format t "~c" y) (format t "~c" n))))) (defun deterministic-ttt-eval (xobstring &key (winfor #\o)) "A deterministic, always-correct (barring bugs) tic-tac-toe evaluator, which can be used to provide more training cases for the GP." (let* ((grid (xobstring->numvec xobstring)) (streaks '((0 1 2) (3 4 5) (6 7 8) (0 3 6) (1 4 7) (2 5 8) (0 4 8) (2 4 6))) (winner nil)) (loop for streak in streaks do (let* ((in-streak (remove-duplicates (mapcar #'(lambda (x) (elt grid x)) streak))) (xobstreak (mapcar #'(lambda (y) (cdr (assoc y .digits-xob.))) in-streak))) (when (equal `(,winfor) xobstreak) (setf winner winfor ) (return)))) winner)) (defun xobstring->csv (xobstring) (let ((positive (deterministic-ttt-eval xobstring)) (xoblist (coerce xobstring 'list)) (commas '(#\, #\, #\, #\, #\, #\, #\, #\, #\,))) (concatenate 'string (flatten (mapcar #'list xoblist commas)) (if positive "positive" "negative")))) (defun endgame-generator (&key (positive 100) (negative 100)) (let ((poscount 0) (negcount 0) (results '())) (loop repeat #3r1000000000 do (let* ((int (random #3r1000000000)) (xobstring (int->tictactoe int)) (xcount (count #\x xobstring)) (ocount (count #\x xobstring))) (when (and (>= negcount negative) (>= poscount positive)) (return)) (when (and (>= xcount 3) (< (abs (- xcount ocount)) 2)) (cond ((deterministic-ttt-eval xobstring) (incf poscount) (if (<= poscount positive) (push (xobstring->csv xobstring) results))) (t (incf negcount) (if (<= negcount negative) (push (xobstring->csv xobstring) results))))))) results)) (defun write-ttt-csv (&key (filename "generated-ttt.csv") (positive 1000) (negative 1000)) (with-open-file (fd filename :direction :output) (loop for line in (endgame-generator :positive positive :negative negative) do (write-line line fd)) (close fd))) ) ;; end of tictactoe environment (setf *stop* t)
10,483
Common Lisp
.lisp
218
37.848624
201
0.460886
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
6cfac403dcd6827e3fff8c9f9fe00e99930914e33b9144c33b99c07530cce720
16,832
[ -1 ]
16,833
altcrossover.lisp
oblivia-simplex_genlin/altcrossover.lisp
;; This buffer is for notes you don't want to save, and for Lisp evaluation. ;; If you want to create a file, visit that file with C-x C-f, ;; then enter the text in that file's own buffer. (defun shufflefuck (p0 p1) (declare (type creature p0 p1)) (declare (optimize (speed 1))) (let* (;;(lp0 (length (creature-seq p0))) ;;(lp1 (length (creature-seq p1))) ;;(ovum (creature-seq p0)) ;;(sperm (creature-seq p1)) (ovum (circular (coerce (creature-seq p0) 'list))) (sperm (circular (coerce (creature-seq p1) 'list))) ;; (parents (sort (list p00 p01) #'(lambda (x y) (< (length x) (length y))))) ;; (father (car parents)) ;; we trim off the car, which holds fitness ;; (mother (cadr parents)) ;; let the father be the shorter of the two ;; (r-align (random 2)) ;; 1 or 0 ;; (offset (* r-align (- (length mother) (length father)))) (fzygote) (mzygote) (children) ;; (xx) ;; (xy) ;; (yx) ;; (yy) (ov-i (random (length (creature-seq p0)))) (ov-j (random (length (creature-seq p0)))) (sp-i (random (length (creature-seq p1)))) (sp-j (random (length (creature-seq p1)))) (genes0 (multiple-value-bind (xx xy) (subcirc ovum ov-i ov-j) (cons xx xy))) (genes1 (multiple-value-bind (yx yy) (subcirc sperm sp-i sp-j) (cons yx yy))) (setf fzygote (concatenate 'list (cdr genes0) (car genes1))) (setf mzygote (concatenate 'list (cdr genes1) (car genes0))) ;; half guessing here ;;(loop repeat ov-j do (pop fzygote)) ;;(loop repeat sp-j do (pop mzygote)) ;; (format t "mother: ~a~%father: ~a~%daughter: ~a~%son: ~a~%" ;; mother father daughter son) (setf children (list (make-creature :seq (coerce (de-ring mzygote) 'vector)) (make-creature :seq (coerce (de-ring fzygote) 'vector))))))
2,062
Common Lisp
.lisp
43
39.093023
85
0.55
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
55fca451fd3dc210f33d44b74d2c598a738e6a17ed9be7b3bf46cc76d71598f5
16,833
[ -1 ]
16,834
datafiler.lisp
oblivia-simplex_genlin/datafiler.lisp
;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; Data reading functions ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;;(defpackage :genlin ;; (:use :common-lisp)) (in-package #:genlin) ;; moved here from params. may cause bug. (defparameter =label-scanner= ;; Enumerates labels, keeping track of labels it's already seen. (let ((seen '())) (lambda (lbl) (cond ((eq lbl 'flush) (setf seen '())) ((not (member lbl seen :test #'equalp)) (push lbl seen))) (cond ((eq lbl 'get) (pop seen) (reverse seen)) ;; return seen, w/o 'get ((eq lbl 'count) (pop seen) (length seen)) (t (position lbl (reverse seen) :test #'equalp :from-end t)))))) (defun parse-numeric-csv-key (k) (coerce (mapcar #'rational (read-from-string (concatenate 'string "(" (substitute #\space #\, k) ")"))) 'vector)) (defun data-hash (line ht) (let* ((kv (split-at-label line)) (raw-k (car kv)) (raw-v (cdr kv)) (val (funcall =label-scanner= raw-v)) (key (parse-numeric-csv-key raw-k))) (setf (gethash key ht) val))) (defun set-out-reg () (setf *out-reg* (loop for i from 0 to (1- (length (funcall =label-scanner= 'get))) collect i))) (defun datafile->hashtable (&key filename (rescaler *scale-data*)) (cond ((eq *dataset* :tictactoe) (ttt-datafile->hashtable :filename filename)) (t (format t "[+] PATH TO DATA: ~a~%" filename) (let ((ht (make-hash-table :test 'equal)) (input (open filename :if-does-not-exist nil))) (when input (loop for line = (read-line input nil) while line do (data-hash line ht) (and *debug* (format t "READ| ~a~%" line))) (close input)) (case rescaler ((:mean-variance) (rescale-data ht :scaling-function #'listwise-mean-variances)) ((:linear-transform) (rescale-data ht :scaling-function #'listwise-linear-transforms)) (otherwise ht)))))) (defun attribute-string (vec) (let ((str "")) (loop for i from 1 to (length vec) do (setf str (concatenate 'string str (format nil "ATTRIBUTE ~@R:~C~F~%" i #\Tab (aref vec (1- i)))))) str)) (defun ugly-max-array (arr) (reduce #'max (loop for i in (loop for k below (apply #'* (array-dimensions arr)) collect (row-major-aref arr k)) collect i))) (defun build-confusion-matrix (classes) (make-array `(,(length classes) ,(length classes)) :initial-element 0)) (defun print-confusion-matrix (cm &optional (stream *standard-output*)) (let* ((s (ugly-max-array cm)) (names (mapcar #'string-upcase (funcall =label-scanner= 'get))) (fmt (format nil "~~~dd" (+ 2 (ceiling (log s 10))))) (longest (reduce #'max (mapcar #'length names))) (padded-names (mapcar #'(lambda (x) (concatenate 'string x (loop repeat (- longest (length x)) collect #\space))) names))) (loop for row from 0 below (car (array-dimensions cm)) do (format stream "~A " (elt padded-names row)) (loop for col from 0 below (cadr (array-dimensions cm)) do (format stream fmt (aref cm col row))) (terpri)))) ;; use the helper functions in the fitness section in here, instead. (defun data-classification-report (&key (crt *best*) (ht) (out) (verbose *verbose-report*) (artfunc #'attribute-string)) (let ((cm (build-confusion-matrix out)) (correct 0) (incorrect 0) (names (mapcar #'string-upcase (funcall =label-scanner= 'get))) (failures '())) (loop for k being the hash-keys in ht using (hash-value v) do (let* ((output (mapcar #'abs (execute-creature crt :debug verbose :input k :output out))) (vote (register-vote output)) (success (= vote v)) (certainties (mapcar #'(lambda (x) (divide x (reduce #'+ output))) output))) (incf (aref cm vote v)) ;; confusion matrix entry (if success (incf correct) (progn (incf incorrect) (push k failures))) (when verbose (hrule) (format t "~A~%" (funcall artfunc k)) (terpri) (loop for i from 0 to (1- (length output)) do (format t "CLASS ~A: ~5,2f %~%" (elt names i) (* 100 (elt certainties i)))) (cond (success (when verbose (format t "~%CORRECTLY CLASSIFIED AS ~A~%" (elt names v)))) ((not success) (when verbose (format t "~%INCORRECTLY CLASSIFIED. ") (format t "WAS ACTUALLY ~A~%" (elt names v))))) (hrule)))) (when verbose (format t " ~@(~R~) Failures:~%" (length failures)) (hrule) (loop for fail in failures do (format t "CLASS: ~A~%VECTOR: ~a~%" (elt names (gethash fail ht)) fail) (format t "~%~A" (funcall artfunc fail)) (hrule))) (format t "TOTAL CORRECT: ~d~%TOTAL INCORRECT: ~d~%" correct incorrect) (hrule) (format t "CONFUSION MATRIX: ROW = TRUE CLASS, COLUMN = GUESSED CLASS~%") (hrule) (print-confusion-matrix cm) (format t "~%DETECTION RATE: ~5,2F%~%" (* 100 (cmatrix->detection-rate cm))) (format t "ACCURACY: ~5,2F%~%" (* 100 (cmatrix->accuracy cm))) (hrule) ;; (format t "AGGREGATE CONFUSION MATRIX OF ISLAND-RING:~%~%") ;; (print-confusion-matrix (cmatrix-sum-of-island-ring +island-ring+)) (values (cons correct incorrect) failures))) ;; moved over here from genlin.lisp: (defun partition-data (hashtable ratio &key (first-part-only nil)) ;; need to modify this so that the distribution of values in the test ;; set is at least similar to the distribution of values in the training (let* ((size (hash-table-count hashtable)) (training (make-hash-table :test 'equalp)) (testing (make-hash-table :test 'equalp)) (keys (shuffle (loop for k being the hash-keys in hashtable collect k))) (vals) (keys-by-val) (portions)) (setf vals (remove-duplicates (loop for v being the hash-values in hashtable collect v))) (setf keys-by-val (loop for v in vals collect (remove-if-not #'(lambda (x) (equalp (gethash x hashtable) v)) keys))) (loop for klist in keys-by-val do (push (round (* ratio size (/ (length klist) size))) portions)) (setf portions (reverse portions)) (and *debug* (format t "TOTAL COUNT OF SPECIMENS: ~D~%CLASS COUNTS: ~A~%PORTIONS FOR TRAINING, BY CLASS: ~A~%" size (mapcar #'length keys-by-val) portions)) (loop for keylist in keys-by-val for portion in portions do (if (some #'null keylist) (format t "FOUND NULL IN ~A~%" keylist)) (loop for i from 1 to portion do (let ((k)) (setf k (pop keylist)) (setf (gethash k training) (gethash k hashtable)))) (unless first-part-only (loop for k in keylist do (setf (gethash k testing) (gethash k hashtable))))) (cons training testing))) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; is there any reason why I'm using vecs instead of lists for ;; the ht keys? (defun listwise-sums (list-of-lists &key (pre nil)) (when (null pre) (setf pre (lambda (x) x))) ;; set pre to nop if nil (reduce #'(lambda (x y) ;; create list of abs sums (mapcar #'(lambda (a b) (+ (funcall pre a) (funcall pre b))) x y)) list-of-lists)) (defun listwise-means (list-of-lists) (mapcar #'(lambda (x) (divide x (length list-of-lists))) (listwise-sums list-of-lists :pre #'abs))) (defun listwise-variances (list-of-lists) (let* ( (meanlist (listwise-means list-of-lists)) (deviations (mapcar #'(lambda (l) (mapcar #'- l meanlist)) list-of-lists)) (devmeans (listwise-means deviations)) (variancelists (loop for klist in list-of-lists collect (mapcar #'(lambda (x y) (expt (- x y) 2)) klist devmeans))) (variances (listwise-means variancelists))) variances)) (defun listwise-stddevs (list-of-lists) (mapcar #'(lambda (x) (expt x 1/2)) (listwise-variances list-of-lists))) (defun listwise-mean-variances (list-of-lists) (let ((meanlist (listwise-means list-of-lists)) (devilist (listwise-stddevs list-of-lists))) (loop for list in list-of-lists collect (mapcar #'(lambda (x y z) (divide (- x y) z)) list meanlist devilist)))) (defun listwise-maxima (list-of-lists) (reduce #'(lambda (x y) ;; create list of abs sums (mapcar #'max x y)) list-of-lists)) (defun listwise-minima (list-of-lists) (reduce #'(lambda (x y) ;; create list of abs sums (mapcar #'min x y)) list-of-lists)) (defun listwise-linear-transforms (list-of-lists) (let* ((maxes (listwise-maxima list-of-lists)) (mins (listwise-minima list-of-lists)) (rescaled (loop for list in list-of-lists collect (mapcar #'(lambda (initial maximum minimum) (divide (- initial minimum) (- maximum minimum))) list maxes mins)))) rescaled)) (defun listwise-scale-by (list-of-lists factor) (loop for list in list-of-lists collect (mapcar #'(lambda (x) (* x factor)) list))) (defun rescale-data (ht &key (scaling-function #'listwise-linear-transforms) (scaling-factor 8)) (let* ((newht (make-hash-table)) (kvecs (loop for k being the hash-keys in ht collect k)) (klists (mapcar #'(lambda (x) (coerce x 'list)) kvecs)) (rescaled (listwise-scale-by (funcall scaling-function klists) scaling-factor))) (mapcar #'(lambda (x y) (setf (gethash (coerce x 'vector) newht) (gethash y ht))) rescaled kvecs) (format t "[+] RESCALED DATA USING ~A~%" (func->string scaling-function)) newht)) (defun count-labels (ht) (let ((counts '()) (tally 0) (lastseen)) (loop for val in (sort (loop for v being the hash-values in ht collect v) #'<) do (unless (or (null lastseen) (= val lastseen)) (push tally counts) (setf tally 0)) (incf tally) (setf lastseen val)) (push tally counts) counts))
12,317
Common Lisp
.lisp
265
32.667925
114
0.496909
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
f3f4f7756de74962ed12dde4bf6f1aa5f00cebd5c27a57b26c713bcfc3ccbc16
16,834
[ -1 ]
16,835
frontend.lisp
oblivia-simplex_genlin/frontend.lisp
(load #p"~/Projects/genlin/package.lisp") ;; (defpackage :genlin ;; (:use :common-lisp)) (in-package #:genlin) ;;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;;; Linear Genetic Algorithm ;;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defparameter *project-path* "~/Projects/genlin/") ;; (defun loadfile (filename) ;; (load (merge-pathnames filename *load-truename*))) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defparameter *machine* :stackmachine) ;; (defparameter *machine-file* ;; (case *machine* ;; ((:stackmachine "stackmachine.lisp")) ;; ((:slomachine) "slomachine.lisp") ;; ((:r-machine) "r-machine.lisp"))) ;; ;; slomachine is an unstable VM for self-modifying code (defun load-other-files () (loop for f in `("auxiliary.lisp" "params.lisp" "stackmachine.lisp" "datafiler.lisp" "tictactoe.lisp" ;; "iris.lisp" "genlin.lisp") do (loadfile (concatenate 'string *project-path* f)))) ;;(load-other-files) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ;; A pretty front-end ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defun print-operations () (let ((used #\*) (unused #\space)) (loop for op in (coerce *operations* 'list) for i from 0 to (length *operations*) do (format t "~A ~A~%" (func->string op) (if (< i (expt 2 *opcode-bits*)) used unused))))) (defun string->earmuff (string) (let ((muffed (concatenate 'string "*" (string-upcase string) "*"))) (intern muffed))) (defun earmuff->string (symbol) (let ((string (remove #\* (symbol-name symbol)))) string)) (defun tweakable->posixopt (symbol) (concatenate 'string "--" (string-downcase (earmuff->string symbol)))) (defun print-tweakables () (loop for symbol in *tweakables* for i from 0 to (length *tweakables*) do (format t "[~d] ~A ~S~% ~A~%" i (tweakable->posixopt symbol) (symbol-value symbol) (documentation symbol 'variable)))) (defun get-opt-arg (list key) (let ((anything-there (member key list :test #'equalp))) (when anything-there (cadr anything-there)))) (defun print-help () (format t "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=~%") (format t " GENLIN~%") (format t "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=~%~%") (format t "Many of the dynamic (global) parameters in GENLIN can be set using familiar POSIX-style command line argument syntax. Valid options and the default values of the parameters they modify are printed below. Note that quotation marks must be escaped for string arguments, but keywords (prefixed by a colon) need no quotes.~%~%") (print-tweakables) nil) (defun parse-command-line-args () (let ((args (cdr sb-ext:*posix-argv*))) ;; (FORMAT T "ARGV = ~S~%" args) (when (member (tweakable->posixopt '*params-path*) args) (format t "READING PARAMETERS FROM ~A~%" *params-path*) (read-parameter-file (read-from-string (get-opt-arg args (tweakable->posixopt '*params-path*))))) (cond ((or (member "--help" args :test #'equalp) (member "-h" args :test #'equalp)) (print-help)) (t (hrule) (loop for param in *tweakables* do (let ((key (tweakable->posixopt param))) (when (member key args :test #'equalp) ;; (FORMAT T "FOUND OPT: ~S = ~S~%" ;; key (get-opt-arg args key)) (setf (symbol-value param) (read-from-string (get-opt-arg args key))) (format t "[+] SETTING ~A TO ~A...~%" param (symbol-value param))))) T)))) ;; (format t "~S = ~S~%" param (symbol-value param)))))) (defun menu () "The front end and user interface of the programme. Allows the user to tweak a number of dynamically scoped, special variables, and then launch setup and evolve." (flet ((validate (n) (or (eq n :Q) (and (numberp n) (<= 0 n) (< n (length *tweakables*)))))) (let ((sel)) (loop do (hrule) (print-tweakables) (hrule) (loop do (format t "~%ENTER NUMBER OF PARAMETER TO TWEAK, OR :Q TO PROCEED.~%") (princ "~ ") ; (clear-input) (setf sel (read)) (when (validate sel) (return))) (when (eq sel :Q) (return)) (format t "~%YOU SELECTED ~D: ~A~%CURRENT VALUE: ~S~% ~A~%~%" sel (elt *tweakables* sel) (symbol-value (elt *tweakables* sel)) (documentation (elt *tweakables* sel) 'variable)) (format t "ENTER NEW VALUE (BE CAREFUL, AND MIND THE SYNTAX)~%~~ ") (setf (symbol-value (elt *tweakables* sel)) (read)) (format t "~A IS NOW SET TO ~A~%" (elt *tweakables* sel) (symbol-value (elt *tweakables* sel))))))) (defun sanity-check () "A place to prevent a few of the more disasterous parameter clashes and eventually, sanitize the input." (when (or (eql *migration-size* 0) (eql *greedy-migration* 0)) (setf *greedy-migration* nil)) ;; (unless *sex* ;; (setf *mutation-rate* 1)) (when *debug* (setf *parallel* nil) (when (eq *selection-method* :lexicase) (format t "WARNING: *TRACK-GENEALOGY* CURRENTLY INCOMPATIBLE") (format t " WITH LEXICASE SELECTION.~%DISABLING.") (setf *track-genealogy* nil) (setf *case-storage* t)))) ;; =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= (defun setup-population () (setf +ISLAND-RING+ (init-population *population-size* *max-start-len* :number-of-islands *number-of-islands*))) (defun read-parameter-file (param-path) (load param-path)) (defparameter *label-counts* nil) (defun setup-data (&key (ratio *training-ratio*) (dataset *dataset*) (selection-method *selection-method*) (pack-selection-method *pack-selection-method*) (filename *data-path*)) (let ((hashtable) (training+testing)) (setf *method* (case selection-method ((:tournement) #'tournement!) ((:roulette) #'roulette!) ((:greedy-roulette) #'greedy-roulette!) ((:lexicase) #'lexicase!) (otherwise (progn (format t "WARNING: METHOD NAME NOT RECO") (format t "GNIZED. USING #'TOURNEMENT!.~%") #'tournement!)))) (setf *pack-method* (case pack-selection-method ((:tournement) #'tournement!) ((:roulette) #'roulette!) ((:greedy-roulette) #'greedy-roulette!) ((:lexicase) #'lexicase!) (otherwise (progn (format t "WARNING: METHOD NAME NOT RECO") (format t "GNIZED. USING #'TOURNEMENT!.~%") #'tournement!)))) (setf *dataset* dataset) (reset-records) (funcall =label-scanner= 'flush) (setf hashtable (datafile->hashtable :filename filename)) (when *testing-data-path* (setf training+testing (cons hashtable (datafile->hashtable :filename *testing-data-path*)))) (setf *number-of-classes* (funcall =label-scanner= 'count)) (unless *split-data* (setf training+testing (cons hashtable hashtable))) (unless training+testing (setf training+testing (partition-data hashtable ratio))) ;; init-fitness-env sets up the training and testing hashtables, ;; the fitness function, and the output registers. (init-fitness-env :training-hashtable (car training+testing) :testing-hashtable (cdr training+testing)) (case *sex* ((:1pt) (setf *mating-func* #'shufflefuck-1pt)) ((:2pt) (setf *mating-func* #'shufflefuck-2pt-constant)) ((t) (setf *mating-func* #'shufflefuck-2pt-constant)) (otherwise (setf *mating-func* 'cloning))) (setf *label-counts* (count-labels (car training+testing))) training+testing)) ;; todo: write a generic csv datafile->hashtable loader, for ;; deployment on arbitrary datasets. ;; it's not convenient, yet, to select the VM at runtime. this choice needs ;; to be made at compile time, for the time being. (defun save-all (island-ring) (with-open-file (stream "STATISTICS.SAV" :direction :output :if-exists :append :if-does-not-exist :create) (format stream "~A~%~%" (timestring)) (print-statistics island-ring :stream stream)) (save-parameters) (save-island-ring)) (defun save-parameters (&optional (param-path *last-params-path*)) "Will append to existing file, allowing old settings to be retrieved if accidentally clobbered." (with-open-file (stream param-path :direction :output :if-exists :supersede :if-does-not-exist :create) (format stream "~%~A~%~%" (timestring)) (loop for param in *tweakables* do (format stream "~S~%" `(setf ,param ,(symbol-value param)))))) (defun save-island-ring (&key (filename "ISLAND-RING.SAV") (bury-parents t) (island-ring +ISLAND-RING+)) (let ((copy (island-ring-writeable-copy island-ring :bury-parents bury-parents))) (with-open-file (stream filename :direction :output :if-exists :supersede :if-does-not-exist :create) (setf *print-circle* nil) (format stream "~A~%;; +ISLAND-RING+ below: ~%~%~S~%)" (timestring) copy) (setf *print-circle* T)))) (defun island-ring-writeable-copy (island-ring &key (bury-parents t)) (let ((copy (mapcar #'copy-structure (de-ring island-ring)))) (loop for isle in copy do (when bury-parents (mapc #'bury-parents (island-deme isle)) (mapc #'bury-parents (island-packs isle))) (setf (island-method isle) nil) (setf (island-lock isle) nil) (setf (island-logger isle) nil) (setf (island-coverage isle) nil)) copy)) ;; ;; placeholders ;; (defun tournement! ()) ;; (defun roulette! ()) ;; (defun greedy-roulette! ()) ;; (defun lexicase! ()) (defun restore-island-ring (&key (filename "ISLAND-RING.SAV")) (let ((copy) (method-chooser)) (format t "[-] RESTORING ISLAND-RING FROM ~A..." filename) (with-open-file (stream filename :direction :input :if-does-not-exist nil) (and (setf copy (read stream)) (format t " ISLAND-RING SUCCESSFULLY RESTORED!"))) (loop for isle in copy do (setf (island-logger isle) (make-logger)) (setf (island-lock isle) (sb-thread:make-mutex :name (format nil "isle-~d-lock" (island-id isle)))) (setf (island-era isle) 0) ;; necessary to prevent certain bugs ;; but admittedly a bit of a kludge (if *case-storage* (setf (island-coverage isle) (init-cases-covered *training-hashtable*))) (setf method-chooser (if (island-packs isle) *pack-selection-method* *selection-method*)) (setf (island-method isle) (case method-chooser ((:tournement) #'tournement!) ((:roulette) #'roulette!) ((:greedy-roulette) #'greedy-roulette!) ((:lexicase) #'lexicase!) (otherwise (progn (format t "WARNING: METHOD NAME NOT RECO") (format t "GNIZED. USING #'TOURNEMENT!.~%") #'tournement!))))) (setf +island-ring+ (circular copy)))) ;; Note: it should be simple enough to generalize the ttt data processing ;; technique. ;; - scan the dataset ;; - count the possible values for each field, and if there are an equal ;; number of possibilities for each field, say n, formalize the key as ;; an m-digit base-n gray code integer. ;; - this may, in some cases, even work when there is a maximum number ;; of possibilities per field. or if each field can have any of n ;; values, when unconstrained by other fields (the mutual constraints, ;; of course, are an impt aspect of the pattern that the algo's meant ;; to detect). (defun main (&key (run t)) (format t "~A~%" (timestring)) (when (parse-command-line-args) (when *menu* (menu)) (setup-data) ;; load the dataset, build the hashtables (update-dependent-machine-parameters) (sanity-check) ;; makes things slightly less likely to explode (if *restore-island-ring* (restore-island-ring :filename *restore-island-ring*) (setup-population)) (print-params) (when run (format t " -oO( COMMENCING EVOLUTIONARY PROCESS, PLEASE STANDBY )Oo-~%") (hrule) (evolve :target *target* :rounds *rounds*) (save-parameters *last-params-path*) (format t "PARAMETERS SAVED IN ~A~%" *last-params-path*) (save-island-ring :filename "ISLAND-RING.SAV" :island-ring +ISLAND-RING+) (format t "ISLAND-RING SAVED IN ISLAND-RING.SAV~%"))))
14,455
Common Lisp
.lisp
317
34.832808
90
0.534392
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
f6f5762e3ce0e604be3afce3e76ca4ba241c05ee5699403b9ea3865b6fdae213
16,835
[ -1 ]
16,836
hello.lisp
oblivia-simplex_genlin/genetic-hello/hello.lisp
(defpackage :genetic.hello (:use :common-lisp)) (in-package :genetic.hello) ;(defparameter *target* "Genetic Algorithm") ;;(defparameter *target* "You do look, my son, in a moved sort, As if you were dismay'd: be cheerful, sir. Our revels now are ended. These our actors, As I foretold you, were all spirits and Are melted into air, into thin air: And, like the baseless fabric of this vision, The cloud-capp'd towers, the gorgeous palaces, The solemn temples, the great globe itself, Ye all which it inherit, shall dissolve And, like this insubstantial pageant faded, Leave not a rack behind. We are such stuff As dreams are made on, and our little life Is rounded with a sleep. Sir, I am vex'd; Bear with my weakness; my, brain is troubled: Be not disturb'd with my infirmity: If you be pleased, retire into my cell And there repose: a turn or two I'll walk, To still my beating mind") (defparameter *target* "Happy birthday to you! Happy birthday to you! Happy birthday, dear Neha! Happy birthday to you!") (defparameter *creature-len* (length *target*)) (defparameter *pop-size* 5) (defparameter *mutation-rate* 90) ; percent chance of mutation (defparameter *default-best* '(9999999999 "")) (defparameter *best* '()) (defparameter *population* '()) (defparameter *display-thresh* 99999999999) (defparameter *display-step* 100) (defun cls() (format t "~A[H~@*~A[J" #\escape)) (defun rnd-char () (code-char (+ (random #x5F) #x20))) (defun rnd-str (len) (concatenate 'string (loop repeat len collect (rnd-char)))) (defun char-dist (a b) (abs (- (char-code a) (char-code b)))) (defun str-dist (a b &optional (len *creature-len*)) (loop for i from 0 to (1- len) sum (char-dist (char a i) (char b i)))) (defun fitness (creature) (let ((f (str-dist creature *target*))) (when (< f (car *best*)) (setf (car *best*) f) (setf (cadr *best*) creature) (when (< f *display-thresh*) (cls) (format t "~a[~d] ~a~%~%" #\return (car *best*) (cadr *best*)) (setf *display-thresh* (- f (floor (/ f *display-step*)))))) f)) (defun init-population (&optional (psize *pop-size*) (clen *creature-len*)) (concatenate 'vector (loop repeat psize collect (rnd-str clen)))) (defun mutate (creature) "Destructively mutates a string, by randomly shifting one character." (let* ((shift (if (= (random 2) 0) -1 1)) (idx (random (length creature))) (allele (char-code (char creature idx))) (mutation (code-char (max #x20 (min #x7F (+ allele shift)))))) (setf (char creature idx) mutation) creature)) (defun maybe-mutate (creature) (if (< (random 100) *mutation-rate*) (mutate creature) creature)) (defun crossover (mother father &optional (idx0 (random *creature-len*)) (idx1 (random *creature-len*))) (let ((child (copy-seq mother)) (minidx (min idx0 idx1)) (maxidx (max idx0 idx1))) ;; (format t "swapping ~a for ~a at ~d in ~a~%" (char father idx) (char mother idx) idx child) (setf (subseq child minidx maxidx) (subseq father minidx maxidx)) (maybe-mutate child))) (defun shufflefuck (mother father) (let ((child mother)) (loop for i from 0 to (1- *creature-len*) do (setf (char child i) (if (= 0 (random 2)) (char mother i) (char father i)))) (maybe-mutate child))) (defun mate (mother father) (list (crossover mother father) (crossover father mother))) (defun n-rnd (low high &optional (r '()) (n 4)) "Returns a list of n distinct random numbers between low and high." (when (<= (- high low) n) (error "This will loop forever, you fool!")) (loop (when (= (length r) n) (return r)) (setf r (remove-duplicates (cons (+ low (random high)) r))))) (defun tournement (population &optional (psize *pop-size*)) (let* ((lots (n-rnd 0 psize)) (combatants (mapcar #'(lambda (i) (list (elt population i) i)) lots)) (ranked (sort combatants #'(lambda (x y) (< (fitness (car y)) (fitness (car x)))))) (winners (cddr ranked)) (parents (mapcar #'car winners)) (children (apply #'mate parents)) (losers (subseq ranked 0 2)) (graves (mapcar #'cadr losers))) (map 'list #'(lambda (grave child) (setf (elt population grave) child)) graves children) (mapcar #'fitness children))) ;; to update the *best* variable ;; (format t "LOSERS:~c~c~a~c~a~%WINNERS:~c~a~c~a~%OFFSPRING:~c~a~c~a~%~%" ;; #\Tab #\Tab (caar losers) #\Tab (caadr losers) ;; #\Tab (car parents) #\Tab (cadr parents) ;; #\Tab (car children) #\Tab (cadr children)) (defun main-loop (iterations) ;;(let ((population (init-population))) (setf *population* (init-population)) (setf *best* (copy-seq *default-best*)) (setf *display-thresh* 9999999999999) (loop for i from 1 to iterations do (tournement *population*) (when (equal (cadr *best*) *target*) (format t "**** TARGET REACHED AFTER ~d TOURNEMENTS ****~%" i) (return *best*)))) (defun main () (main-loop 10000000))
5,191
Common Lisp
.lisp
103
44.912621
766
0.636885
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
9d658c002576c2d15ea41f67bfd23193252feb1d33721fcb470e030e1fc5cfd3
16,836
[ -1 ]
16,838
compile.lisp
oblivia-simplex_genlin/genetic-hello/compile.lisp
(load "hello.lisp") (in-package :genetic.hello) (sb-ext:save-lisp-and-die "hello" :executable t :toplevel #'main)
115
Common Lisp
.lisp
3
37
65
0.72973
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
740fdd389c4642021e527e3ef7dce5cc29eaecd977242ce488edaaddabc7c572
16,838
[ -1 ]
16,839
genlin.asd
oblivia-simplex_genlin/genlin.asd
;;;; genlin.asd (asdf:defsystem #:genlin :description "A linear genetic programming engine" :author "Olivia Lucca Fraser <[email protected]>" :license "GNU GPL" ;; :depends-on (#:sb-thread) :serial t :components ((:file "package") (:file "auxiliary") (:file "params") (:file "stackmachine") (:file "datafiler") (:file "genlin") (:file "frontend") (:file "tictactoe"))) ;; (:file "compile")))
545
Common Lisp
.asd
16
24.6875
56
0.524462
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
a3fdb37274387a90d5ea94d0c819ebae0bb5ccb5e7be46ab841130c639c9e04a
16,839
[ -1 ]
16,848
Makefile
oblivia-simplex_genlin/Makefile
genlin: compile.lisp genlin.lisp auxiliary.lisp tictactoe.lisp stackmachine.lisp params.lisp frontend.lisp sbcl --dynamic-space-size 2048 --script compile.lisp # testing # testing data: datasets.tgz tar xzvf datasets.tgz all: genlin data clean: tar czvf datasets.tgz datasets/ rm -rf datasets GENLIN
307
Common Lisp
.l
10
29
106
0.816949
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
6c591299c980838e7c7bbeeefe79a73dc80775e1faecb9d5198aaafe68bbe243
16,848
[ -1 ]
16,849
trials.sh
oblivia-simplex_genlin/trials.sh
#! /bin/bash ./GENLIN --parallel t \ --packs nil \ --opcode-bits 3 \ --dataset :thyroid \ --data-path \"./datasets/thyroid/ann-train.lbl.csv\" \ --testing-data-path \"./datasets/thyroid/ann-test.lbl.csv\" \ --sex nil \ --mutation-rate 1 \ --selection-method :lexicase \ --fitfunc-name :detection-rate \ --rounds 4000 \ --save-every 1000 \ --stat-interval 100 \ --migration-rate 100 \ --migration-size 1/5 \ --greedy-migration 1/2 \ --target .99 \ --number-of-islands 8 \ --population-size 1200 \ --max-cal-depth 2 \ --sampling-policy :balanced \ --sampling-ratio 1/3 \ | tee logs/thyroid-lexicase-asexual-balanced.lab.log ./GENLIN --parallel t \ --packs nil \ --opcode-bits 3 \ --dataset :thyroid \ --data-path \"./datasets/thyroid/ann-train.lbl.csv\" \ --testing-data-path \"./datasets/thyroid/ann-test.lbl.csv\" \ --sex :1pt \ --mutation-rate 1/3 \ --selection-method :lexicase \ --fitfunc-name :detection-rate \ --rounds 4000 \ --save-every 1000 \ --stat-interval 100 \ --migration-rate 100 \ --migration-size 1/5 \ --greedy-migration 1/2 \ --target .99 \ --number-of-islands 8 \ --population-size 1200 \ --max-cal-depth 2 \ --sampling-policy :balanced \ --sampling-ratio 1/3 \ | tee logs/thyroid-lexicase-sex1pt-balanced.lab.log ./GENLIN --parallel t \ --packs nil \ --opcode-bits 3 \ --dataset :thyroid \ --data-path \"./datasets/thyroid/ann-train.lbl.csv\" \ --testing-data-path \"./datasets/thyroid/ann-test.lbl.csv\" \ --sex nil \ --mutation-rate 1 \ --selection-method :tournement \ --fitfunc-name :detection-rate \ --rounds 4000 \ --save-every 1000 \ --stat-interval 100 \ --migration-rate 100 \ --migration-size 1/5 \ --greedy-migration 1/2 \ --target .99 \ --number-of-islands 8 \ --population-size 1200 \ --max-cal-depth 2 \ --sampling-policy :balanced \ --sampling-ratio 1/3 \ | tee logs/thyroid-tournement-asexual.lab.log ./GENLIN --parallel t \ --packs nil \ --opcode-bits 3 \ --dataset :thyroid \ --data-path \"./datasets/thyroid/ann-train.lbl.csv\" \ --testing-data-path \"./datasets/thyroid/ann-test.lbl.csv\" \ --sex :1pt \ --mutation-rate 1/3 \ --selection-method :lexicase \ --fitfunc-name :detection-rate \ --rounds 4000 \ --save-every 1000 \ --stat-interval 100 \ --migration-rate 100 \ --migration-size 1/5 \ --greedy-migration 1/2 \ --target .99 \ --number-of-islands 8 \ --population-size 1200 \ --max-cal-depth 2 \ --sampling-policy :balanced \ --sampling-ratio 1/3 \ | tee logs/thyroid-tournement-sex1pt.lab.log ./GENLIN --parallel t \ --packs nil \ --opcode-bits 3 \ --dataset :thyroid \ --data-path \"./datasets/thyroid/ann-train.lbl.csv\" \ --testing-data-path \"./datasets/thyroid/ann-test.lbl.csv\" \ --sex :1pt \ --mutation-rate 1/3 \ --selection-method :lexicase \ --fitfunc-name :n-ary-prop-vote \ --rounds 4000 \ --save-every 1000 \ --stat-interval 100 \ --migration-rate 100 \ --migration-size 1/5 \ --greedy-migration 1/2 \ --target .99 \ --number-of-islands 8 \ --population-size 1200 \ --max-cal-depth 2 \ --sampling-policy :balanced \ --sampling-ratio 1/3 \ | tee logs/thyroid-tournement-sex1pt-propvote.lab.log ./GENLIN --parallel t \ --packs nil \ --opcode-bits 3 \ --dataset :shuttle \ --data-path \"./datasets/shuttle/shuttle.trn.csv\" \ --testing-data-path \"./datasets/shuttle/shuttle.tst.csv\" \ --sex :1pt \ --mutation-rate 1/3 \ --selection-method :tournement \ --fitfunc-name :n-ary-prop-vote \ --rounds 4000 \ --save-every 1000 \ --stat-interval 100 \ --migration-rate 100 \ --migration-size 1/5 \ --greedy-migration 1/2 \ --target .99 \ --number-of-islands 8 \ --population-size 1200 \ --max-cal-depth 2 \ --sampling-policy :balanced \ --sampling-ratio 1/3 \ | tee logs/shuttle-tournement-sex1pt-propvote.lab.log ./GENLIN --parallel t \ --packs nil \ --opcode-bits 3 \ --dataset :shuttle \ --data-path \"./datasets/shuttle/shuttle.trn.csv\" \ --testing-data-path \"./datasets/shuttle/shuttle.tst.csv\" \ --sex :1pt \ --mutation-rate 1/3 \ --selection-method :tournement \ --fitfunc-name :detection-rate \ --rounds 4000 \ --save-every 1000 \ --stat-interval 100 \ --migration-rate 100 \ --migration-size 1/5 \ --greedy-migration 1/2 \ --target .99 \ --number-of-islands 8 \ --population-size 1200 \ --max-cal-depth 2 \ --sampling-policy :balanced \ --sampling-ratio 1/3 \ | tee logs/shuttle-tournement-sex1pt-dr.lab.log ./GENLIN --parallel t \ --packs nil \ --opcode-bits 3 \ --dataset :shuttle \ --data-path \"./datasets/shuttle/shuttle.trn.csv\" \ --testing-data-path \"./datasets/shuttle/shuttle.tst.csv\" \ --sex :1pt \ --mutation-rate 1/3 \ --selection-method :lexicase \ --fitfunc-name :detection-rate \ --rounds 4000 \ --save-every 1000 \ --stat-interval 100 \ --migration-rate 100 \ --migration-size 1/5 \ --greedy-migration 1/2 \ --target .99 \ --number-of-islands 8 \ --population-size 1200 \ --max-cal-depth 2 \ --sampling-policy :balanced \ --sampling-ratio 1/3 \ | tee logs/shuttle-lexicase-sex1pt-dr.lab.log ./GENLIN --parallel t \ --packs nil \ --opcode-bits 3 \ --dataset :shuttle \ --data-path \"./datasets/shuttle/shuttle.trn.csv\" \ --testing-data-path \"./datasets/shuttle/shuttle.tst.csv\" \ --sex nil \ --mutation-rate 1 \ --selection-method :lexicase \ --fitfunc-name :detection-rate \ --rounds 4000 \ --save-every 1000 \ --stat-interval 100 \ --migration-rate 100 \ --migration-size 1/5 \ --greedy-migration 1/2 \ --target .99 \ --number-of-islands 8 \ --population-size 1200 \ --max-cal-depth 2 \ --sampling-policy :balanced \ --sampling-ratio 1/3 \ | tee logs/shuttle-lexicase-asexual-dr.lab.log
7,239
Common Lisp
.l
208
25.326923
70
0.529479
oblivia-simplex/genlin
3
2
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
bb76c466167093598d1f0bf2b2926e3040baa83d0600f21c56505661d5b58f7d
16,849
[ -1 ]
16,879
test-profiler.lsp
clausb_lisp-profiler/test-profiler.lsp
;;-*-Lisp-*- ;; Test code for ridiculously trivial profiler for Lisp code ;; See http://www.clausbrod.de/Blog/DefinePrivatePublic20160308LispProfiler ;; Original author: Claus Brod ;; http://www.clausbrod.de ;; ;; For licensing details, see the LICENSE file. ;; For documentation, see README.md. (in-package :clausbrod.de) (require "lisp-profiler" #P"lisp-profiler") (use-package :profiler.clausbrod.de) #+hcl (f2::win-open-console-window) #+hcl (setf si::*enter-break-handler* t) #+hcl (use-fast-links nil) (defun test-func(cnt) (dotimes (i cnt) (format t "~%~a" i))) ;;(frame2-ui::display (macroexpand '(with-profiler ('test-func (find-package "ELAN")) (test-func 42)))) #+hcl (with-profiler ('test-func 'format (find-package "ELAN") (find-package "OLI")) (test-func 42))
803
Common Lisp
.l
19
40.631579
103
0.705806
clausb/lisp-profiler
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
dd763b0f68388d0631c88a2d1069e45042b19c6448a6f5aa6986d42f6708a204
16,879
[ -1 ]
16,880
lisp-profiler.lsp
clausb_lisp-profiler/lisp-profiler.lsp
;;-*-Lisp-*- ;; Ridiculously trivial profiler for Lisp code ;; See http://www.clausbrod.de/Blog/DefinePrivatePublic20160308LispProfiler ;; ;; Original author: Claus Brod ;; http://www.clausbrod.de ;; ;; For licensing details, see the LICENSE file. ;; For documentation, see README.md. ;; (in-package :profiler.clausbrod.de) (export '(profile-function profile-package profile-functions unprofile-function unprofile-all list-profiling-results reset-profiling-results with-profiler *profiler-stream*)) (provide "lisp-profiler") #+hcl (use-fast-links nil) ;; To redirect profiling output, create a dynamic binding for this stream before profiling. (defvar *profiler-stream* *standard-output*) (let ((profile-hashtable (make-hash-table))) (defun reset-profiling-results() (clrhash profile-hashtable)) (defun update-hashtable(func execution-time) (let ((accum (gethash func profile-hashtable 0.0))) (setf (gethash func profile-hashtable) (+ accum execution-time)))) (defun list-profiling-results() "List profiling results in order of decreasing accumulated execution times" (format *profiler-stream* "~%Accumulated execution times:~%") (let (table-as-list) (maphash (lambda(k v) (push (cons k v) table-as-list)) profile-hashtable) (dolist (pair (sort table-as-list #'> :key #'cdr)) ;; Lisp prints symbols in "used" packages without package name. Seems ;; we need to roll our own printing code if we always want to see the full ;; symbol name including package. (Is there a better way?) (let* ((sym (car pair)) (sympkg (symbol-package sym))) (multiple-value-bind (s st) (find-symbol (symbol-name sym) sympkg) (format *profiler-stream* "~14,10F ~A~A~A~%" (cdr pair) (package-name sympkg) (if (eq :internal st) "::" ":") sym)))))) ) (defun get-current-time-in-microseconds() #+hcl (f2::seconds-since-1970) #-hcl (* (/ 1000000 internal-time-units-per-second) (get-internal-real-time)) ) (defun execute-with-profiling(func original-symbol-function args) (let ((start-time (get-current-time-in-microseconds))) (unwind-protect (if args (apply original-symbol-function args) (funcall original-symbol-function)) (update-hashtable func (- (get-current-time-in-microseconds) start-time))))) (let ((unprofilable-functions (make-hash-table :test 'equal))) #+hcl (setf (gethash "FRAME2" unprofilable-functions) '("SECONDS-SINCE-1970")) #+hcl (setf (gethash "SYSTEM" unprofilable-functions) '("EVAL-FEATURE" "FUNCALL-PROTECTED" "GET-STRING-INPUT-STREAM-INDEX" "STRUCTURE-SUBTYPE-P" "STRUCTURE-REF1")) (defun profilable-p(func) (let ((p (gethash (package-name (symbol-package func)) unprofilable-functions))) (not (member (symbol-name func) p :test 'equal)))) (defun profile-function(func) "Instrument function for profiling" (when (stringp func) (setf func (find-symbol func))) (when (or (not (fboundp func)) (get func :profile-original-symbol-function)) (return-from profile-function)) (unless (profilable-p func) (return-from profile-function)) (let ((original-symbol-function (symbol-function func))) (unless (functionp original-symbol-function) (return-from profile-function)) (setf (get func :profile-original-symbol-function) original-symbol-function) ;; mark as profiled ;; install profiler code (setf (symbol-function func) (lambda(&rest r) (execute-with-profiling func original-symbol-function r)))))) (defun profile-package(pkg) "Profile all external functions in a package" (do-external-symbols (s pkg) (when (and (functionp s) (fboundp s)) (profile-function s)))) (defun unprofile-package(pkg) (do-external-symbols (s pkg) (when (and (functionp s) (fboundp s)) (unprofile-function s)))) (defun unprofile-function(func) "Remove profiling instrumentation for function" (let ((original-symbol-function (get func :profile-original-symbol-function))) (when (remprop func :profile-original-symbol-function) (setf (symbol-function func) original-symbol-function)))) (defun to-package(fspec) (cond ((packagep fspec) fspec) ((stringp fspec) (find-package fspec)) ((keywordp fspec) (find-package fspec)) ((symbolp fspec) (find-package fspec)))) (defun profile-functions(&rest function-specifiers) (dolist (fspec function-specifiers) (if (to-package fspec) (profile-package (to-package fspec)) (profile-function fspec)))) (defun unprofile-functions(&rest function-specifiers) (dolist (fspec function-specifiers) (if (packagep fspec) (unprofile-package fspec) (unprofile-function fspec)))) (defun unprofile-all() (apply 'unprofile-functions (list-all-packages))) (defmacro with-profiler(function-specifiers &body b) `(progn (reset-profiling-results) (profile-functions ,@function-specifiers) (progn ,@b) (unprofile-functions ,@function-specifiers) (list-profiling-results)))
5,078
Common Lisp
.l
117
38.931624
165
0.713905
clausb/lisp-profiler
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
a9967488eff831a4c8a73e57ca2e405743c71943af4e898ca527517eebedbe66
16,880
[ -1 ]
16,881
lisp-profiler-ui.lsp
clausb_lisp-profiler/lisp-profiler-ui.lsp
;;-*-Lisp-*- ;; UI dialog for ridiculously trivial Lisp profiler ;; See http://www.clausbrod.de/Blog/DefinePrivatePublic20160308LispProfiler ;; Original author: Claus Brod ;; http://www.clausbrod.de ;; ;; For licensing details, see the LICENSE file. ;; For documentation, see README.md. (in-package :profiler-ui.clausbrod.de) (use-package :oli) ;;(require "lisp-profiler" #P"lisp-profiler") (require "lisp-profiler") (use-package :profiler.clausbrod.de) (sd-defdialog 'profiler :dialog-title "Ridiculously trivial profiler" :toolbox-button t :variables '((package-or-function :value-type :string :title "Pkg/function" :prompt-text "Specify package or function to be profiled" :after-input (profile-another-package-or-function package-or-function)) (code-to-profile :title "Code to profile" :prompt-text "Specify function name or arbitrary Lisp form" :value-type :string :after-input (profile-code code-to-profile)) (start-profiling :title "Start profiling" :toggle-type :grouped-toggle :push-action (profile-start)) (stop-profiling :title "Stop profiling" :toggle-type :grouped-toggle :push-action (profile-stop)) (unprofile-all :title "Unprofile all" :toggle-type :wide-toggle :push-action (profiler.clausbrod.de:unprofile-all)) ) :local-functions '((profile-another-package-or-function(p-or-f) (dolist (segment (sd-string-split p-or-f " ")) (profiler.clausbrod.de:profile-functions segment))) (profile-code(code) (with-output-to-string (profiler.clausbrod.de:*profiler-stream*) (with-profiler () (eval (read-from-string code))) (frame2-ui::display (get-output-stream-string profiler.clausbrod.de:*profiler-stream*)))) (profile-start() (profiler.clausbrod.de:reset-profiling-results)) (profile-stop() (with-output-to-string (profiler.clausbrod.de:*profiler-stream*) (profiler.clausbrod.de:list-profiling-results) (frame2-ui::display (get-output-stream-string profiler.clausbrod.de:*profiler-stream*)))) ) :ok-action '(profiler.clausbrod.de:unprofile-all) )
2,177
Common Lisp
.l
59
32.474576
100
0.713739
clausb/lisp-profiler
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
c248485da10216b321a8bd16fc336c401d5781cf8287d19a7b95cf231d512292
16,881
[ -1 ]
16,899
delta.package.lisp
epipping_delta-lisp/delta.package.lisp
;; -*- mode:common-lisp; indent-tabs-mode: nil -*- (defpackage #:delta (:export #:delta-file) (:use #:cl) (:use #:let-plus))
132
Common Lisp
.lisp
5
24
50
0.603175
epipping/delta-lisp
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
8fe47931ac6236a648a8b003aa45e8cb8ddddf6bab2aae161c8d7e1679bf85c1
16,899
[ -1 ]
16,900
delta-tests.package.lisp
epipping_delta-lisp/delta-tests.package.lisp
;; -*- mode:common-lisp; indent-tabs-mode: nil -*- (defpackage #:delta-tests (:use #:cl #:5am))
107
Common Lisp
.lisp
4
23
50
0.578431
epipping/delta-lisp
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
786e4b9adca836cf4efaa7a84c4cee1983da78b04f3ebbd918b27c7ba85e3912
16,900
[ -1 ]
16,901
delta-standalone.package.lisp
epipping_delta-lisp/delta-standalone.package.lisp
;; -*- mode:common-lisp; indent-tabs-mode: nil -*- (defpackage #:delta-standalone (:export #:main) (:use #:cl) (:use #:let-plus))
137
Common Lisp
.lisp
5
25
50
0.618321
epipping/delta-lisp
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
9be25f031048b264c698e419db183637975513a20e9a6398c6a022f687a0764c
16,901
[ -1 ]
16,902
utilities.lisp
epipping_delta-lisp/utilities.lisp
;; -*- mode:common-lisp; indent-tabs-mode: nil -*- (in-package #:delta) (defun compute-break (length part numparts) "Compute mark at which chunk #`part` begins when a list of length `length` is divided into `numparts`-many chunks of (roughly) equal size." (floor (* part length) numparts)) (defun exclude-range (first last list) "Remove range of indices from `first` to `last` from list `list`. The range is taken is left-inclusive and right-exclusive." (cond ((plusp first) (cons (car list) (exclude-range (1- first) (1- last) (cdr list)))) ((plusp last) (exclude-range first (1- last) (cdr list))) (t list))) (defun shift-and-wrap (part shift numparts) (mod (+ part shift) numparts))
723
Common Lisp
.lisp
18
37.111111
71
0.691429
epipping/delta-lisp
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
cbfd2f0224c7cd35eda0904a19abad66bb3ebfd1639b0908c04fd9fce450d780
16,902
[ -1 ]
16,903
delta-tests.lisp
epipping_delta-lisp/delta-tests.lisp
;; -*- mode:common-lisp; indent-tabs-mode: nil -*- (in-package #:delta-tests) (def-suite delta-utility-tests :description "Test utilities contained within delta.") (in-suite delta-utility-tests) (test compute-break "Test the compute-break function." (is (= 0 (delta::compute-break 10 0 2))) (is (= 5 (delta::compute-break 10 1 2))) (is (= 10 (delta::compute-break 10 2 2)))) (test exclude-range "Test the exclude-range function." (is (equal '(b c d e) (delta::exclude-range 0 1 '(a b c d e)))) (is (equal '(d e) (delta::exclude-range 0 3 '(a b c d e)))) (is (equal '(a b d e) (delta::exclude-range 2 3 '(a b c d e))))) (test shift-and-wrap "Test shift-and-wrap function." (is (= 3 (delta::shift-and-wrap 0 3 10))) (is (= 3 (delta::shift-and-wrap 3 0 10))) (is (= 4 (delta::shift-and-wrap 1 3 10))) (is (= 2 (delta::shift-and-wrap 6 6 10))))
929
Common Lisp
.lisp
21
39.047619
70
0.599778
epipping/delta-lisp
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
60713419d14aaabc0339540764c6353bd506ba437e6ee0c4d365793a683fe230
16,903
[ -1 ]
16,904
delta.lisp
epipping_delta-lisp/delta.lisp
;; -*- mode:common-lisp; indent-tabs-mode: nil -*- (in-package #:delta) (defvar *max-processes*) (defvar *script-name*) (defvar *minimal-output-name* "output-minimal") (defvar *file-contents*) (defvar *suffix*) (defvar *quiet*) (defvar *show-stdout*) (defvar *show-stderr*) (alexandria:define-constant +sleep-between-checks+ 1e-4 :test #'=) (defun read-file (filename) "Split the file given by `filename` by newline and append the lines as strings to the array `*file-contents*`." (setf *file-contents* (coerce (uiop:read-file-lines filename) 'vector))) (defun write-from-indices (indices stream) "Write the subset of `*file-contents*` represented by the index list `indices` to the stream `stream`." (loop :for index :in indices :for line = (aref *file-contents* index) :do (format stream "~a~%" line))) (defun indices->file (indices filename) "Write the subset of `*file-contents*` represented by the index list `indices` to the file \"output\"." (with-open-file (stream filename :direction :output :if-exists :supersede) (write-from-indices indices stream))) (defclass reduction () ((part :initarg :part :initform -1) (complement :initarg :complement :initform nil))) (defclass process-with-result () ((process :initarg :process) (result :initarg :result))) (defun report-status (lines segments &key (granularity-increased nil)) (unless *quiet* (format t (if granularity-increased "Lines: ~a. Segments: ~a (granularity increased).~%" "Lines: ~a. Segments: ~a.~%") lines segments))) (defun terminate-process-cleanly (process) (uiop:terminate-process process) (uiop:wait-process process)) (defun test-removal (indices numparts initial-part) "Check if removing certain subsets of `indices` yields a reduction. The parameter `indices` should be a subset of `*file-contents*`, represented through a list of indices. The subset will be divided into `numparts`-many chunks of (roughly) equal size; for each chunk, its complement with respect to the subset will be tested. The first one that makes `*script-name*` pass will be returned. If no chunk passes, nil is returned." (loop :with pwr-list :with part = 0 :do (loop ;; Fill process list :until (or (>= part numparts) (>= (length pwr-list) *max-processes*)) :do (push (test-removal-helper indices numparts :relative-part part :shift-by initial-part) pwr-list) :do (incf part)) :do (loop ;; Check if a process has terminated :for pwr :in pwr-list :for process = (slot-value pwr 'process) :unless (uiop:process-alive-p process) :do (cond ;; Successful exit: Kill everyone and return ((= 0 (uiop:wait-process process)) (loop :for other-pwr :in (delete process pwr-list) :for other-process = (slot-value other-pwr 'process) :do (terminate-process-cleanly other-process)) (let+ (((&slots-r/o (reduction result)) pwr) ((&slots-r/o complement) reduction)) (report-status (length complement) (1- numparts)) (indices->file complement *minimal-output-name*) (return-from test-removal reduction))) ;; Otherwise: Treat the reduction as a failure (t (setf pwr-list (remove pwr pwr-list)))) :and :do (uiop:close-streams process)) ;; Return a dummy to signal overall reduction failure. :when (and (>= part numparts) (null pwr-list)) :do (return-from test-removal (make-instance 'reduction)) :do (sleep +sleep-between-checks+))) (defun run-on-subset (indices) (uiop:with-temporary-file (:pathname p :prefix "delta" :direction :output :keep t :element-type 'character :type *suffix*) (indices->file indices p) (uiop:launch-program (list *script-name* (namestring p)) :output (when *show-stdout* :interactive) :error-output (when *show-stderr* :interactive)))) (defun test-removal-helper (indices numparts &key relative-part shift-by) (let* ((part (shift-and-wrap relative-part shift-by numparts)) (begin (compute-break (length indices) part numparts)) (end (compute-break (length indices) (1+ part) numparts)) (complement (exclude-range begin end indices))) (make-instance 'process-with-result :process (run-on-subset complement) :result (make-instance 'reduction :part part :complement complement)))) (defun ddmin (indices numparts &key (initial-part 0)) (let+ (((&slots-r/o (passing-subset complement) (removed-part part)) (test-removal indices numparts initial-part)) (subset-length (length passing-subset)) (numindices (length indices))) (cond ;; Keep granularity. Try subsequent complements (wraps around) ((> subset-length 1) (ddmin passing-subset (max (1- numparts) 2) :initial-part removed-part)) ;; Increase granularity. ((and (zerop subset-length) (< numparts numindices)) (let ((new-numparts (min numindices (* 2 numparts)))) (report-status numindices new-numparts :granularity-increased T) (ddmin indices new-numparts))) ;; Done: Cannot partition single-line input ((= subset-length 1) passing-subset) ;; Done: Unable to remove any subset of size 1. (t indices)))) (defun delta (indices) "Minimise a subset of `*file-contents*` represented by the index list `indices` under the constraint that `*script-name*` returns 0 when a file consisting of that subset is passed as its sole argument." (report-status (length indices) 1) (let* ((process (run-on-subset indices)) (exit-code (uiop:wait-process process))) (unless (= 0 exit-code) (error "Initial input does not satisfy the predicate"))) (report-status (length indices) 2 :granularity-increased T) (ddmin indices 2)) (defun delta-file (script-name filename &key (suffix (nth-value 1 (uiop:split-name-type (file-namestring filename)))) (processes 1) quiet show-stdout show-stderr) "Minimise the file given by `filename` under the constraint that `script-name` should continue to return 0 when passed the name of the resulting file as its sole argument. If `filename` can be reduced, a file will be created by the name `*minimal-output-name*`. The solution will not in general be a global minimum. It will satisfy the condition of 1-minimility, i.e. that no different solution can be found by removing a single line." (read-file filename) (setf *quiet* quiet) (setf *show-stdout* show-stdout) (setf *show-stderr* show-stderr) (setf *max-processes* processes) (setf *script-name* script-name) (setf *suffix* suffix) (delta (loop :for line :across *file-contents* :for index :from 0 :collect index)))
7,728
Common Lisp
.lisp
164
36.756098
77
0.606362
epipping/delta-lisp
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
8fc5c04ac1dd55988d30d8abf7b4e818962d62eb832bc6236d2ab3017ce8e21a
16,904
[ -1 ]
16,905
test.lisp
epipping_delta-lisp/mk/test.lisp
(load "mk/path.lisp") (asdf:operate 'asdf:load-op :delta-tests) (5am:run 'delta-tests::delta-utility-tests) (write-line "") (quit)
134
Common Lisp
.lisp
5
25.2
43
0.722222
epipping/delta-lisp
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
0b7d88998d583b02171871e8f6d4c7bbf54bf29f665eae203871f14850501dea
16,905
[ -1 ]
16,906
delta.asd
epipping_delta-lisp/delta.asd
(asdf:defsystem #:delta :serial t :depends-on (#:alexandria #:let-plus) :components ((:file "delta.package") (:file "utilities" :depends-on ("delta.package")) (:file "delta" :depends-on ("delta.package"))))
243
Common Lisp
.asd
6
33.5
64
0.594937
epipping/delta-lisp
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
b236aab4c45518b9b7a5745886396648caaf35347f9a77d5a5e606343c9a53d4
16,906
[ -1 ]
16,907
delta-tests.asd
epipping_delta-lisp/delta-tests.asd
(asdf:defsystem #:delta-tests :serial t :depends-on (#:delta #:FiveAM) :components ((:file "delta-tests.package") (:file "delta-tests" :depends-on ("delta-tests.package"))))
195
Common Lisp
.asd
5
33.8
74
0.636842
epipping/delta-lisp
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
dd0a48396538acf580786e1d36878c65c3c0e417fc26339dcc9d620f432e40db
16,907
[ -1 ]
16,908
delta-standalone.asd
epipping_delta-lisp/delta-standalone.asd
(asdf:defsystem #:delta-standalone :serial t :depends-on (#:alexandria #:delta #:getopt) :components ((:file "delta-standalone.package") (:file "delta-standalone" :depends-on ("delta-standalone.package"))) :entry-point "delta-standalone:main" :build-operation program-op :build-pathname "delta-standalone")
334
Common Lisp
.asd
8
37.375
83
0.708589
epipping/delta-lisp
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
715c8ea506066fe8ea3581f6456311594d9fa17af621d0296638790e65de83e5
16,908
[ -1 ]
16,919
secondorderassemblertest-57319f.ii
epipping_delta-lisp/t/clang-28087/secondorderassemblertest-57319f.ii
namespace std { typedef long unsigned int size_t; template <typename> class allocator; template <typename _Tp, _Tp __v> struct integral_constant { static constexpr _Tp value = __v; typedef _Tp value_type; typedef integral_constant<_Tp, __v> type; constexpr operator value_type() const {} }; typedef integral_constant<bool, false> false_type; template <bool, typename, typename> struct conditional; template <typename...> struct __or_; template <typename _B1, typename _B2> struct __or_<_B1, _B2> : public conditional<_B1::value, _B1, _B2>::type {}; template <typename _B1, typename _B2, typename _B3, typename... _Bn> struct __or_<_B1, _B2, _B3, _Bn...> : public conditional<_B1::value, _B1, __or_<_B2, _B3, _Bn...>>::type {}; template <typename _Pp> struct __not_ : public integral_constant<bool, !_Pp::value> {}; template <typename _Tp> struct __success_type { typedef _Tp type; }; template <typename> struct remove_cv; template <typename> struct __is_void_helper : public false_type {}; template <typename _Tp> struct is_void : public __is_void_helper<typename remove_cv<_Tp>::type>::type {}; template <typename> struct is_array : public false_type {}; template <typename> struct is_lvalue_reference : public false_type {}; template <typename> struct is_rvalue_reference : public false_type {}; template <typename> struct __is_member_object_pointer_helper : public false_type {}; template <typename _Tp> struct is_member_object_pointer : public __is_member_object_pointer_helper< typename remove_cv<_Tp>::type>::type {}; template <typename> struct __is_member_function_pointer_helper : public false_type {}; template <typename _Tp> struct is_member_function_pointer : public __is_member_function_pointer_helper< typename remove_cv<_Tp>::type>::type {}; template <typename> struct is_function : public false_type {}; template <typename _Tp> struct is_reference : public __or_<is_lvalue_reference<_Tp>, is_rvalue_reference<_Tp>>::type { }; template <typename _Tp> struct is_object : public __not_< __or_<is_function<_Tp>, is_reference<_Tp>, is_void<_Tp>>>::type {}; template <typename _Tp> struct __is_referenceable : public __or_<is_object<_Tp>, is_reference<_Tp>>::type {}; template <typename _Tp> struct is_empty : public integral_constant<bool, __is_empty(_Tp)> {}; template <typename> struct add_rvalue_reference; template <typename _Tp> typename add_rvalue_reference<_Tp>::type declval() noexcept; template <typename, typename> struct is_same : public false_type {}; template <typename _Base, typename _Derived> struct is_base_of : public integral_constant<bool, __is_base_of(_Base, _Derived)> {}; template <typename _Tp> struct remove_const { typedef _Tp type; }; template <typename _Tp> struct remove_volatile { typedef _Tp type; }; template <typename _Tp> struct remove_cv { typedef typename remove_const<typename remove_volatile<_Tp>::type>::type type; }; template <typename _Tp> struct remove_reference { typedef _Tp type; }; template <typename _Tp> struct remove_reference<_Tp &> { typedef _Tp type; }; template <typename _Tp, bool = __is_referenceable<_Tp>::value> struct __add_rvalue_reference_helper { typedef _Tp type; }; template <typename _Tp> struct add_rvalue_reference : public __add_rvalue_reference_helper<_Tp> {}; template <typename _Up, bool _IsArray = is_array<_Up>::value, bool _IsFunction = is_function<_Up>::value> struct __decay_selector; template <typename _Up> struct __decay_selector<_Up, false, false> { typedef typename remove_cv<_Up>::type __type; }; template <typename _Tp> class decay { typedef typename remove_reference<_Tp>::type __remove_type; public: typedef typename __decay_selector<__remove_type>::__type type; }; template <bool, typename _Tp = void> struct enable_if {}; template <bool _Cond, typename _Iftrue, typename _Iffalse> struct conditional { typedef _Iffalse type; }; template <typename _Signature> class result_of; template <bool, bool, typename _Functor, typename... _ArgTypes> struct __result_of_impl {}; struct __result_of_other_impl { template <typename _Fn, typename... _Args> static __success_type< decltype(std::declval<_Fn>()(std::declval<_Args>()...))> _S_test(int); }; template <typename _Functor, typename... _ArgTypes> struct __result_of_impl<false, false, _Functor, _ArgTypes...> : private __result_of_other_impl { typedef decltype(_S_test<_Functor, _ArgTypes...>(0)) type; }; template <typename _Functor, typename... _ArgTypes> struct result_of<_Functor(_ArgTypes...)> : public __result_of_impl< is_member_object_pointer< typename remove_reference<_Functor>::type>::value, is_member_function_pointer< typename remove_reference<_Functor>::type>::value, _Functor, _ArgTypes...>::type {}; template <typename _Tp> using decay_t = typename decay<_Tp>::type; template <typename _Tp> constexpr _Tp &&forward(typename std::remove_reference<_Tp>::type & __t) noexcept {}; } typedef long unsigned int size_t; namespace std __attribute__((__visibility__("default"))) { template <typename _Tp, std::size_t _Nm> struct array {}; template <size_t... _Indexes> struct _Index_tuple {}; template <size_t _Num> struct _Build_index_tuple { typedef _Index_tuple<> __type; }; template <typename _Tp, _Tp... _Idx> struct integer_sequence {}; template <typename _Tp, _Tp _Num, typename _ISeq = typename _Build_index_tuple<_Num>::__type> struct _Make_integer_sequence; template <typename _Tp, _Tp _Num, size_t... _Idx> struct _Make_integer_sequence<_Tp, _Num, _Index_tuple<_Idx...>> { typedef integer_sequence<_Tp, static_cast<_Tp>(_Idx)...> __type; }; template <typename _Tp, _Tp _Num> using make_integer_sequence = typename _Make_integer_sequence<_Tp, _Num>::__type; template <size_t... _Idx> using index_sequence = integer_sequence<size_t, _Idx...>; template <size_t _Num> using make_index_sequence = make_integer_sequence<size_t, _Num>; template <typename _Tp, typename _Alloc> struct _Vector_base {}; template <typename _Tp, typename _Alloc = std::allocator<_Tp>> class vector : protected _Vector_base<_Tp, _Alloc> {}; template <typename _Tp> struct __add_ref {}; template <std::size_t _Idx, typename _Head, bool _IsEmptyNotFinal> struct _Head_base; template <std::size_t _Idx, typename _Head> struct _Head_base<_Idx, _Head, false> { constexpr _Head_base(const _Head &__h) : _M_head_impl(__h) {} _Head _M_head_impl; }; template <std::size_t _Idx, typename... _Elements> struct _Tuple_impl; template <std::size_t _Idx> struct _Tuple_impl<_Idx> {}; template <typename _Tp> struct __is_empty_non_tuple : is_empty<_Tp> {}; template <typename _Tp> using __empty_not_final = typename conditional<__is_final(_Tp), false_type, __is_empty_non_tuple<_Tp>>::type; template <std::size_t _Idx, typename _Head, typename... _Tail> struct _Tuple_impl<_Idx, _Head, _Tail...> : public _Tuple_impl<_Idx + 1, _Tail...>, private _Head_base<_Idx, _Head, __empty_not_final<_Head>::value> { typedef _Tuple_impl<_Idx + 1, _Tail...> _Inherited; typedef _Head_base<_Idx, _Head, __empty_not_final<_Head>::value> _Base; explicit constexpr _Tuple_impl(const _Head &__head, const _Tail &... __tail) : _Inherited(__tail...), _Base(__head) {} }; template <typename... _Elements> class tuple : public _Tuple_impl<0, _Elements...> { typedef _Tuple_impl<0, _Elements...> _Inherited; public: explicit constexpr tuple(const _Elements &... __elements) : _Inherited(__elements...) {} }; template <std::size_t __i, typename _Tp> struct tuple_element; template <typename _Tp> struct tuple_size; template <typename... _Elements> struct tuple_size<tuple<_Elements...>> : public integral_constant<std::size_t, sizeof...(_Elements)> {}; template <std::size_t __i, typename... _Elements> constexpr typename __add_ref< typename tuple_element<__i, tuple<_Elements...>>::type>::type get(tuple<_Elements...> & __t) noexcept {}; } namespace Dune { template <typename Communicator> class CollectiveCommunication {}; typedef struct ompi_communicator_t *MPI_Comm; template <int k> class bigunsignedint; template <typename V> class DenseVector {}; template <class K, int SIZE> class FieldVector : public DenseVector<FieldVector<K, SIZE>> {}; class GeometryType { public: enum BasicType { simplex, cube, pyramid, prism, extended, none }; unsigned int topologyId_; unsigned char dim_ : 7; bool none_ : 1; GeometryType(BasicType basicType, unsigned int dim) : topologyId_(0), dim_(dim), none_((basicType == GeometryType::none) ? true : false) {} }; enum PartitionIteratorType { }; template <class ViewTraits> class GridView { public: typedef ViewTraits Traits; typedef typename Traits::Grid Grid; typedef typename Grid::ctype ctype; enum { dimension = Grid::dimension }; }; template <class GridImp> struct DefaultLevelGridViewTraits {}; template <class GridImp> struct DefaultLeafGridViewTraits { typedef typename std::remove_const<GridImp>::type Grid; }; template <int mydim, int cdim, class GridImp, template <int, int, class> class GeometryImp> class Geometry; template <int codim, int dim, class GridImp, template <int, int, class> class EntityImp> class Entity; template <class GridImp, class IndexSetImp, class IndexTypeImp = unsigned int, class TypesImp = std::vector<GeometryType>> class IndexSet; template <int dim, int dimworld, class ct, class GridFamily> class Grid { public: enum { dimension = dim }; enum { dimensionworld = dimworld }; typedef typename GridFamily::Traits::LeafGridView LeafGridView; template <int cd> struct Codim { typedef typename GridFamily::Traits::template Codim<cd>::Geometry Geometry; }; }; template <int dim, int dimworld, class ct, class GridFamily> class GridDefaultImplementation : public Grid<dim, dimworld, ct, GridFamily> {}; template <int dim, int dimw, class GridImp, template <int, int, class> class GeometryImp, template <int, int, class> class EntityImp, template <int, PartitionIteratorType, class> class LevelIteratorImp, template <class> class LeafIntersectionImp, template <class> class LevelIntersectionImp, template <class> class LeafIntersectionIteratorImp, template <class> class LevelIntersectionIteratorImp, template <class> class HierarchicIteratorImp, template <int, PartitionIteratorType, class> class LeafIteratorImp, class LevelIndexSetImp, class LeafIndexSetImp, class GlobalIdSetImp, class GIDType, class LocalIdSetImp, class LIDType, class CCType, template <class> class LevelGridViewTraits, template <class> class LeafGridViewTraits, template <int, class> class EntitySeedImp, template <int, int, class> class LocalGeometryImp = GeometryImp> struct GridTraits { template <int cd> struct Codim { typedef Dune::Geometry<dim - cd, dimw, const GridImp, GeometryImp> Geometry; }; typedef Dune::GridView<LeafGridViewTraits<const GridImp>> LeafGridView; }; template <class K, int ROWS, int COLS> class FieldMatrix; template <int mydim, int cdim, class GridImp, template <int, int, class> class GeometryImp> class Geometry { public: typedef typename GridImp::ctype ctype; typedef FieldVector<ctype, cdim> GlobalCoordinate; }; template <int cd, int dim, class GridImp, template <int, int, class> class EntityImp> class EntityDefaultImplementation {}; template <class GridImp, class IdSetImp, class IdTypeImp> class IdSet {}; template <class CoordType, unsigned int dim, unsigned int coorddim> class AxisAlignedCubeGeometry {}; const int yaspgrid_dim_bits = 24; const int yaspgrid_level_bits = 5; template <int dim, class Coordinates> class YaspGrid; template <int codim, class GridImp> class YaspEntitySeed; template <class GridImp> class YaspIntersectionIterator; template <class GridImp> class YaspHierarchicIterator; template <class ct, int dim> class EquidistantCoordinates { public: typedef ct ctype; }; template <int mydim, int cdim, class GridImp> class YaspGeometry : public AxisAlignedCubeGeometry<typename GridImp::ctype, mydim, cdim> {}; template <int codim, int dim, class GridImp> class YaspEntity : public EntityDefaultImplementation<codim, dim, GridImp, YaspEntity> {}; template <class GridImp> class YaspIntersection {}; template <int codim, class GridImp> class YaspEntityPointer {}; template <int codim, PartitionIteratorType pitype, class GridImp> class YaspLevelIterator : public YaspEntityPointer<codim, GridImp> {}; template <class GridImp, bool isLeafIndexSet> class YaspIndexSet : public IndexSet<GridImp, YaspIndexSet<GridImp, isLeafIndexSet>, unsigned int> {}; template <class GridImp> class YaspGlobalIdSet : public IdSet< GridImp, YaspGlobalIdSet<GridImp>, typename std::remove_const<GridImp>::type::PersistentIndexType> {}; template <int dim, class Coordinates> struct YaspGridFamily { typedef CollectiveCommunication<MPI_Comm> CCType; typedef GridTraits< dim, dim, Dune::YaspGrid<dim, Coordinates>, YaspGeometry, YaspEntity, YaspLevelIterator, YaspIntersection, YaspIntersection, YaspIntersectionIterator, YaspIntersectionIterator, YaspHierarchicIterator, YaspLevelIterator, YaspIndexSet<const YaspGrid<dim, Coordinates>, false>, YaspIndexSet<const YaspGrid<dim, Coordinates>, true>, YaspGlobalIdSet<const YaspGrid<dim, Coordinates>>, bigunsignedint<dim * yaspgrid_dim_bits + yaspgrid_level_bits + dim>, YaspGlobalIdSet<const YaspGrid<dim, Coordinates>>, bigunsignedint<dim * yaspgrid_dim_bits + yaspgrid_level_bits + dim>, CCType, DefaultLevelGridViewTraits, DefaultLeafGridViewTraits, YaspEntitySeed> Traits; }; template <int dim, class Coordinates = EquidistantCoordinates<double, dim>> class YaspGrid : public GridDefaultImplementation<dim, dim, typename Coordinates::ctype, YaspGridFamily<dim, Coordinates>> { public: typedef typename Coordinates::ctype ctype; }; template <class DF, int n, class D, class RF, int m, class R, class J, int dorder = 0> struct LocalBasisTraits { typedef DF DomainFieldType; enum { dimDomain = n }; typedef D DomainType; typedef RF RangeFieldType; enum { dimRange = m }; typedef R RangeType; typedef J JacobianType; }; template <class LB, class LC, class LI> struct LocalFiniteElementTraits { typedef LB LocalBasisType; }; template <class T> struct LowerOrderLocalBasisTraits {}; template <class T, int order> struct FixedOrderLocalBasisTraits { typedef LocalBasisTraits<typename T::DomainFieldType, T::dimDomain, typename T::DomainType, typename T::RangeFieldType, T::dimRange, typename T::RangeType, typename T::JacobianType, order> Traits; }; template <class T> class LocalFiniteElementVirtualInterface : public virtual LocalFiniteElementVirtualInterface< typename LowerOrderLocalBasisTraits<T>::Traits> {}; }; template <class GV, class RT, class LFE> class FunctionSpaceBasis { public: typedef LFE LocalFiniteElement; }; namespace Arithmetic { template <class A, class B, class C> void addProduct(A &a, const B &b, const C &c) {} } namespace Dune { namespace TypeTree { class LeafNode {}; template <typename... T> class HybridTreePath {}; namespace impl { } } namespace Functions { template <typename size_t, typename TP> class BasisNodeMixin {}; template <typename size_t, typename TP> class LeafBasisNode : public BasisNodeMixin<size_t, TP>, public TypeTree::LeafNode {}; }; template <class D, class R, int d> class P0LocalBasis { public: typedef LocalBasisTraits<D, d, Dune::FieldVector<D, d>, R, 1, Dune::FieldVector<R, 1>, Dune::FieldMatrix<R, 1, d>, 0> Traits; }; class P0LocalCoefficients {}; template <class LB> class P0LocalInterpolation {}; template <class D, class R, int d> class P0LocalFiniteElement { public: typedef LocalFiniteElementTraits<P0LocalBasis<D, R, d>, P0LocalCoefficients, P0LocalInterpolation<P0LocalBasis<D, R, d>>> Traits; }; } class QuadratureRuleKey { public: QuadratureRuleKey(const int dim, const int order, const int refinement = 0, bool lumping = false) : gt_(Dune::GeometryType::none, dim), order_(order), refinement_(refinement), lumping_(lumping) {} Dune::GeometryType gt_; int order_; int refinement_; bool lumping_; }; template <class GridType, class TrialLocalFE, class AnsatzLocalFE, typename T> class LocalOperatorAssembler { public: typedef T MatrixEntry; }; namespace Dune { namespace Fufem { namespace Concept { namespace Imp { template <class... T> struct TypeList {}; template <class T> struct IsTypeList : std::false_type {}; template <class T> static constexpr bool isTypeList() { return IsTypeList<T>(); } template <class T> static constexpr bool isEmptyTypeList() { return isTypeList<T>() and std::is_same<T, TypeList<>>(); } struct RefinedConcept {}; template <class C> static constexpr bool isRefinedConcept() { return std::is_base_of<RefinedConcept, C>(); } template <class C, class... T> static constexpr bool matchesRequirement() { return decltype(matchesRequirement<C, T...>(std::declval<C *>()))::value; } template <class C, class... T, typename std::enable_if<isEmptyTypeList<C>(), int>::type = 0> static constexpr bool modelsConceptList() { return true; } template <class C, class... T, typename std::enable_if< not(isTypeList<C>()) and isRefinedConcept<C>(), int>::type = 0> static constexpr bool modelsConcept() { return matchesRequirement<C, T...>() and modelsConceptList<typename C::BaseConceptList, T...>(); } template <class C, class... T> static constexpr bool modelsImp() { return modelsConcept<C, T...>(); } } template <class C, class... T> static constexpr bool models() { return Imp::modelsImp<C, T...>(); } } } } template <typename F, typename Tuple, size_t... I> decltype(auto) apply_impl(F &&f, Tuple &&t, std::index_sequence<I...>) { return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...); } template <typename F, typename Tuple> decltype(auto) apply(F &&f, Tuple &&t) { using Indices = std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>::value>; return apply_impl(std::forward<F>(f), std::forward<Tuple>(t), Indices{}); } namespace Dune { namespace Fufem { namespace Concept { template <class ResultMat, class Scalar, class Coord, class... ReturnTypes> struct SecondOrderOperatorAssemblerContraction { static ResultMat &r; static Scalar &s; std::tuple<ReturnTypes...> &otherArgs; template <class F> auto require(F &&f) -> decltype(Arithmetic::addProduct(r, s, apply([](auto... args) {}, otherArgs))); }; } } } template <class GridType, class TrialLocalFE, class AnsatzLocalFE, class Contraction, class MB = Dune::FieldMatrix<double, 1, 1>, class... FunctionTypes> class SecondOrderOperatorAssembler : public LocalOperatorAssembler<GridType, TrialLocalFE, AnsatzLocalFE, MB> { typedef LocalOperatorAssembler<GridType, TrialLocalFE, AnsatzLocalFE, MB> Base; static const int dimworld = GridType::dimensionworld; public: typedef typename Base::MatrixEntry MatrixEntry; typedef typename Dune::template FieldVector<double, dimworld> WorldCoordinate; SecondOrderOperatorAssembler(const Contraction &contraction, bool isSymmetric, QuadratureRuleKey coefficientQuadKey, FunctionTypes... functions) : contraction_(contraction), isSymmetric_(isSymmetric), coefficientQuadKey_(coefficientQuadKey), functions_(functions...) { typedef Dune::Fufem::Concept::SecondOrderOperatorAssemblerContraction< MatrixEntry, double, WorldCoordinate, typename std::result_of<FunctionTypes(WorldCoordinate)>::type...> ContractionConcept; static_assert( Dune::Fufem::Concept::models<ContractionConcept, Contraction>(), "contraction(WorldCoordinate, WorldCoordinate, ...))"); } const Contraction contraction_; bool isSymmetric_; const QuadratureRuleKey coefficientQuadKey_; std::tuple<FunctionTypes...> functions_; }; template <class DFBasis> class DuneFunctionsBasis : public FunctionSpaceBasis< typename DFBasis::GridView, double, typename DFBasis::LocalView::Tree::FiniteElement> {}; namespace Dune { template <class D, class R, int dim, int k> class PQkLocalFiniteElementCache { typedef typename FixedOrderLocalBasisTraits< typename P0LocalFiniteElement<D, R, dim>::Traits::LocalBasisType::Traits, 0>::Traits T; typedef LocalFiniteElementVirtualInterface<T> FE; public: typedef FE FiniteElementType; }; namespace Functions { template <class GB> class DefaultLocalView { using PrefixPath = TypeTree::HybridTreePath<>; public: using GlobalBasis = GB; using Tree = typename GlobalBasis::NodeFactory::template Node<PrefixPath>; }; template <class NF> class DefaultGlobalBasis { public: using NodeFactory = NF; using GridView = typename NodeFactory::GridView; using LocalView = DefaultLocalView<DefaultGlobalBasis<NodeFactory>>; }; template <class size_type> class FlatMultiIndex : public std::array<size_type, 1> {}; template <typename GV, typename ST, typename TP> class PQ1Node; template <typename GV, class MI, class ST> class PQ1NodeFactory { public: using GridView = GV; using size_type = ST; template <class TP> using Node = PQ1Node<GV, size_type, TP>; }; template <typename GV, typename ST, typename TP> class PQ1Node : public LeafBasisNode<ST, TP> { static const int dim = GV::dimension; using FiniteElementCache = typename Dune::PQkLocalFiniteElementCache<typename GV::ctype, double, dim, 1>; public: using FiniteElement = typename FiniteElementCache::FiniteElementType; }; template <typename GV, class ST = std::size_t> using PQ1NodalBasis = DefaultGlobalBasis<PQ1NodeFactory<GV, FlatMultiIndex<ST>, ST>>; } } using namespace Dune; int main(int argc, char *argv[]) { const int dim = 3; typedef YaspGrid<dim> GridType; typedef DuneFunctionsBasis< Dune::Functions::PQ1NodalBasis<GridType::LeafGridView>> P1Basis; typedef FieldMatrix<double, dim, dim> LocalMatrix; { double const E = 2.8; double const nu = 0.23; typedef GridType::Codim<0>::Geometry::GlobalCoordinate GlobalCoordinate; auto const funcE = [E](GlobalCoordinate const &) { return E; }; auto const funcNu = [nu](GlobalCoordinate const &) { return nu; }; auto contraction = [](const GlobalCoordinate &g1, const GlobalCoordinate &g2, double E, double nu) {}; SecondOrderOperatorAssembler< GridType, P1Basis::LocalFiniteElement, P1Basis::LocalFiniteElement, decltype(contraction), LocalMatrix, decltype(funcE), decltype(funcNu)> secondOrderAssembler(contraction, true, QuadratureRuleKey(dim, 0), funcE, funcNu); } }
23,771
Common Lisp
.l
570
37.2
80
0.701263
epipping/delta-lisp
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
eea7b4edd85b114641215375fa6bfda83830435c208335ab69f78cf155232ba9
16,919
[ -1 ]
16,935
robit.lisp
karason_lisp-robit/robit.lisp
;;;; robit.lisp— an internet relay chat automaton defined in common lisp. ;;; Copyright (C) 2013 Chris Wallace and Ryan Karason ;;; ;;; 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/>. ;;; change scope to :robit namespace (in-package :robit) ;;; startup sequence- connect to a server (defun boot () (defparameter *connection* (connect :nickname *nick* :server *server*)) (cond (*password* (privmsg *connection* "nickserv" (concatenate 'string "identify " *password*))) (t 'nil)) (labels ((join-all (channels) (cond ((eq channels 'nil) 'nil) (t (join *connection* (car channels)) (join-all (cdr channels)))))) (join-all *channels*)) (say-all *channels* "ima robit.") (add-hook *connection* 'irc::irc-privmsg-message 'ping-hook) (ping-loop)) ;;; say— echo message to channel (defun say (channel message) (cond ((eq message 'nil) 'nil) (t (let ((current-ping (make-ping (get-universal-time) channel *nick* message))) (log-ping current-ping) (privmsg *connection* channel message))))) ;;; say all— echo message to list of channels (defun say-all (channels message) (cond ((eq channels 'nil) 'nil) (t (say (car channels) message) (say-all (cdr channels) message)))) ;;; act— echo action to channel (defun act (channel action) (privmsg *connection* channel (format nil "~A~A~A~A" #\Soh "ACTION " action #\Soh))) ;;; ping-hook— create a log and response hook for incoming ping (defun ping-hook (ping) (let ((current-ping (make-ping (get-universal-time) (cond ((equal (first (arguments ping)) *nick*) (source ping)) (t (first (arguments ping)))) (source ping) (car (last (arguments ping)))))) (log-ping current-ping) (say (ping-channel current-ping) (evaluate-ping current-ping)))) ;;; ping-loop— read messages on the connection (defun ping-loop () (read-message-loop *connection*)) ;;; the PING class ;;; used for events and incoming messages (defclass ping () ((date :accessor ping-date :initarg :date) (channel :accessor ping-channel :initarg :channel) (nick :accessor ping-nick :initarg :nick) (message :accessor ping-message :initarg :message))) ;;; make-ping— constructor for ping object (defun make-ping (date channel nick message) (make-instance 'ping :date date :channel channel :nick nick :message message)) ;;; number-to-string— convert number to string with padding (defun number-to-string (digits) (cond ((< digits 10) ;; pad single digit with leading zero (concatenate 'string "0" (write-to-string digits))) (t (write-to-string digits)))) ;;; prettify-ping— create pretty output from a ping object (defun prettify-ping (ping-object) (let ((date-list (multiple-value-list (decode-universal-time (ping-date ping-object))))) (concatenate 'string (number-to-string (nth 2 date-list)) ; hours ":" (number-to-string (nth 1 date-list)) ; minutes ":" (number-to-string (nth 0 date-list)) ; seconds " <" (ping-nick ping-object) "> " (ping-message ping-object)))) ;;; prettify-date— create pretty output from universal timestamp (defun prettify-date (date) (let ((date-list (multiple-value-list (decode-universal-time date)))) (concatenate 'string (write-to-string (nth 5 date-list)) ; year "-" (number-to-string (nth 4 date-list)) ; month "-" (number-to-string (nth 3 date-list))))) ; day ;;; get-log-path— get full path for logging (defun get-log-path (ping-object) (concatenate 'string *path* "/logs/" (ping-channel ping-object) "/" (prettify-date (ping-date ping-object)) ".log")) ;;; log-ping— write a ping object to log file (defun log-ping (ping-object) (ensure-directories-exist (concatenate 'string *path* "/logs/" (ping-channel ping-object) "/")) (let ((stream (open (get-log-path ping-object) :direction :output :if-exists :append :if-does-not-exist :create))) (princ (prettify-ping ping-object) stream) (princ #\newline stream) (close stream))) ;;; evaluate-ping— evaluate a ping object (defun evaluate-ping (ping-object) (evaluate-message (ping-message ping-object))) ;;; evaluate-message— evaluate a message (defun evaluate-message (message) (cond ((search "(" message) (cond ((search ")" message :from-end t) (write-to-string (ignore-errors (eval (read-from-string (subseq message (search "(" message) (+ 1 (search ")" message :from-end t)))))))) (t nil))) (t nil))) ;;; auto-load all accessory modules (labels ((load-all (accessories) (cond ((eq accessories 'nil) 'nil) (t (load (concatenate 'string *path* "/modules/" (car accessories))) (load-all (cdr accessories)))))) (in-package :cl-user) (load-all *accessories*)) ;;; for repl (setq custom:*prompt-body* "") ;;; print robit header to screen (progn (format t "~%") (format t "RRR 00 BBB IIII TTTT~%") (format t "R R O O B B II TT~%") (format t "RRR O O BBB II TT~%") (format t "R R O O B B II TT~%") (format t "R R OO BBB IIII TT~%") (format t "~%"))
6,705
Common Lisp
.lisp
185
27.940541
105
0.577719
karason/lisp-robit
3
0
4
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
a7cba8a842ad9a6772d5064da64b15e111fa133d3127efb7fe46b4070571abbe
16,935
[ -1 ]
16,936
eval-me.lisp
karason_lisp-robit/eval-me.lisp
;EVAL-ME.LISP: create configuration file for ROBIT.LISP (princ "Path of robit? ") (defparameter *robit-path* (read-line)) ;stream for configuration file (defparameter stream (open (concatenate 'string *robit-path* "/.robitrc") :direction :output :if-exists :new-version :if-does-not-exist :create)) (princ ";;;; robitrc.lisp- the initialization file for robit.lisp" stream) (princ #\newline stream) (princ #\newline stream) (princ ";;; suppess output of load" stream) (princ #\newline stream) (princ '(setq *load-verbose* 'nil) stream) (princ #\newline stream) (princ #\newline stream) (princ "Path of quicklisp? ") (princ ";;; load quicklisp system" stream) (princ #\newline stream) (princ `(load ,(write-to-string (concatenate 'string (read-line) "/setup.lisp"))) stream) (princ #\newline stream) (princ #\newline stream) (princ ";;; load cl-irc library" stream) (princ #\newline stream) (princ `(with-open-file (*standard-output* ,(write-to-string "/dev/null") \:direction \:output \:if-exists \:supersede) (QL\:QUICKLOAD ,(write-to-string "cl-irc"))) stream) (princ #\newline stream) (princ #\newline stream) (princ ";;; define :robit package" stream) (princ #\newline stream) (prin1 '(defpackage :robit (:use :common-lisp :irc) (:export boot)) stream) (princ #\newline stream) (princ #\newline stream) (princ ";;; move scope to :robit package" stream) (princ #\newline stream) (prin1 '(in-package :robit) stream) (princ #\newline stream) (princ #\newline stream) ;(princ "Path of robit? ") (princ ";;; set path directory for robit" stream) (princ #\newline stream) (princ `(defparameter *path* ,(write-to-string *robit-path*)) stream) (princ #\newline stream) (princ #\newline stream) (princ "Server of robit? ") (princ ";;; set server of robit" stream) (princ #\newline stream) (princ `(defparameter *server* ,(write-to-string (read-line))) stream) (princ #\newline stream) (princ #\newline stream) (princ "Nick of robit? ") (princ ";;; set nick of robit" stream) (princ #\newline stream) (princ `(defparameter *nick* ,(write-to-string (read-line))) stream) (princ #\newline stream) (princ #\newline stream) (princ ";;; set password of robit" stream) (princ #\newline stream) (princ "Is nick guarded? ") (princ `(defparameter *password* ,(cond ((equal (read-line) "yes") (princ "Password of robit? ") (write-to-string (read-line))) (t 'nil))) stream) (princ #\newline stream) (princ #\newline stream) ;car, if atoms were words and lists were strings (defun head (string) (let ((position (search " " string))) (cond ((eq position 'nil) string) (t (subseq string 0 position))))) ;cdr, if atoms were words and lists were strings (defun tail (string) (let ((position (search " " string))) (cond ((eq position 'nil) "") (t (subseq string (+ 1 position) (length string)))))) ;tokenize string into list of strings (defun tokenize (string) (cond ((equal string "") 'nil) (t (cons (write-to-string (head string)) (tokenize (tail string)))))) (princ "Channels of robit? ") (princ ";;; set channels of robit" stream) (princ #\newline stream) (princ `(defparameter *channels* ,(cons 'list (tokenize (read-line)))) stream) (princ #\newline stream) (princ #\newline stream) (princ ";;; set accessories of robit" stream) (princ #\newline stream) (princ "Auto-load accessory modules? ") (princ `(defparameter *accessories* ,(cond ((equal (read-line) "yes") (princ "Accessories of robit? ") (cons 'list (tokenize (read-line)))) (t 'nil))) stream) (princ #\newline stream) (close stream)
3,925
Common Lisp
.lisp
123
27.260163
78
0.638742
karason/lisp-robit
3
0
4
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
fc8882dc33a4614cd0816a14959cd1dd411a095a763eaf0ff12c2f75b968d983
16,936
[ -1 ]
16,937
safe-eval.lisp
karason_lisp-robit/safe-eval.lisp
(defparameter arithm (list '+ '- '* '/)) (defun is-safe? (sexp safe-commands) (cond ((eq sexp nil) T) ((atom sexp) (member sexp safe-commands)) ((atom (car sexp)) (and (member (car sexp) safe-commands) (is-safe? (cdr sexp) safe-commands)) ) (T (and (is-safe? (car sexp) safe-commands) (is-safe? (cdr sexp) safe-commands)))))
362
Common Lisp
.lisp
14
22.214286
44
0.618768
karason/lisp-robit
3
0
4
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
3abb264bef49da4ad1744a9287881df8cf1b3f5924873b82694a8584b99b0f60
16,937
[ -1 ]
16,938
shelly.lisp
karason_lisp-robit/modules/shelly.lisp
;;;; shelly.lisp (defun stream-to-list (a-stream) (let ((line (read-line a-stream nil))) (cond ((eq line 'nil) '()) (t (cons line (stream-to-list a-stream)))))) (defun $ (command) (stream-to-list (run-shell-command command :output :stream)))
344
Common Lisp
.lisp
13
17.615385
57
0.480243
karason/lisp-robit
3
0
4
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
e19d39b846e5dcdd2df0036b2897af7561965230c56f84833757777d0a5d1e58
16,938
[ -1 ]
16,939
dice.lisp
karason_lisp-robit/modules/dice.lisp
;;;; dice.lisp (defparameter ⚀ '1) (defparameter ⚁ '2) (defparameter ⚂ '3) (defparameter ⚃ '4) (defparameter ⚄ '5) (defparameter ⚅ '6) (defun dieify (numeric) (cond ((eq numeric '1) '⚀) ((eq numeric '2) '⚁) ((eq numeric '3) '⚂) ((eq numeric '4) '⚃) ((eq numeric '5) '⚄) ((eq numeric '6) '⚅))) (defun roll-die () (dieify (+ 1 (random 6)))) (defun roll-dice (quantity) (cond ((eq quantity '0) '()) (t (cons (roll-die) (roll-dice (- quantity 1)))))) (defun compare-die (die-1 die-2) (let ((numeric-1 (eval die-1)) (numeric-2 (eval die-2))) (cond ((> numeric-1 numeric-2) '1) ((< numeric-1 numeric-2) '-1) ((= numeric-1 numeric-2) '0)))) (defun sort-dice (dice) (mapcar 'dieify (sort (mapcar 'eval dice) '>))) (defun compare-dice (dice-1 dice-2) (let ((score (reduce '+ (mapcar 'compare-die (sort-dice dice-1) (sort-dice dice-2))))) (cond ((> score '0) '1) ((< score '0) '-1) ((= score '0) '0))))
1,139
Common Lisp
.lisp
39
21.897436
84
0.492049
karason/lisp-robit
3
0
4
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
bd9931b925c014ac9ae3bd1cc2155d20a850842c0f15afde3f5c3fc8c92841a5
16,939
[ -1 ]
16,940
elements.lisp
karason_lisp-robit/modules/elements.lisp
;;;; elements.lisp ;;; *elements*— atomic-number, atomic-symbol, atomic-name, atomic-weight, atomic-density, atomic-radius (defparameter *elements* '((1 '(H Hydrogen 1.00794 0.0000899 53)) (2 '(He Helium 4.002602 0.0001785 31)) (3 '(Li Lithium 6.941 0.535 167)) (4 '(Be Beryllium 9.012182 1.848 112)) (5 '(B Boron 10.8111 2.460 87)) (6 '(C Carbon 12.0107 2.260 67)) (7 '(N Nitrogen 14.0067 0.001251 56)) (8 '(O Oxygen 15.9994 0.001429 48)) (9 '(F Fluorine 18.9984032 0.001696 42)) (10 '(Ne Neon 20.1797 0.000900 38)) (11 '(Na Sodium 22.989770 0.968 190)) (12 '(Mg Magnesium 24.3050 1.738 145)) (13 '(Al Aluminum 26.981538 2.7 118)) (14 '(Si Silicon 28.0855 2.330 111)) (15 '(P Phosphorus 30.973761 1.823 98)) (16 '(S Sulfur 32.065 1.960 88)) (17 '(Cl Chlorine 35.453 0.003214 79)) (18 '(Ar Argon 39.948 0.001784 71)) (19 '(K Potassium 39.0983 0.856 243)) (20 '(Ca Calcium 40.078 1.550 194)) (21 '(Sc Scandium 44.955910 2.985 184)) (22 '(Ti Titanium 47.867 4.507 176)) (23 '(V Vanadium 50.9415 6.110 171)) (24 '(Cr Chromium 51.9961 7.140 166)) (25 '(Mn Manganese 54.938049 7.470 161)) (26 '(Fe Iron 55.845 7.874 156)) (27 '(Co Cobalt 58.9332 8.9 152)) (28 '(Ni Nickel 58.6934 8.908 149)) (29 '(Cu Copper 63.546 8.920 145)) (30 '(Zn Zinc 65.409 7.140 142)) (31 '(Ga Galium 69.723 5.904 136)) (32 '(Ge Germanium 72.64 5.323 125)) (33 '(As Arsenic 74.92160 5.727 114)) (34 '(Se Selenium 78.96 4.819 103)) (35 '(Br Bromine 79.904 3.120 94)) (36 '(Kr Krypton 83.798 0.00375 88)) (37 '(Rb Rubidium 85.4678 1.532 265)) (38 '(Sr Strontium 87.62 2.630 219)) (39 '(Y Yttrium 88.90585 4.472 212)) (40 '(Zr Zirconium 91.224 6.511 206)) (41 '(Nb Niobium 92.90638 8.570 198)) (42 '(Mo Molybdenum 95.94 10.280 190)) (43 '(Tc Technetium 98 11.5 183)) (44 '(Ru Ruthenium 101.07 12.370 178)) (45 '(Rh Rhodium 102.90550 12.450 173)) (46 '(Pd Palladium 106.42 12.023 169)) (47 '(Ag Silver 107.8682 10.490 165)) (48 '(Cd Cadmium 112.411 8.650 161)) (49 '(In Indium 114.818 7.310 156)) (50 '(Sn Tin 118.710 7.310 145)) (51 '(Sb Antimony 121.760 6.697 133)) (52 '(Te Tellurium 127.60 6.240 123)) (53 '(I Iodine 126.90447 4.940 115)) (54 '(Xe Xenon 131.293 0.0059 108)) (55 '(Cs Cesium 132.90545 1.879 298)) (56 '(Ba Barium 137.327 3.510 253)) (57 '(La Lanthanum 138.9055 6.146 195)) (58 '(Ce Cerium 140.116 6.689 158)) (59 '(Pr Praseodymium 140.90765 6.640 247)) (60 '(Nd Neodymium 144.24 7.010 206)) (61 '(Pm Promethium 145 7.264 205)) (62 '(Sm Samarium 150.36 7.353 238)) (63 '(Eu Europium 151.964 5.244 231)) (64 '(Gd Gadolinium 157.25 7.901 233)) (65 '(Tb Terbium 158.92534 8.219 225)) (66 '(Dy Dysprosium 162.5 8.551 228)) (67 '(Ho Holmium 164.93032 8.795 226)) (68 '(Er Erbium 167.259 9.066 226)) (69 '(Tm Thulium 168.93421 9.321 222)) (70 '(Yb Ytterbium 173.04 6.570 222)) (71 '(Lu Lutetium 174.967 9.841 217)) (72 '(Hf Hafnium 178.49 13.310 208)) (73 '(Ta Tantalum 180.9479 16.650 200)) (74 '(W Tungsten 183.84 19.250 193)) (75 '(Re Rhenium 186.207 21.020 188)) (76 '(Os Osmium 190.23 22.59 185)) (77 '(Ir Iridium 192.217 22.56 180)) (78 '(Pt Platinum 195.078 21.090 177)) (79 '(Au Gold 196.96655 19.3 174)) (80 '(Hg Mecury 200.59 13.534 171)) (81 '(Tl Thallium 204.3833 11.850 156)) (82 '(Pb Lead 207.2 11.340 154)) (83 '(Bi Bismuth 208.98038 9.780 143)) (84 '(Po Polonium 209 9.196 135)) (85 '(At Astatine 210 NIL 127)) (86 '(Rn Radon 222 0.00973 120)) (87 '(Fr Francium 223 NIL NIL)) (88 '(Ra Radium 226 5.0 215)) (89 '(Ac Actinium 227 10.070 195)) (90 '(Th Thorium 232.0381 11.724 180)) (91 '(Pa Protactinium 231.03588 15.370 180)) (92 '(U Uranium 238.02891 19.050 175)) (93 '(Np Neptunium 237 20.450 175)) (94 '(Pu Plutonium 244 19.816 175)) (95 '(Am Americium 243 NIL 175)) (96 '(Cm Curium 247 13.510 NIL)) (97 '(Bk Berkelium 247 14.780 NIL)) (98 '(Cf Californium 251 15.1 NIL)) (99 '(Es Einsteinium 252 NIL NIL)) (100 '(Fm Fermium 257 NIL NIL)) )) (defparameter atomic-number "Atomic number: the number of protons found in the nucleus of an atom of an element.") (defparameter atomic-symbol "Atomic symbol: the short-hand unique identifier of an element.") (defparameter atomic-name "Atomic name: the long-hand unique identifier of an element.") (defparameter atomic-weight "Atomic weight: the average weight of an atom of an element as sampled on Earth.") (defun get-element-by (atomic-? ??) (cond ((eq atomic-? 'atomic-number) (get-element-by-atomic-number ?? *elements*)) ((eq atomic-? 'atomic-symbol) (get-element-by-atomic-symbol ?? *elements*)) ((eq atomic-? 'atomic-name) (get-element-by-atomic-name ?? *elements*)) ((eq atomic-? 'atomic-weight) (get-element-by-atomic-weight ?? *elements*)) ((eq atomic-? 'atomic-density) (get-element-by-atomic-density ?? *elements*)) ((eq atomic-? 'atomic-radius) (get-element-by-atomic-radius ?? *elements*)) (t "Error: Property of element not known."))) (defun get-element-by-atomic-number (atomic-number elements) (cond ((eq elements '()) (concatenate 'string "Error: Atomic number " (write-to-string atomic-number) " not found.")) ((eq (get-atomic-number (car elements)) atomic-number) (car elements)) (t (get-element-by-atomic-number atomic-number (cdr elements))))) (defun get-element-by-atomic-symbol (atomic-symbol elements) (cond ((eq elements '()) (concatenate 'string "Error: Atomic symbol " (write-to-string atomic-symbol) " not found.")) ((eq (get-atomic-symbol (car elements)) atomic-symbol) (car elements)) (t (get-element-by-atomic-symbol atomic-symbol (cdr elements))))) (defun get-element-by-atomic-name (atomic-name elements) (cond ((eq elements '()) (concatenate 'string "Error: Atomic name " (write-to-string atomic-name) " not found.")) ((eq (get-atomic-name (car elements)) atomic-name) (car elements)) (t (get-element-by-atomic-name atomic-name (cdr elements))))) (defun get-element-by-atomic-weight (atomic-name elements) (cond ((eq elements '()) (concatenate 'string "Error: Atomic weight " (write-to-string atomic-weight) " not found.")) ((eq (get-atomic-weight (car elements)) atomic-weight) (car elements)) (t (get-element-by-atomic-weight atomic-weight (cdr elements))))) (defun get-element-by-atomic-density (atomic-density elements) (cond ((eq elements '()) (concatenate 'string "Error: Atomic density " (write-to-string atomic-density) " not found.")) ((eq (get-atomic-density (car elements)) atomic-density) (car elements)) (t (get-element-by-atomic-density atomic-density (cdr elements))))) (defun get-element-by-atomic-radius (atomic-radius elements) (cond ((eq elements '()) (concatenate 'string "Error: Atomic radius " (write-to-string atomic-radius) " not found.")) ((eq (get-atomic-radius (car elements)) atomic-radius) (car elements)) (t (get-element-by-atomic-radius atomic-radius (cdr elements))))) (defun get-atomic-number (an-element) (car an-element)) (defun get-atomic-symbol (an-element) (nth 0 (cadadr an-element))) (defun get-atomic-name (an-element) (nth 1 (cadadr an-element))) (defun get-atomic-weight (an-element) (nth 2 (cadadr an-element))) (defun get-atomic-density (an-element) (nth 3 (cadadr an-element))) (defun get-atomic-radius (an-element) (nth 4 (cadadr an-element)))
8,260
Common Lisp
.lisp
188
36.595745
106
0.602857
karason/lisp-robit
3
0
4
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
38427d9345a49a663bc14e922834bf3fbde7679f054505c66c06c7328f08614f
16,940
[ -1 ]
16,941
misc.lisp
karason_lisp-robit/modules/misc.lisp
;;;; misc.lisp (defun robit () "https://github.com/karason/lisp-robit") (defun beep () 'boop) (defun boop () 'beep) (defun help (&optional query) (cond ((eq query 'nil) "http://www.lispworks.com/documentation/HyperSpec/Front/index.htm") (t (concatenate 'string "http://www.xach.com/clhs?q=" (write-to-string query)))))
371
Common Lisp
.lisp
11
28
90
0.613445
karason/lisp-robit
3
0
4
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
58dff325dec877eb9bcd75571777b9bc2c9e20128c32eb30780b292d4ee11775
16,941
[ -1 ]
16,945
robit.manual
karason_lisp-robit/robit.manual
#manual for robit.lisp robit.lisp is an internet relay chat automaton defined in common lisp #prerequisites for execution common lisp interpreter (CLISP is assumed) quicklisp system cl-irc library #to execute robit if .robitrc does not exist, evaluate eval-me.lisp #clisp eval-me.lisp evaluate .robitrc && robit.lisp #clisp -i .robitrc -repl robit.lisp whence loaded, call (robit:boot) to begin IRC loop or (in-package :robit) to begin hacking #for source see robit.lisp #for todos see robit.todo #for bug report see robit.bugs #for license see LICENSE.txt
626
Common Lisp
.l
18
29.944444
71
0.723967
karason/lisp-robit
3
0
4
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
7814824b399cf9500962240eff444fa42a0232e13da22d930a493b13fb1482ac
16,945
[ -1 ]
16,947
.logrc
karason_lisp-robit/logs/.logrc
"clear all syntax syntax clear "time syntax match Identifier /[0-9][0-9]:[0-9][0-9]:[0-9][0-9]/ "channel syntax region Comment start=/#/ end=/ / oneline "user syntax region Statement start=/</ end=/>/ oneline "hyperlink syntax region Type start=/www./ end=/[\n\ ]/ syntax region Type start=/http:./ end=/[\n\ ]/ syntax region Type start=/https:./ end=/[\n\ ]/ "quote syntax region PreProc start=/"/ end=/"/ oneline "s-expression syntax match String /(.*)/
463
Common Lisp
.l
16
27.5
58
0.693878
karason/lisp-robit
3
0
4
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
351d30c5c2af1efdc0e708f32689a597c4844098ea69ef31c99712b59f6ac13c
16,947
[ -1 ]
16,967
parametryk.lsp
kmartenczuk_AutoLISP/Parametryk_zlacze_postaciowe_wieloboczne_trojkatne/param/parametryk.lsp
;;;;;;;;; ZLACZE WIELOBOCZNE TRÓJKATNE ;;;;;;;;; ;Kamil Martenczuk Autodesk Authorized Developer; ;;;;;;;;;;;;;; ADN ID DEPL2710 ;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;; 05/2020 ;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;Przeliczenia katów (defun kat (w) (* pi (/ w 180.0))) (defun katWew (w) (* pi (/ (- 180.0 w) 180.0))) ;Deklaracja funkcji (defun trojk () (setvar 'osmode 0) ;Menu wybór srednicy zlacza (initget 1 "30 35 40 45 50 55 60 65 70 75") (setq d (getreal "\nPodaj srednice zlacza d (mm)[30/35/40/45/50/55/60/65/70/75]: ")) ;Wgranie tablicy (setq zlacza (open (strcat kxx "tablice/parametryk_zlacza_dane.txt") "r")) (setq linia (read-line zlacza)) (setq li (atof (substr linia 1 4))) (setq wyzn (atof (substr linia 4 4))) ;Przeszukanie tablicy (setq wi 1) (while (> d li) (setq linia (read-line zlacza)) (setq li (atof (substr linia 1 4))) (setq wi (+ wi 1)) ) (close zlacza) ;Przypisywanie wymiarow posrednich (setq d2 (atof (substr linia 9 4))) (setq d3 (atof (substr linia 4 4))) (setq e1 (atof (substr linia 14 4))) (setq wsk (atof (substr linia 19 3))) (setq Pp0 (atof (substr linia 23 3))) (setq skala (/ d3 wyzn)) (setq r1 (/ d2 2)) (setq r2 (/ d3 2)) ;Deklaracja P0 (setq p0 (getpoint "\nWskaz punkt wstawienia widoku: ")) (command "_.zoom" "_w" (polar p0 (kat 225) 100) (polar p0 (kat 45) 100)) ;Wyznaczanie punktów (command "_.layer" "_s" "0" "_lw" "0.3" "0" "") (setq p1 (polar p0 (kat 90) r2)) (setq p2 (polar p0 (kat -90) r2)) (setq p3 (polar p0 (kat 90) r1)) (setq p4 (polar p0 (kat -90) r1)) (setq pW1 (polar p0 (kat 180) (* d3 0.8))) (setq pW2 (polar p0 (kat 180) d3)) (setq pW3 (polar p0 (kat 180) (* d3 1.2))) (setq pW4 (polar p2 (kat -45) (* 1.2 d3))) ;Wymiarowanie (command "_.-layer" "_n" "wymiary" "_s" "wymiary" "_color" "_T" "0,255,0" "wymiary" "") (command "_.dim" "_ver" p1 p2 pW3 (strcat "%%c " (rtos d3 2 1 ) "mm") "_ver" p2 p3 pW2 (strcat "%%c " (rtos d 2 1 ) "mm") "_ver" p3 p4 pW1 (strcat "%%c " (rtos d2 2 1 ) "mm") "_ver" p1 p3 pW4 (strcat "2e1 " (rtos (* 2 e1) 2 1 ) "mm") "_exit") ;Wgranie bloku zlacza (command "_.-layer" "_n" "P3G" "_s" "P3G" "_color" "_T" "255,0,0" "P3G" "_lw" "0.3" "P3G" "") (command "_.insert" (strcat kxx "bloki/parametryk_blok") p0 skala skala "") ;Zapis Piasty i Zlacza (command "_.-layer" "_n" "other" "_s" "other" "_color" "_T" "100,100,100" "other" "_lw" "0.3" "other" "") (command "_.circle" p0 "_d" d2) (command "_.circle" p0 "_d" d3) (command "_.circle" p0 "_d" (* d3 1.3)) (command "_.-layer" "_n" "Centers" "_s" "Centers" "_color" "_T" "100,100,100" "Centers" "_lw" "0.15" "Centers" "") (command "_.centermark" p1 "") (command "_.layer" "_s" "0" "") ;Wstawianie widoku 2 (initget 1 "Tak Nie") (setq wid2 (getkword "\nCzy wstawic kolejny widok? [Tak/Nie]: ")) (cond ((= wid2 "Tak") ;Deklaracja dlugosci (setq l (getreal "\nPodaj dlugosc (mm): ")) ;Rekonfiguracja punktów pierwotnych (setq p5 (polar p0 (kat 90) (* 1.5 r1))) (setq p6 (polar p0 (kat -90) (* 1.5 r1))) (setq p7 (polar p0 (kat 90) (* skala 7.93))) (setq p8 (polar p0 (kat -90) r2)) (setq p9 (polar p0 (kat 90) r1)) ;Wyznaczenie punktów (setq p10 (polar p0 (kat -90) r1)) (setq p11 (polar p5 (kat 0) (* 1.4 d3))) (setq p12 (polar p6 (kat 0) (* 1.4 d3))) (setq p13 (polar p7 (kat 0) (* 1.4 d3))) (setq p14 (polar p8 (kat 0) (- (* 1.4 d3) 10))) (setq p15 (polar p9 (kat 0) (- (* 1.4 d3) 10))) (setq p16 (polar p10 (kat 0) (* 1.4 d3))) (setq p17 (polar p16 (kat 0) 30)) (command "_.zoom" "_w" (polar p0 (kat 225) 100) (polar p12 (kat 45) (+ 50 l))) ;Zapis widoku 2 (command "_.layer" "_s" "other" "") (command "_pline" (polar p12 (kat 0) l) "_w" 0.3 0.3 p12 p11 (polar p11 (kat 0) l) "_cl") (command "_.layer" "_n" "zig" "_s" "zig" "_color" "_T" "255,0,0" "zig" "_ltype" "Amzigzag" "zig" "_lw" "0.15" "zig" "") (command "_line" p15 p14 "") (command "_line" (polar p14 0 (+ 20 l)) (polar p15 0 (+ 20 l)) "") (command "_.layer" "_s" "P3G" "") (command "_line" p15 "@10<0" "") (command "_line" p14 "@10<0" "") (command "_line" (polar p7 0 (- (* 1.4 d3) 10)) "@10<0" "") (command "_line" (polar p7 0 (+ (* 1.4 d3) l)) "@10<0" "") (command "_line" (polar p14 0 (+ 10 l)) "@10<0" "") (command "_line" (polar p15 0 (+ 10 l)) "@10<0" "") (command "_.layer" "_n" "sym" "_s" "sym" "_lw" "0.15" "sym" "_color" "_T" "100,100,100" "sym" "_ltype" "Center" "sym" "") (command "_line" (polar p0 0 (- (* 1.3 d3) 15)) (polar p0 0 (+ (* 1.3 d3) (+ 15 l))) "") ;Wymiarowanie (command "_.-layer" "_s" "wymiary" "") (command "_.dim" "_hor" p11 (polar p11 0 l) (polar p11 (kat 90) (/ r1 2)) (strcat "L=" (rtos l 2 1 ) "mm") "_exit") (command "_.layer" "_s" "0" "") ) ) (setvar 'osmode 1) ) (trojk) (setq trojk nil)
4,985
Common Lisp
.l
113
40.19469
124
0.541735
kmartenczuk/AutoLISP
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
b33838c1b42ff8311a13680c5c6482b7776458e3d6a12c6d4528dd05bccd4a9a
16,967
[ -1 ]
16,968
parametryk_zlacza_dane.txt
kmartenczuk_AutoLISP/Parametryk_zlacze_postaciowe_wieloboczne_trojkatne/tablice/parametryk_zlacza_dane.txt
30 32.0 28.0 1.00 0.6 150 35 37.5 32.5 1.25 0.6 150 40 42.8 37.2 1.40 0.6 150 45 48.2 41.8 1.60 0.6 150 50 53.6 46.4 1.80 0.6 150 55 59.0 51.0 2.00 0.6 150 60 64.5 55.5 2.25 0.6 150 65 69.9 60.1 2.45 0.6 150 70 75.6 64.4 2.80 0.6 150 75 81.3 68.7 3.15 0.6 150
269
Common Lisp
.l
10
25
27
0.615385
kmartenczuk/AutoLISP
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
f71bf08c930cb7b1b10b7241f0ff70189f811c711b8d9f6652fca5a1a4abcd0c
16,968
[ -1 ]
16,984
get_circles_together_and_color_them.lsp
CiganOliviu_AutoLISP-autocad/get_circles_together_and_color_them.lsp
(defun get_average(sum index) (setq result (/ sum index)) (setq result result) ) (defun set_new_center(entities center) (setq index 0) (repeat (sslength circles) (setq circle (entget (ssname circles index))) (setq circle (subst (cons 10 center) (assoc 10 circle) circle)) (entmod circle) (setq index (+ index 1)) ) ) (defun C:MOVE_CIRCLES() (setq sumOx 0) (setq sumOy 0) (setq circles (ssget "X" '((0 . "CIRCLE")) )) (setq index 0) (repeat (sslength circles) (setq circle (entget (ssname circles index))) (setq circle (subst (cons 62 index) (assoc 62 circle) circle) circle (append circle (list (cons 62 index))) ) (setq center (cdr (assoc 10 circle))) (setq Ox (car center)) (setq Oy (cadr center)) (setq sumOx (+ sumOx Ox)) (setq sumOy (+ sumOy Oy)) (entmod circle) (setq index (+ 1 index)) ) (princ) (setq centerOx (get_average sumOx index)) (setq centerOy (get_average sumOy index)) (setq newCenter (list centerOx centerOy 0.0)) (set_new_center circles newCenter) (princ) )
1,194
Common Lisp
.cl
39
24.076923
73
0.601232
CiganOliviu/AutoLISP-autocad
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
1a2eabd3f84d878ae3a4fe7e43ed03eebf3a3d212ed28b36f207ac7adca3aa1e
16,984
[ -1 ]
16,985
draw_circle_based_on_conditions.LSP
CiganOliviu_AutoLISP-autocad/draw_circle_based_on_conditions.LSP
(defun projdist (p0 p1) (list (abs (- (car p0) (car p1))) (abs (- (cadr p0) (cadr p1))) ) ) (defun C:CIRCLEC (/ radius start_rectangle_point) (setq start_rectangle_point (getpoint "Pick first point of rectangle")) (setq second_rectangle_point (getcorner start_rectangle_point "Pick second point of rectangle")) (setq width (projdist start_rectangle_point second_rectangle_point)) (setq part_one (car width)) (setq part_two (cadr width)) (setq least_size (min part_one part_two)) (setq center (getpoint "Set circle center")) (setq radius (getdist center "Set radius for circle")) (while (> radius (/ least_size 2)) (setq center (getpoint "Set circle center")) (setq radius (getdist center "Set radius for circle")) ) (command "circle" center radius) )
816
Common Lisp
.cl
20
36.55
99
0.691421
CiganOliviu/AutoLISP-autocad
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
2c7e8d530e9a90b5671b6bb4b407a16bd98ac933536a53d3a84766c87c087324
16,985
[ -1 ]
16,986
get_circles_together.lsp
CiganOliviu_AutoLISP-autocad/get_circles_together.lsp
(defun get_average(sum index) (setq result (/ sum index)) (setq result result) ) (defun set_new_center(entities center) (setq index 0) (repeat (sslength circles) (setq circle (entget (ssname circles index))) (setq circle (subst (cons 10 newCenter) (assoc 10 circle) circle)) (entmod circle) (setq index (+ index 1)) ) ) (defun C:MOVE_CIRCLES() (setq sumOx 0) (setq sumOy 0) (setq circles (ssget "X" '((0 . "CIRCLE")) )) (setq index 0) (repeat (sslength circles) (setq circle (entget (ssname circles index))) (setq center (cdr (assoc 10 circle))) (setq Ox (car center)) (setq Oy (cadr center)) (setq sumOx (+ sumOx Ox)) (setq sumOy (+ sumOy Oy)) (entmod circle) (setq index (+ 1 index)) ) (princ) (setq centerOx (get_average sumOx index)) (setq centerOy (get_average sumOy index)) (setq newCenter (list centerOx centerOy 0.0)) (set_new_center circles newCenter) (princ) )
993
Common Lisp
.cl
35
23.885714
70
0.657297
CiganOliviu/AutoLISP-autocad
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
75d3e16df1449d26cd3a23f3ae2be4f76bd281110af5c3c49fc601623a82903c
16,986
[ -1 ]
16,988
simple_sentence.lsp
CiganOliviu_AutoLISP-autocad/simple_sentence.lsp
(defun first_sentence (a b) (setq result (+ 22 (* a (+ 13 b)))) ) (defun second_sentence (a b c d) (setq result (+ (* a b) (* c d))) )
139
Common Lisp
.l
6
21.5
37
0.548872
CiganOliviu/AutoLISP-autocad
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
0701ec1d6d0edef41e9c1420a1418efdec0c95b9655ff394ace44199568790a9
16,988
[ -1 ]
16,990
PD_SEARCH.lsp
CiganOliviu_AutoLISP-autocad/PD_SEARCH.lsp
(defun C:PD_ADDENTRY ( / fname lname age entry) (initget 1) (setq fname (getstring "\nEnter person's first name: ")) (initget 1) (setq lname (getstring "\nEnter person's last name: ")) (initget 7) (setq age (getint "\nEnter person's age: ")) (setq entry (list (cons 'FN fname) (cons 'LN lname) (cons 'AGE age)) PD_DATA (append PD_DATA (list entry)) ) (princ) ) (defun C:PD_LIST ( / current entry counter) (setq current PD_DATA counter 1) (while current (setq entry (car current)) (princ (strcat "\nRecord #" (itoa counter) ": " (cdr (assoc 'LN entry)) ", " (cdr (assoc 'FN entry)) ". Age " (itoa (cdr (assoc 'AGE entry))) ) ) (setq current (cdr current) counter (1+ counter) ) ) (princ) ) (defun C:PD_SEARCH(/ current entry counter) (setq inferior_limit (getint "\nEnter inferior age: ")) (setq superior_limit (getint "\nEnter superior age: ")) (setq current PD_DATA counter 1) (while current (setq entry (car current)) (if (> (cdr (assoc 'AGE entry)) inferior_limit) (if (< (cdr (assoc 'AGE entry)) superior_limit) (princ (strcat "\nRecord #" (itoa counter) ": " (cdr (assoc 'LN entry)) ", " (cdr (assoc 'FN entry)) ". Age " (itoa (cdr (assoc 'AGE entry))) ) ) ) ) (setq current (cdr current) counter (1+ counter) ) ) (princ) )
1,424
Common Lisp
.l
52
22.634615
70
0.6
CiganOliviu/AutoLISP-autocad
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
c567eab6549402294629868a63cc5deb721a97cdb7fdf248b25e8d9de6c6ac58
16,990
[ -1 ]
16,991
draw_david_star.lsp
CiganOliviu_AutoLISP-autocad/draw_david_star.lsp
(defun C:DRAW_DAVID_STAR (/ star_center star_radius) (setq star_center (getpoint "\nChoose star center:")) (setq star_radius (getdist star_center "\nChoose star radius:")) (command "polygon" 3 star_center "inscribed" star_radius) (command "rotate" (entlast) "" star_center "180") (command "polygon" 3 star_center "inscribed" star_radius) )
354
Common Lisp
.l
7
47.571429
65
0.726471
CiganOliviu/AutoLISP-autocad
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
07422ba6daa7c1721765d6d1a4477e49eadf3f669948f6627c5213912d2a9c63
16,991
[ -1 ]
16,992
simple_formula.lsp
CiganOliviu_AutoLISP-autocad/simple_formula.lsp
(defun get_sum(x) (setq end_point 20) (setq index 2) (setq result 0) (while (<= index end_point) (if (= (rem index 2) 0) (setq result (+ result (* x index))) ) (if (= (rem index 2) 1) (setq result (+ result (+ x index))) ) (setq index (+ 1 index)) ) (setq result result) )
328
Common Lisp
.l
15
17.2
42
0.539474
CiganOliviu/AutoLISP-autocad
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
fc306c22dbfc6611ce11620ea1dde00cfbe2759e8451d752508a4e8facc6601a
16,992
[ -1 ]
17,015
ex-08-41.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-41.lisp
; file: ex-08-41.lisp ; author: Jon David ; date: Wednesday, September 24, 2014 ; description: ; exercise 8.41 - Write a function SUM-TREE that returns the sum of ; all the numbers appearing in a tree. Nonnumbers should be ; ignored. (SUM-TREE '((3 BEARS) (3 BOWLS) 1 (GIRL))) should return ; seven. ; (defun sum-tree (x) (cond ((numberp x) x) ((atom x) 0) (t (+ (sum-tree (car x)) (sum-tree (cdr x))))))
425
Common Lisp
.lisp
14
28.571429
69
0.652068
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
e07b777bc8c290f605b99e6e30dfa83444b60bcf56f5ca6908a8d72d6b42737d
17,015
[ -1 ]
17,016
ex-08-56.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-56.lisp
; file: ex-08-56.lisp ; author: Jon David ; date: Monday, September 29, 2014 ; description: ; exercise 8.56 - Write EVERY-OTHER, a recursive function that ; returns every other element of a list-the first, third, fifth, ; and so on. (EVERY-OTHER '(A B C D E F G)) should return (A C E G). ; (EVERY-OTHER '(I CAME I SAW I CONQUERED)) should return (I I I). (defun every-other-recursive (counter list) (cond ((null list) nil) ((oddp counter) (cons (car list) (every-other-recursive (+ counter 1) (cdr list)))) (t (every-other-recursive (+ counter 1) (cdr list))))) (defun every-other (list) (every-other-recursive 1 list))
652
Common Lisp
.lisp
16
38.3125
70
0.682035
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
7beeb3cf4b6cc771ce1336b4d30936391b49f634df00fdd2f24804fe9d539540
17,016
[ -1 ]
17,017
ex-08-59.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-59.lisp
; file: ex-08-59.lisp ; author: Jon David ; date: Monday, September 29, 2014 ; description: ; exercise 8.59 - Here is another definition of the factorial ; function: ; Factorial(0) = 1 ; Factorial(N) = Factorial(N+1) / (N+1) ; ; Verify that these equations are true. Is the definition recursive? ; Write a Lisp function that implements it. For which inputs will ; the function return the correct answer? For which inputs will it ; fail to return the correct answer? Which of the three rules of ; recursion does the definition violate? ; Notes: ; So these equations are true. ; 0! = 1 ; n! = (n+1)! / (n+1) = ((n+1)*(n)*(n-1)*(n-2)*...*3*2*1) / (n+1)) ; Notice, that the (n+1) in the numerator cancels with the ; (n+1) in the denominator. What's left is n!. ; ; However, the recursive implementation is true only when n=0. ; This is because if n>0, this function will recurse infinitely. ; The problem becomes larger and larger at each recursion instead ; of smaller and smaller. (defun my-factorial (n) (cond ((zerop n) 1) (t (/ (my-factorial (+ n 1)) (+ n 1)))))
1,114
Common Lisp
.lisp
28
38.642857
70
0.675576
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
e32e02dc25199ea4174ba9629a90a543edb4d882d01511c43364f23659bcf19b
17,017
[ -1 ]
17,018
ex-08-22.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-22.lisp
; file: ex-08-22.lisp ; author: Jon David ; date: Sunday, August 24, 2014 ; description: ; exercise 8.22 - Write a recursive function ALL-EQUAL that returns ; T if the first element of a list is equal to the second, the ; second is equal to the third, the third is equal to the fourth, ; and so on. (ALL-EQUAL '(I I I I)) should return T. ; (ALL-EQUAL '(I I E I)) should return NIL. ALL-EQUAL should return ; T for lists with less than two elements. Does this problem require ; augmentation. Which template will you use to solve it? (defun all-equal (list) (cond ((< (length list) 2) t) (t (and (equal (car list) (cadr list)) (all-equal (cdr list))))))
673
Common Lisp
.lisp
15
43.466667
70
0.697108
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
15d8e3cea1fde0059dd5339a63cd8a50a2abba743a29a93eae533cf1f1f618df
17,018
[ -1 ]
17,019
ex-08-40.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-40.lisp
; file: ex-08-40.lisp ; author: Jon David ; date: Wednesday, September 24, 2014 ; description: ; exercise 8.40 - Write COUNT-CONS, a function that returns the ; number of cons cells in a tree. (COUNT-CONS '(FOOD)) should ; return one. (COUNT-CONS '(FOO BAR)) should return two. ; (COUNT-CONS '((FOO))) should also return two, since the list ; ((FOO)) requires two cons cells. (COUNT-CONS 'FRED) should ; return zero. ; ; usage: ; (load "ex-08-40.lisp") ; (defun count-cons (x) (cond ((atom x) 0) (t (+ 1 (count-cons (car x)) (count-cons (cdr x))))))
582
Common Lisp
.lisp
19
28.736842
65
0.646536
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
996530d15983411d4c3c28d4b31205a71e7a94ced7894b918e3c966f2ecec317
17,019
[ -1 ]
17,020
ex-08-52.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-52.lisp
; file: ex-08-52.lisp ; author: Jon David ; date: Sunday, September 28, 2014 ; description: ; exercise 8.52 - Write MY-UNION, a recursive version of UNION. ; ; Note: ; the book's solution is more efficient. It begins the union set ; with all of the elements in X and then for each element in Y ; not in X, it appends it to the union-set. ; ; (defun my-union (x y) ; (append x (union-recursively x y))) ; ; (defun union-recursively (x y) ; (cond ((null y) nil) ; ((member (first y) x) ; (union-recursively x (rest y))) ; if already in x, continue ; (t (cons (first y) ; (union-recursively x (rest y)))))) (defun my-union-recursive (Z X Y) (cond ((null X) Z) ((and (member (car X) Y) (not (member (car X) Z))) (my-union-recursive (cons (car X) Z) (cdr X) Y)) (t (my-union-recursive Z (cdr X) Y)))) (defun my-union (X Y) (my-union-recursive nil X Y))
940
Common Lisp
.lisp
28
31.785714
72
0.612155
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
8d07bbb7e81b970f2d716bee5b63845ed9b5336fb3071dcf25b9fc903f0cf496
17,020
[ -1 ]
17,021
ex-08-64.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-64.lisp
; file: ex-08-64.lisp ; author: Jon David ; date: Monday, October 21, 2014 ; description: ; exercise 8.64 - Write a TREE-FIND-IF operator that returns the ; first non-NIL atom of a tree that satisfies a predicate. ; (TREE-FIND-IF #'ODDP '((2 4) (5 6) 7)) should return 5. (defun tree-find-if (fn x) (cond ((null x) x) ((atom x) (if (funcall fn x) x nil)) (t (or (tree-find-if fn (car x)) (tree-find-if fn (cdr x)))))) (defun ut-ex-08-64 () (let* ((fn #'oddp) (list '((2 4) (5 6) 7)) (actual (tree-find-if fn list)) (expected 5)) (equal actual expected)))
587
Common Lisp
.lisp
18
30.166667
66
0.622575
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
ff7c3edd9fbb2fdb77ba2e35a4227a226c3a3b02831bf3deff9d1f9fa7ad95f5
17,021
[ -1 ]
17,022
ex-08-09.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-09.lisp
; file: ex-08-09.lisp ; author: Jon David ; date: Monday, August 18, 2014 ; description: ; exercise 8.9 - Write a recursive version of NTH. Call it REC-NTH. (defun rec-nth (count list) (cond ((zerop count) (car list)) (t (rec-nth (- count 1) (cdr list)))))
265
Common Lisp
.lisp
8
31.375
69
0.673228
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
c4a8dfd54120e5e7ef9af9400f1bb3e4824407bb9977bcb41d9acdf116497c96
17,022
[ -1 ]
17,023
ex-08-43.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-43.lisp
; file: ex-08-43.lisp ; author: Jon David ; date: Wednesday, September 24, 2014 ; description: ; exercise 8.43 - Write FLATTEN, a function that returns all the ; elements of an arbitrarily nested list in a single-level list. ; (FLATTEN '((A B (R)) A C (A D ((A (B)) R) A))) should return ; (A B R A C A D A B R A). ; ; notes: ; I had trouble with this one. This is actually the same as the ; book's solution. Notice the expression: ; (and (cdr list) (flatten (cdr))) ; This expression is used to get rid of the excess NILs at the end ; of the append. (defun flatten (list) (cond ((atom list) (list list)) (t (append (flatten (car list)) (and (cdr list) (flatten (cdr list)))))))
717
Common Lisp
.lisp
19
35.894737
68
0.653295
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
8df39213dce6e48cc34e60eee7bf089b06a2ddc64cf49cce5fd6c4058b78aebb
17,023
[ -1 ]
17,024
ex-08-24.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-24.lisp
; file: ex-08-24.lisp ; author: Jon David ; date: Sunday, August 24, 2014 ; description: ; exercise 8.24 - Write COUNT-DOWN, a function that counts down from ; n using list-consing recursion. (COUNT-DOWN 5) should produce the ; list (5 4 3 2 1). (defun count-down (n) (cond ((zerop n) nil) (t (cons n (count-down (- n 1))))))
336
Common Lisp
.lisp
10
32.2
70
0.673846
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
e7ebc79ec22ed99cd66e139ec74d1fbcbc981286bbc83491fdf1bd655bacfb66
17,024
[ -1 ]
17,025
ex-08-53.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-53.lisp
; file: ex-08-53.lisp ; author: Jon David ; date: Sunday, September 28, 2014 ; description: ; exercise 8.53 - Write LARGEST-EVEN, a recursive function that ; returns the largest even number in a list of nonnegative integers. ; (LARGEST-EVEN '(5 2 4 3)) should return four. (LARGEST-EVEN NIL) ; should return zero. Use the built-in MAX function, which returns ; the largest of its inputs. (defun largest-even-recursive (max list) (cond ((null list) max) ((> (car list) max) (largest-even-recursive (car list) (cdr list))) (t (largest-even-recursive max (cdr list))))) (defun largest-even (num-list) (largest-even-recursive 0 num-list))
661
Common Lisp
.lisp
16
39.3125
70
0.720565
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
918f2933c9caf15fdee727ee2ad26580c052c77293120f990f2262cb0f6c50d7
17,025
[ -1 ]
17,026
ex-08-50.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-50.lisp
; file: ex-08-50.lisp ; author: Jon David ; date: Sunday, September 28, 2014 ; description: ; exercise 8.50 - Write SUBLISTS, a function that returns the ; successive sublists of a list. (SUBLISTS '(FEE FIE FOE)) should ; return ((FEE FIE FOE) (FIE FOE) (FOE)). (defun sublists (list) (cond ((null list) nil) (t (cons (list list) (sublists (cdr list))))))
370
Common Lisp
.lisp
10
35.2
67
0.684507
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
f0d8df8b94fb25dfbafbcd4b114ca4d6993de2ed25025c34cecd6386c25d9eae
17,026
[ -1 ]
17,027
ex-08-51.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-51.lisp
; file: ex-08-51.lisp ; author: Jon David ; date: Sunday, September 28, 2014 ; description: ; exercise 8.51 - The simplest way to write MY-REVERSE, a recursive ; version of REVERSE, is with a helping function plus a recursive ; function of two inputs. Write this version of MY-REVERSE. (defun my-reverse-recursive (list-a list-b) (cond ((null list-b) list-a) (t (my-reverse-recursive (cons (car list-b) list-a) (cdr list-b))))) (defun my-reverse (list) (my-reverse-recursive nil list))
509
Common Lisp
.lisp
13
36.846154
69
0.717791
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
f2894f8366292eab89bfd95054a571084c22bbb15c440421c7e08c947f5d9e3b
17,027
[ -1 ]
17,028
ex-08-47.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-47.lisp
; file: ex-08-47.lisp ; author: Jon David ; date: Sunday, September 28, 2014 ; description: ; exercise 8.47 - Write MAKE-LOAf, a function that returns a loaf of ; size N. (MAKE-LOAF 4) should return (X X X X). Use IF instead of ; COND. (defun make-loaf (n) (if (zerop n) nil (cons 'X (make-loaf (- n 1)))))
333
Common Lisp
.lisp
11
27.545455
70
0.640379
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
7e67c970e9647bca8ccd904b11612917f5b4b9b1df2591f22fd3cd796caa23e1
17,028
[ -1 ]
17,029
ex-08-44.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-44.lisp
; file: ex-08-44.lisp ; author: Jon David ; date: Wednesday, September 24, 2014 ; description: ; exercise 8.44 - Write a function TREE-DEPTH that returns the ; maximum depth of a binary tree. (TREE-DEPTH '(a . b)) should ; return one. (TREE-DEPTH '((A B C D))) should return five, and ; (TREE-DEPTH '((A . B) . (C . D))) should return two. ; ; notes: ; I had trouble with this one. I couldn't think of a way to do ; this without using a helper function. But helper functions ; won't be introduced until the next section in the book... ; ; The book's solution is much more elegant. Here it is: ; ; (defun max-depth (tree) ; (cond ((atom tree) 0) ; (t (+ 1 (max (tree-depth (car tree)) ; (tree-depth (cdr tree))))))) ; ; Note: I thought Common Lisp allowed for function overloading. ; However, I had trouble when my helper function was also ; named max-depth. Hmmm... need to investigate... (defun max-depth-h (current-depth list) (cond ((atom list) current-depth) (t (max (max-depth-h 1 (car list)) (max-depth-h (+ 1 current-depth) (cdr list)))))) (defun max-depth (list) (max-depth-h 0 list))
1,185
Common Lisp
.lisp
30
38.2
66
0.643539
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
b9e998dad128900210bc7052bdeb5e39bcb9c03f1e17693ca5dae68379206447
17,029
[ -1 ]
17,030
ex-08-61.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-61.lisp
; file: ex-08-61.lisp ; author: Jon David ; date: Monday, October 21, 2014 ; description: ; exercise 8.61 - Write a tail-recursive version of COUNT-UP. (defun count-up (loaf) (tr-count-up loaf 0)) (defun tr-count-up (loaf count) (cond ((null loaf) count) (t (tr-count-up (cdr loaf) (1+ count))))) (defun ut-ex-08-61 () (let* ((loaf '(X X X X)) (actual (count-up loaf)) (expected (length loaf))) (equal actual expected)))
442
Common Lisp
.lisp
15
27.2
63
0.659574
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
a3139d5168ccacccf20f308cec86e8896c3b40b3f9f04d0255cefb1a27e224de
17,030
[ -1 ]
17,031
ex-08-10.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-10.lisp
; file: ex-08-10.lisp ; author: Jon David ; date: Monday, August 18, 2014 ; description: ; exercise 8.10 - For x a nonnegative integer and y a positive ; integer, x+y equals x + 1 + (y - 1). ; If y is zero then x+y equals x. Use these equations to build ; a recursive version of + called REC-PLUS out of ADD1, SUB1, ; COND and ZEROP. You'll have to write ADD1 and SUB1, too. (defun add1 (n) (+ n 1)) (defun sub1 (n) (- n 1)) (defun rec-plus (num-list) (cond ((null num-list) 0) (
502
Common Lisp
.lisp
16
29.625
64
0.663202
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
56faf94b20cdccae45cce90c1f5f978b63801aaf8ba7e98be4c94ed028ad4ca6
17,031
[ -1 ]
17,032
ex-08-07.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-07.lisp
; file: ex-08-07.lisp ; author: Jon David ; date: Monday, August 18, 2014 ; description: ; exercise 8.7 - Write a recursive version of MEMBER. Call it ; REC-MEMBER so you don't redefine the built-in MEMBER function. (defun rec-member (item list) (cond ((null list) nil) (t (or (equal item (car list)) (rec-member item (cdr list))))))
344
Common Lisp
.lisp
9
36.555556
66
0.701807
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
7d463a9c4d6471e1971eebb142fe78b3bb836293f2cd43f42d0f81916a7cfb5c
17,032
[ -1 ]
17,033
ex-08-33.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-33.lisp
; file: ex-08-33.lisp ; author: Jon David ; date: Sunday, August 24, 2014 ; description: ; exercise 8.33 - Write my-remove, a recursive version of the REMOVE ; function. (defun my-remove (x list) (cond ((null list) nil) ((equal x (car list)) (my-remove x (cdr list))) (t (cons (car list) (my-remove x (cdr list))))))
326
Common Lisp
.lisp
10
31.1
70
0.669841
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
40a75e352bf5dde1bc8926f44e8631dff083974ab1cea3490147aeecb2c65413
17,033
[ -1 ]
17,034
ex-08-67.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-67.lisp
; file: ex-08-67.lisp ; author: Jon David ; date: Saturday, November 15, 2014 ; description: ; Write a predicate LEGALP that returns T if its input is a legal ; arithmetic expression. For example, (LEGALP 4) and ; (LEGALP '((2 * 2) - 3)) should return T. (LEGALP NIL) and ; (LEGALP '(A B C D)) should return NIL. (load "ex-08-66.lisp") (defun legalp (expr) (not (null (arith-eval expr))))
400
Common Lisp
.lisp
11
35.090909
67
0.680412
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
687a2e7dafd0fe4f0fd6b45936c1c169ba583cd36aae885700c60191d5590c92
17,034
[ -1 ]
17,035
ex-08-57.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-57.lisp
; file: ex-08-57.lisp ; author: Jon David ; date: Monday, September 29, 2014 ; description: ; exercise 8.57 - Write LEFT-HALF, a recursive function in two parts ; that returns the first n/2 elements of a list of length n. Write ; your function so that the list does not have to be of even length. ; (LEFT-HALF '(A B C D E)) should return (A B C). ; (LEFT-HALF '(1 2 3 4 5 6 7 8)) should return (1 2 3 4). You may ; use LENGTH but not REVERSE in your definition. (defun left-half-recursive (n list) (cond ((<= n 0) nil) (t (cons (car list) (left-half-recursive (- n 1) (cdr list)))))) (defun left-half (list) (left-half-recursive (/ (length list) 2) list))
680
Common Lisp
.lisp
15
43.533333
70
0.675266
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
d8a399be66d61ae650f36acf4a7ee0bdaf1a8aa423169d0b835cd869c88b448d
17,035
[ -1 ]
17,036
ex-08-62.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-62.lisp
; file: ex-08-62.lisp ; author: Jon David ; date: Monday, October 21, 2014 ; description: ; exercise 8.62 - Write a tail-recursive version of FACT. (defun my-fact (n) (tr-fact n 1)) (defun tr-fact (n product) (cond ((zerop n) product) (t (tr-fact (- n 1) (* product n))))) (defun ut-ex-08-62 () (let* ((n 4) (expected (fact n)) (actual (* 4 3 2 1))) (equal expected actual)))
397
Common Lisp
.lisp
15
24.2
59
0.62963
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
14df651baafcf337a2500457da6a9e2612971f51ad03a0a632b0efb478e62ed1
17,036
[ -1 ]
17,037
ex-08-08.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-08.lisp
; file: ex-08-08.lisp ; author: Jon David ; date: Monday, August 18, 2014 ; description: ; exercise 8.8 - Write a recursive version of ASSOC. Call it ; REC-ASSOC. (defun rec-assoc (index table) (let ((first-item (car table))) (cond ((null table) nil) ((equal index (car first-item)) first-item) (t (rec-assoc index (cdr table))))))
351
Common Lisp
.lisp
11
29.545455
62
0.670623
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
6b650899c67ac16d1caa3eead0d10fd706550c8638fa288d7094636a3541351b
17,037
[ -1 ]
17,038
ex-08-42.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-42.lisp
; file: ex-08-42.lisp ; author: Jon David ; date: Wednesday, September 24, 2014 ; description: ; exercise 8.42 - Write MY-SUBST, a recursive version of the ; SUBST function. ; ; usage: ; (load "ex-08-42.lisp") ; (my-subst 'a 'b '(a b c)) => (A A C) ; (my-subst 'a '(b c) '(a (b c) d e)) => (A A D E) (defun my-subst (new old list) (cond ((equal list old) new) ((atom list) list) (t (cons (my-subst new old (car list)) (my-subst new old (cdr list))))))
469
Common Lisp
.lisp
16
27.875
62
0.609272
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
6bac0f83209fac3603dc61966884ee6cf0a4b131da123b8be900439a88779b06
17,038
[ -1 ]
17,039
ex-08-32.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-32.lisp
; file: ex-08-32.lisp ; author: Jon David ; date: Sunday, August 24, 2014 ; description: ; exercise 8.32 - Write the function SUM-NUMERIC-ELEMENTS, which ; adds up all the numbers in a list and ignores the non-numbers. ; (SUM-NUMERIC-ELEMENTS '(3 BEARS 3 BOWLS AND 1 GIRL)) should ; return 7. (defun sum-numeric-elements (list) (cond ((null list) 0) ((numberp (car list)) (+ (car list) (sum-numeric-elements (cdr list)))) (t (sum-numeric-elements (cdr list)))))
478
Common Lisp
.lisp
13
35.153846
66
0.697624
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
52c923cbe01d3be368e097c3cff2241340d3f717773398f8bbbb581b04718848
17,039
[ -1 ]
17,040
ex-08-48.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-48.lisp
; file: ex-08-48.lisp ; author: Jon David ; date: Sunday, September 28, 2014 ; description: ; exercise 8.48 - Write a recursive function BURY that buries an ; item under n levels of parentheses. (BURY 'FRED 2) should return ; ((FRED)), while (BURY 'FRED 5) should return (((((FRED))))). Which ; recursion template did you use? (defun bury (name depth) (cond ((zerop depth) name) (t (list (bury name (- depth 1))))))
432
Common Lisp
.lisp
11
37.545455
70
0.682692
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
98464cf667ead380809e36affada1714020a3395a071ba400d8455bd25957418
17,040
[ -1 ]
17,041
ex-08-60-keyboard-exercise.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-60-keyboard-exercise.lisp
; file: ex-08-60.lisp ; author: Jon David ; date: Monday, September 29, 2014 ; description: ; exercise 8.60 - If the genealogy database is already stored on ; the computer for you, load the file containing it. If not, you ; will have to type it in as it appears in Figure 8-12. Store the ; database in the global variable FAMILY. (setf family '((colin nil nil) (deirdre nil nil) (arthur nil nil) (kate nil nil) (frank nil nil) (linda nil nil) (suzanne colin deirdre) (bruce arthur kate) (charles arthur kate) (david arthur kate) (ellen arthur kate) (george frank linda) (hillary frank linda) (andre nil nil) (tamara bruce suzanne) (vincent bruce suzanne) (wanda nil nil) (ivan george ellen) (julie george ellen) (marie george ellen) (nigel andre hillary) (frederick nil tamara) (zelda vincent wanda) (joshua ivan wanda) (quentin nil nil) (robert quentin julie) (olivia nigel marie) (peter nigel marie) (erica nil nil) (yvette robert zelda) (diane peter erica))) ; a) Write the functions FATHER, MOTHER, PARENTS, and CHILDREN that ; returns a person's father, mother, a list of his or her known ; parents, and a list of his or her children, respectively. ; (FATHER 'SUZANNE) should return COLIN. (PARENTS 'SUZANNE) should ; return (COLIN DEIRDRE). (PARENTS 'FREDERICK) should return ; (TAMARA), since Frederick's father is unknown. ; (CHILDREN 'ARTHUR) should return the set of ; (BRUCE CHARLES DAVID ELLEN). ; ; If any of these functions is given a NIL as input, it should ; return NIL. This feature will be useful later when we write some ; recursive functions. ; note: (name father mother) (defun father (name) (if (null name) nil (cadr (assoc name family)))) (defun mother (name) (if (null name) nil (caddr (assoc name family)))) (defun parents (name) (if (null name) nil (list (father name) (mother name)))) (defun children (name) (if (null name) nil (let ((entries (remove-if-not #'(lambda (x) (or (equal name (cadr x)) (equal name (caddr x)))) family))) (mapcar #'car entries)))) ; b) Write SIBLINGS, a function that returns a list of a person's ; siblings, including genetic half-siblings. (SIBLINGS 'BRUCE) ; should return (CHARLES DAVID ELLEN). (SIBLINGS 'ZELDA) should ; return (JOSHUA). (defun siblings (name) (if (null name) nil (let ((siblings (union (children (father name)) (children (mother name))))) (remove name siblings)))) ; c) Write MAPUNION, an applicative operator that takes a function ; and a list as input, applies the function to every element of ; the list, and computes the union of all the results. An example ; is (MAPUNION #'REST '((1 A B C) (2 E C J) (3 F A B C D))), which ; should return the st (A B C E J F D). Hint: MAPUNION can be ; defined as a combination of two applicative operators you already ; know. (defun mapunion (fn list) (let* ((temp (mapcar fn list))) (reduce #'union temp))) ; d) Write GRANDPARENTS, a function that returns the set of a ; person's grandparents. Use MAPUNION in your solution. (defun grandparents (name) (if (null name) nil (mapunion #'parents (parents name)))) ; e) Write COUSINS, a function that returns the set of a person's ; genetically related first cousins, in other words, the children ; of any of their parent's siblings. (COUSINS 'JULIE) should return ; the set (TAMARA VINCENT NIGEL). Use MAPUNION in your solution. (defun cousins (name) (if (null name) nil (let* ((parents (parents name)) (aunts-uncles (mapunion #'siblings parents)) (first-cousins (mapunion #'children aunts-uncles))) first-cousins))) ; f) Write the two-input recursive predicate DESCENDED-FROM that ; returns a true value if the first person is descended from the ; second. (DESCENDED-FROM 'TAMARA 'ARTHUR) should return T. ; (DESCENDED-FROM 'TAMARA 'LINDA) should return NIL. ; (Hint: You are descended from someone if he is one of your ; parents, or if either your father or mother is descended from ; him. This is a recursive definition). ; (defun descended-from (name descendent) (cond ((null name) nil) ((null descendent) nil) ((member descendent (parents name)) t) (t (or (descended-from (father name) descendent) (descended-from (mother name) descendent))))) ; g) Write the recursive function ANCESTORS that returns a person's ; set of ancestors. (ANCESTORS 'MARIE) should return the set ; (ELLEN ARTHUR KATE GEORGE FRANK LINDA). ; (Hint: A person's ancestors are his parents plus his parents' ; ancestors. This is a recursive definition). (defun ancestors (name) (cond ((null name) nil) (t (let* ((ancestors (union (parents name) (union (ancestors (father name)) (ancestors (mother name)))))) (remove nil ancestors))))) ; h) Write the recursive function GENERATION-GAP that returns the ; number of generations separating a person and one of his or ; her ancestors. ; (GENERATION-GAP 'SUZANNE 'COLIN) should return one. ; (GENERATION-GAP 'FREDERICK 'COLIN) should return three. ; (GENERATION-GAP 'FREDERICK 'LINDA) should return NIL, because ; Linda is not an ancestor of Frederick. (defun generation-gap-recursive (name ancestor) (cond ((null (descended-from name ancestor)) 0) ((member ancestor (parents name)) 1) (t (+ 1 (generation-gap-recursive (father name) ancestor) (generation-gap-recursive (mother name) ancestor))))) (defun generation-gap (name ancestor) (cond ((null name) nil) ((null ancestor) nil) ((descended-from name ancestor) (generation-gap-recursive name ancestor)) (t nil))) ; i) Use the functions you have written to answer the following ; questions: ; ; Q1: Is Robert descended from Deirdre? ; A1: (descended-from 'robert 'deirdre) -> No. ; ; Q2: Who are Yvette's ancestors? ; A2: (ancestors 'yvette) -> (WANDA VINCENT SUZANNE BRUCE ARTHUR ; KATE DEIRDRE COLIN LINDA FRANK ; GEORGE ELLEN QUENTIN JULIE ; ROBERT ZELDA). ; ; Q3: What is the generation gap between Olivia and Frank? ; A3: (generation-gap 'Olivia 'Frank) -> 5. ; ; Q4: Who are peter's cousins? ; A4: (cousins 'peter) -> (ROBERT JOSHUA). ; ; Q5: Who are Olivia's grandparents? ; A5: (grandparents 'olivia) -> (HILLARY ANDRE GEORGE ELLEN).
6,684
Common Lisp
.lisp
166
36.614458
70
0.671136
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
2291e1a15bcdcf834cb18464ece72742af37bf5e25360fba1d708a8eff8900a0
17,041
[ -1 ]
17,042
ex-08-70.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-70.lisp
; file: ex-08-70.lisp ; author: Jon David ; date: Saturday, November 15, 2014 ; description: ; Following is a function FACTORS that returns the list of prime ; factors of a number. It uses the built-in REM function to compute ; the remainder of dividing one number by another. (FACTORS 60) ; returns (2 2 3 5). Try tracing the helping function to see how it ; works. Write a similar function, FACTOR-TREE, that returns a ; factorization tree instead. (FACTOR-TREE 60) should return the ; list (60 2 (30 2 (15 3 5))). ; ; (defun factors (n) ; (factors-help n 2)) ; ; (defun factors-help (n p) ; (cond ((equal n 1) nil) ; ((zerop (rem n p)) ; (cons p (factors-help (/ n p) p))) ; (t (factors-help n (+ p 1))))) (defun factor-tree-help (n p) (cond ((equal n p) n) ((zerop (rem n p)) (list n p (factor-tree-help (/ n p) p))) (t (factor-tree-help n (+ p 1))))) (defun factor-tree (n) (factor-tree-help n 2))
971
Common Lisp
.lisp
27
34.555556
69
0.635494
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
99dfee5fcbe59552807212faf415627c5a4e38426bef2317fa4bba0116f10f50
17,042
[ -1 ]
17,043
ex-08-39.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-39.lisp
; file: ex-08-39.lisp ; author: Jon David ; date: Wednesday, September 24, 2014 ; description: ; exercise 8.39 - Write a function COUNT-ATOMS that returns the ; number of atoms in a tree. (COUNT-ATOMS '(A (B) C)) should return ; five, since in addition to A, B, and C there are two NILs in the ; tree. ; ; usage: ; (load "ex-08-39.lisp") ; (count-atoms '(a (b) c)) (defun count-atoms (x) (cond ((null x) 1) ((atom x) 1) (t (+ (count-atoms (car x)) (count-atoms (cdr x))))))
499
Common Lisp
.lisp
17
27.647059
70
0.634096
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
ff38cccc304099b0b70c1ab61e854fc58ec4e9ed0caa3671101ae25211e27747
17,043
[ -1 ]
17,044
ex-08-25.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-25.lisp
; file: ex-08-25.lisp ; author: Jon David ; date: Sunday, August 24, 2014 ; description: ; exercise 8.25 - How could COUNT-DOWN be used to write an ; applicative version of FACT? (You may skip this problem if you ; haven't read Chapter 7 yet). (defun count-down (n) (cond ((zerop n) nil) (t (cons n (count-down (- n 1)))))) (defun fact (n) (reduce #'* (count-down n)))
381
Common Lisp
.lisp
12
30.25
66
0.668478
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
ad51ac7faa8fd63ebc28a63afc29372b40275214180a7d0b277dfc0be7af8f94
17,044
[ -1 ]
17,045
ex-08-04.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-04.lisp
; file: ex-08-04.lisp ; author: Jon David ; date: Monday, August 18, 2014 ; description: ; exercise 8.4 - We are going to write a function called LAUGH that ; takes a number as input and returns a list of that many HAs. ; (LAUGH 3) should return the list (HA HA HA). (LAUGH 0) should ; return a list with no HAs in it, or, as the dragon might put it, ; "the empty laugh." (defun laugh (n) (cond ((zerop n) nil) (t (cons 'ha (laugh (- n 1))))))
461
Common Lisp
.lisp
12
36.833333
69
0.674157
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
3bcbc691425182db2566c34836e0e02348d7d5ceebe43714b32c03c9efdcc338
17,045
[ -1 ]
17,046
ex-08-65.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-65.lisp
; file: ex-08-65.lisp ; author: Jon David ; date: Monday, October 21, 2014 ; description: ; exercise 8.65 - Use LABELS to write versions of TR-COUNT-SLICES ; and TR-REVERSE. (defun count-slices (loaf) (labels ((tr-count-slices (loaf count) (cond ((null loaf) count) (t (tr-count-slices (cdr loaf) (1+ count)))))) (tr-count-slices loaf 0))) (defun ut-ex-08-65 () (let* ((loaf '(X X X X)) (actual (count-slices loaf)) (expected (length loaf))) (equal actual expected)))
502
Common Lisp
.lisp
16
28.5
67
0.654244
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
7978b192c916f0674167537e5efa8cb83daca9577eaab48c0c2230c1db071778
17,046
[ -1 ]
17,047
ex-08-06.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-06.lisp
; file: ex-08-06.lisp ; author: Jon David ; date: Monday, August 18, 2014 ; description: ; exercise 8.6 - Write ALLODDP, a recursive function that returns T ; if all the numbers in a list are odd. (defun alloddp (num-list) (cond ((null num-list) t) (t (and (oddp (car num-list)) (alloddp (cdr num-list))))))
318
Common Lisp
.lisp
9
33.666667
69
0.689542
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
d2d898c25de54cb3992829a1c671d7738f4be15c699090a23e5944443f9f8df1
17,047
[ -1 ]
17,048
ex-08-63.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-63.lisp
; file: ex-08-63.lisp ; author: Jon David ; date: Monday, October 21, 2014 ; description: ; exercise 8.63 - Write tail-recursive versions of UNION, ; INTERSECTION, and SET-DIFFERENCE. Your functions need not return ; results in the same order as the built-in functions. (defun my-union (X Y) (tr-my-union X Y Y)) (defun tr-my-union (X Y resultSet) (cond ((null X) resultSet) ((member (car X) Y) (tr-my-union (cdr X) Y resultSet)) (t (tr-my-union (cdr X) Y (cons (car X) resultSet))))) (defun ut-ex-08-63 () (let* ((X '(a b c)) (Y '(a d e)) (actual (my-union X Y)) (expected (union X Y))) (null (set-difference actual expected))))
659
Common Lisp
.lisp
19
32.526316
69
0.663522
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
8abf634be143215fc1e3cd27c6dae5a9b17b825f63aec0c25475776897f9909f
17,048
[ -1 ]
17,049
ex-08-18.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-18.lisp
; file: ex-08-18.lisp ; author: Jon David ; date: Sunday, August 24, 2014 ; description: ; exercise 8.18 - Use single-test tail recursion to write ; LAST-ELEMENT, a function that returns the last element of a list. ; LAST-ELEMENT should recursively travel down the list until it ; reaches the last cons cell (a cell whose cdr is an atom); then it ; should return the car of this cell. (defun last-element (list) (cond ((atom (cdr list)) (car list)) (t (last-element (cdr list)))))
495
Common Lisp
.lisp
12
39.916667
69
0.719917
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
b4bb451d0fa49e96899a8bb0ef375749bf5297cb659f2dbbd8c2de85e700a5bf
17,049
[ -1 ]
17,050
ex-08-29.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-29.lisp
; file: ex-08-29.lisp ; author: Jon David ; date: Sunday, August 24, 2014 ; description: ; exercise 8.29 - Write MY-MEMBER, a recursive version of MEMBER. ; This function will take two inputs, but you will only want to ; reduce one of them with each successive call. The other should ; remain unchanged. (defun my-member (item list) (cond ((null list) nil) ((equal item (car list)) list) (t (my-member item (cdr list)))))
434
Common Lisp
.lisp
12
34.833333
67
0.71327
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
8ae5597e52a6c5f309f4bbb041c1556b9c3d8deaaa38de67d79d775c11584d78
17,050
[ -1 ]
17,051
ex-08-35.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-35.lisp
; file: ex-08-35.lisp ; author: Jon David ; date: Monday, August 25, 2014 ; description: ; exercise 8.35 - Write MY-SET-DIFFERENCE, a recursive version of ; the SET-DIFFERENCE function. ; Note: X-Y is not necessarily equal to Y-X. (defun my-set-difference (X Y) (cond ((null X) nil) ((null Y) X) ((member (car X) Y) (my-set-difference (cdr X) Y)) (t (cons (car X) (my-set-difference (cdr X) Y)))))
408
Common Lisp
.lisp
12
32.5
67
0.673418
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
509f1d4d4bb8d0115ffb3ee3caacd3921f408d75da79d2a4f28e0fef064b1fbe
17,051
[ -1 ]
17,052
ex-08-49.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-49.lisp
; file: ex-08-49.lisp ; author: Jon David ; date: Sunday, September 28, 2014 ; description: ; exercise 8.49 - Write PAIRINGS, a function that pairs the elements ; of two lists. (PAIRINGS '(A B C) '(1 2 3)) should return ; ((A 1) (B 2) (C 3)). You may assume that the two lists will be of ; equal length. (defun pairings (letter-list num-list) (cond ((null letter-list) nil) (t (cons (list (car letter-list) (car num-list)) (pairings (cdr letter-list) (cdr num-list))))))
490
Common Lisp
.lisp
12
38.916667
70
0.674419
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
9353875564fa7a5ed414cd25af7ba700d174557b9bb8fb0a7f0b557ba09f5bee
17,052
[ -1 ]
17,053
ex-08-34.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-34.lisp
; file: ex-08-34.lisp ; author: Jon David ; date: Monday, August 25, 2014 ; description: ; exercise 8.34 - Write MY-INTERSECTION, a recursive version of the ; INTERSECTION function. (defun my-intersection (X Y) (cond ((or (null X) (null Y)) nil) ((member (car X) Y) (cons (car X) (my-intersection (cdr X) Y))) (t (my-intersection (cdr X) Y))))
355
Common Lisp
.lisp
11
30.636364
69
0.673469
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
61a46abedb456faf99253e463077eddff138bb6b3e798abe19755bcd72821786
17,053
[ -1 ]
17,054
ex-08-54.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-54.lisp
; file: ex-08-54.lisp ; author: Jon David ; date: Sunday, September 28, 2014 ; description: ; exercise 8.54 - Write a recursive function HUGE that raises a ; number to its own power. (HUGE 2) should return 2^2=4. (HUGE 3) ; should return 3^3=27, (HUGE 4) should return 4^4=256, and so on. ; Do not use REDUCE. (defun huge-recursive (n counter) (cond ((equal counter 1) n) (t (* n (huge-recursive n (- counter 1)))))) (defun huge (n) (huge-recursive n n))
475
Common Lisp
.lisp
13
34.615385
68
0.679121
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
6020545b4a5ad7eb5f76b15e01e44548a4c5f737a6e7213ee3609776c934d048
17,054
[ -1 ]
17,055
ex-08-30.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-30.lisp
; file: ex-08-30.lisp ; author: Jon David ; date: Sunday, August 24, 2014 ; description: ; exercise 8.30 - Write MY-ASSOC, a recursive version of ASSOC. (defun my-assoc (key table) (cond ((null table) nil) ((equal key (caar table)) (car table)) (t (my-assoc key (cdr table)))))
285
Common Lisp
.lisp
9
30.111111
65
0.683636
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
3558219275fee98010e938fc93e9c4d9f11de9b1b872df9a4968f297a10b1bba
17,055
[ -1 ]
17,056
ex-08-66.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-66.lisp
; file: ex-08-66.lisp ; author: Jon David ; date: Monday, October 21, 2014 ; description: ; exercise 8.66 - Write ARITH-EVAL, a function that evalutes ; arithmetic expressions. (ARITH-EVAL '(2 + (3 * 4))) should ; return 14. ; ; notes: ; An arithmetic expression is either a number, or a three-element ; list whose first and third elements are arithmetic expressions ; and whose middle element is one of +, -, *, or /. (defun arith-eval (expr) (cond ((null expr) nil) ((numberp expr) expr) ((equal 3 (length expr)) (funcall (cadr expr) (arith-eval (car expr)) (arith-eval (caddr expr)))) (t nil)))
626
Common Lisp
.lisp
20
29.5
67
0.682645
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
06a7e98a2a0f44ee1639dbaded547a0603f140a48d6954a2f75f79b922195a89
17,056
[ -1 ]
17,057
ex-08-31.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-31.lisp
; file: ex-08-31.lisp ; author: Jon David ; date: Sunday, August 24, 2014 ; description: ; exercise 8.31 - Suppose we want to tell as quickly as possible ; whether one list is shorter than another. If one list has five ; elements and the other has a million, we don't want to have to ; go through all one million cons cells before deciding that the ; second list is longer. So we must not call LENGTH on the two ; lists. Write a recursive function COMPARE-LENGTHS that takes two ; lists as input and returns one of the following symbols: ; SAME-LENGTH, FIRST-IS-LONGER, or SECOND-IS-LONGER. ; Use triple-test simultaneous recursion. (defun compare-lengths (lista listb) (cond ((and (null lista) (null listb)) 'same-length) ((null lista) 'second-is-longer) ((null listb) '(first-is-longer)) (t (compare-lengths (cdr lista) (cdr listb)))))
864
Common Lisp
.lisp
18
46.555556
68
0.734597
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
9168ac7d2aed2f8c89c3eac7a768ed504c6b24039fb0142ebea0ac6e213e7424
17,057
[ -1 ]
17,058
ex-08-45.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-45.lisp
; file: ex-08-45.lisp ; author: Jon David ; date: Wednesday, September 24, 2014 ; description: ; exercise 8.45 - Write a function PAREN-DEPTH that returns the ; maximum depth of nested parentheses in a list. ; (PAREN-DEPTH '(A B C)) should return one, whereas TREE-DEPTH ; would return three. (PAREN-DEPTH '(A B ((C) D) E)) should return ; three, since there is an element C that is nested in three levels ; of parentheses. Hint: This problem can be solved by car/cdr ; recursion, but the CAR and CDR cases will not be exactly ; symmetric. ; (defun paren-depth (list) (cond ((atom list) 0) (t (max (+ 1 (paren-depth (car list))) (paren-depth (cdr list))))))
680
Common Lisp
.lisp
17
38.705882
69
0.701357
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
95c2c51b8c7154a1226916c2020c252935037ccf78893132c48a1b6c823f28e3
17,058
[ -1 ]
17,059
ex-08-27.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-27.lisp
; file: ex-08-27.lisp ; author: Jon David ; date: Sunday, August 24, 2014 ; description: ; exercise 8.27 - Write SQUARE-LIST, a recursive function that takes ; a list of numbers as input and returns a list of their squares. ; (SQUARE-LIST '(3 4 5 6)) should return (9 16 25 36). (defun square-list (num-list) (cond ((null num-list) nil) (t (cons (* (car num-list) (car num-list)) (square-list (cdr num-list))))))
425
Common Lisp
.lisp
11
37.090909
70
0.681159
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
66fd3779afa0bd1e27c4b69475fcb3ac81b2bff96fc0cc60347bc071f88f38bf
17,059
[ -1 ]
17,060
ex-08-05.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-05.lisp
; file: ex-08-05.lisp ; author: Jon David ; date: Monday, August 18, 2014 ; description: ; exercise 8.5 - In this exercise we are going to write a function ; ADD-UP to add up all the numbers in a list. (ADD-UP '(2 3 7)) ; should return 12. You already know how to solve this problem ; applicatively with REDUCE; now you'll learn how to solve it ; recursively. (defun add-up (num-list) (cond ((null num-list) 0) (t (+ (car num-list) (add-up (cdr num-list))))))
476
Common Lisp
.lisp
12
38.166667
68
0.689805
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
21994a0ee4a0c4d2e2c6ea96a5a4a626a9764acf364c9315773cc7f8635dd286
17,060
[ -1 ]
17,061
ex-08-46.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-46.lisp
; file: ex-08-46.lisp ; author: Jon David ; date: Sunday, September 28, 2014 ; description: ; exercise 8.46 - Another way to solve the problem of counting ; upward is to add an element to the end of the list with each ; recursive call instead of adding elements to the beginning. ; This approach doesn't require a helping function. Write this ; version of COUNT-UP. (defun count-up (n) (cond ((zerop n) nil) (t (append (count-up (- n 1)) (list n)))))
469
Common Lisp
.lisp
12
37.416667
64
0.712389
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
f99955386f119b3c11f3751dc8a29da57daeb5022816079590c192be8af6cff4
17,061
[ -1 ]
17,062
ex-08-17.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-17.lisp
; file: ex-08-17.lisp ; author: Jon David ; date: Sunday, August 24, 2014 ; description: ; exercise 8.17 - Use double-test tail recursion to write ; FIND-FIRST-ODD, a function that returns the first odd number in a ; list, or NIL if there are none. Start by copying the recursion ; template for ANYODDP; only a small change is neccessary to derive ; FIND-FIRST-ODD. (defun find-first-odd (num-list) (let ((n (car num-list))) (cond ((null num-list) nil) ((oddp n) n) (t (find-first-odd (cdr num-list))))))
528
Common Lisp
.lisp
14
35.785714
69
0.695906
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
926cbf4b92cce6ba1a69a63028efaca3fd4daa296a3bbd7ab05cc81365de09c9
17,062
[ -1 ]
17,063
ex-08-21.lisp
joncdavid_touretzky-lisp-exercises/chp8-recursion/ex-08-21.lisp
; file: ex-08-21.lisp ; author: Jon David ; date: Sunday, August 24, 2014 ; description: ; exercise 8.21 - Write a recursive function ADD-NUMS that adds up ; the numbers N, N-1, N-2, and so on, down to 0, and returns the ; result. For example, (ADD-NUMS 5) should compute 5+4+3+2+1+0=15. (defun add-nums (n) (cond ((zerop n) n) (t (+ n (add-nums (- n 1))))))
370
Common Lisp
.lisp
10
35.5
68
0.653631
joncdavid/touretzky-lisp-exercises
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
44f9fdcbf54e89a87d67a06490b4f340eaf587d0b2ff6cd3c18ba1066631c5ed
17,063
[ -1 ]