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
17,313
mixture-test.lisp
jnjcc_cl-ml/test/mixture-test.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Unsupervised Learning > Probability Model Estimation > Mixture Model (in-package #:cl-ml/test) (define-test gaussian-mixture-test (let ((X (copy-matrix *gmm-train*)) ;; (y (copy-matrix *gmm-label*)) (gmm (make-instance 'gaussian-mixture :tolerance 0.001 :epochs 30 :ninit 1 :ncomponents 3)) (pred nil)) (with-random-seed (5) (fit gmm X) (setf pred (predict gmm (mhead X))) (assert-true (= (vref pred 0) (vref pred 1) (vref pred 3))) (assert-true (= (vref pred 2) (vref pred 4) (vref pred 5))))))
657
Common Lisp
.lisp
15
37.2
73
0.60625
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
7e274b8af5b13b1c4d09a9138a5ff8b4da601ddb4a91c853d2b9bd2e476d5bec
17,313
[ -1 ]
17,314
packages.lisp
jnjcc_cl-ml/test/packages.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-user) (defpackage #:cl-ml/test (:nicknames #:ml/test) (:use #:cl #:lisp-unit #:cl-ml/probs #:cl-ml/linalg #:cl-ml/algo #:cl-ml/graph #:cl-ml/io #:cl-ml) (:export #:run-all-tests))
285
Common Lisp
.lisp
8
32.625
66
0.621818
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
05115f82983379ddd89ed47749a1fbb104c32ac097eb93ac98e2ee13b6338e81
17,314
[ -1 ]
17,315
dataset.lisp
jnjcc_cl-ml/test/dataset.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-ml/test) (defvar *dataset-path* (merge-pathnames "test/dataset/" (asdf:system-source-directory :cl-ml-test))) ;;; iris dataset (defvar *iris-file-path* (merge-pathnames "iris/iris.data" *dataset-path*)) (defvar *iris-train* nil) (defvar *iris-label* nil) (multiple-value-setq (*iris-train* *iris-label*) (read-matrix *iris-file-path* :labclass :string)) (defvar *iris-labenc* (make-instance 'label-encoder)) (defvar *iris-class* (copy-matrix *iris-label*)) (fit-transform *iris-labenc* *iris-class*) ;;; california housing dataset (defvar *cal-file-path* (merge-pathnames "california/cal_housing.data" *dataset-path*)) (defvar *cal-train* nil) (defvar *cal-label* nil) (multiple-value-setq (*cal-train* *cal-label*) (read-matrix *cal-file-path*)) (m/= *cal-label* 100000) ;;; blobs from make_blobs() (defvar *kmeans-blob* (merge-pathnames "sklearn/kmeans.blob" *dataset-path*)) (defvar *kmeans-train* nil) (defvar *kmeans-label* nil) (multiple-value-setq (*kmeans-train* *kmeans-label*) (read-matrix *kmeans-blob*)) (defvar *gmm-blob* (merge-pathnames "sklearn/gmm.blob" *dataset-path*)) (defvar *gmm-train* nil) (defvar *gmm-label* nil) (multiple-value-setq (*gmm-train* *gmm-label*) (read-matrix *gmm-blob*)) ;;; dataset preprocessing (defun load-iris-label-binary (&optional (neg -1) (pos +1)) (let ((label (copy-matrix *iris-label*))) (do-vector (i label) (if (string= (vref label i) "Iris-virginica") (setf (vref label i) pos) (setf (vref label i) neg))) label)) ;;; karate.edgelist from `node2vec' (defvar *karate-path* (merge-pathnames "karate.edgelist" *dataset-path*)) (defvar *karate-graph* (read-graph *karate-path* :delimiter #\Space))
1,823
Common Lisp
.lisp
40
42.425
87
0.689014
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
d2f45d0a2b1d69bbcaf812f12a2250129b8853adaca5dda24659cefe4040c823
17,315
[ -1 ]
17,316
gaussian.lisp
jnjcc_cl-ml/pgm/gaussian.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Multivariate Gaussian Distribution (in-package #:cl-ml) (defun mgpdf (x mus sigmas) "Probability Density Function for Multivariate Gaussian Distribution `mus': row or column vector; `sigmas': covariance matrix" (declare (type smatrix mus sigmas)) (let ((n (nrow sigmas)) (det (abs (mdet sigmas))) (maha (mahalanobis-distance x mus sigmas))) (/ (exp (* -1/2 maha maha)) (* (expt (* 2 pi) (/ n 2)) (expt det 1/2))))) (defun mglogpdf (x mus sigmas) (declare (type smatrix mus sigmas)) (let ((n (nrow sigmas)) (det (abs (mdet sigmas))) (maha (mahalanobis-distance x mus sigmas))) (- (* -1/2 maha maha) (* n 1/2 (log (* 2 pi))) (* 1/2 (log det)))))
805
Common Lisp
.lisp
22
31.772727
70
0.610256
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
6127a00b88bfb28a3a08081ce7d82bcaf4ff7154b361236bd3d39c3ba1f3568c
17,316
[ -1 ]
17,317
gmm.lisp
jnjcc_cl-ml/pgm/gmm.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Unsupervised Learning > Probability Model Estimation > Mixture Model (in-package #:cl-ml) (defclass gaussian-mixture (estimator) ((ncomponents :initform 3 :initarg :ncomponents :documentation "number of mixture components") (alphas :initform nil :documentation "weight for each of the `ncomponents'") (mus :initform nil :documentation "mus of the shape `ncomponents'x`nfeatures'") ;; TODO: for now this is a list of matrices (sigmas :initform nil :documentation "convariance of each mixture component") ;; TODO: multiple initializations (ninit :initform 1 :initarg :ninit :documentation "number of inits to perform") (epochs :initform 30 :initarg :epochs :documentation "number of EM iterations") (tolerance :initform 1.0e-3 :initarg :tolerance))) (defmethod init-components ((gauss gaussian-mixture) X) (with-slots (ncomponents alphas mus sigmas) gauss (setf alphas (make-rand-vector ncomponents)) (m/= alphas (msum alphas)) (setf mus (make-rand-matrix ncomponents (ncol X))) (setf sigmas nil) (dotimes (i ncomponents) (push (make-identity-matrix (ncol X)) sigmas)))) (defmethod expectation-step ((gauss gaussian-mixture) X qdist) "for each example I, estimate probability for component K" (with-slots (ncomponents alphas mus sigmas) gauss (let ((logvec (make-vector ncomponents :initial-element 0.0)) ;; logsumexp(logvec) (logsum nil) ;; log(\alpha[k]) (logalpha nil) ;; log(\phi(x[i])), given \theta[k] (logdensity nil)) (do-matrix-row (i X) (dotimes (k ncomponents) (setf logalpha (log (vref alphas k))) (setf logdensity (mglogpdf (mrv X i) (mrv mus k) (nth k sigmas))) (setf (vref logvec k) (+ logalpha logdensity))) (setf logsum (logsumexp logvec)) (dotimes (k ncomponents) (setf (mref qdist i k) (exp (- (vref logvec k) logsum)))))) qdist)) (defmethod maximization-step ((gauss gaussian-mixture) X qdist) (with-slots (ncomponents alphas mus sigmas) gauss (let ((denoms (msum qdist :axis 0))) (dotimes (k ncomponents) (setf (vref alphas k) (/ (vref denoms k) (nrow X))) (setf (mrv mus k) 0.0) (do-matrix-row (i X) (m+= (mrv mus k) (m* (mref qdist i k) (mrv X i)))) (if (float= (vref denoms k) 0 1.0e-5) (setf (mrv mus k) 0.0) (m/= (mrv mus k) (vref denoms k))) (let ((sigmak (nth k sigmas))) (do-matrix (i j sigmak) (setf (mref sigmak i j) 0.0)) (do-matrix-row (i X) (let ((dif (m- (mrv X i) (mrv mus k)))) (m+= sigmak (m* (mref qdist i k) (mt dif) dif)))) (unless (float= (vref denoms k) 0 1.0e-5) (m/= sigmak (vref denoms k))))) ))) (defmethod fit ((gauss gaussian-mixture) X &optional y) (declare (ignore y)) (with-slots (ncomponents alphas mus sigmas ninit epochs tolerance) gauss (dotimes (ini ninit) (init-components gauss X) (let ((qdist (make-matrix (nrow X) ncomponents))) (dotimes (ep epochs) ;; E-step: qdist[i][k] = P(z[i] = k | X, \Theta) (expectation-step gauss X qdist) ;; M-step: alphas, mus, sigmas (maximization-step gauss X qdist)))))) (defmethod predict-proba ((gauss gaussian-mixture) X) (with-slots (ncomponents) gauss (let ((pred (make-matrix (nrow X) ncomponents))) (expectation-step gauss X pred) pred))) (defmethod predict ((gauss gaussian-mixture) X) (let ((prob (predict-proba gauss X))) (margmax prob :axis 1)))
3,710
Common Lisp
.lisp
81
38.802469
82
0.627798
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
d05d3a3cf4059afe88f049809cfd8c75a01f4c48621ae6dcdd27aea78a29b822
17,317
[ -1 ]
17,318
sim-lex.lisp
jnjcc_cl-ml/io/sim-lex.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Lexical analysis, with #\Space being word delimiter (in-package #:cl-ml/io) (defun alpha-word-p (word) (every #'alpha-char-p word)) (defun upper-word-p (word) (every #'upper-case-p word)) (defun lower-word-p (word) (every #'lower-case-p word)) (defun title-word-p (word) (and (upper-case-p (char word 0)) (lower-word-p (subseq word 1)))) (defun digit-word-p (word) (every #'digit-char-p word)) (defun alnum-word-p (word) (every #'alphanumericp word)) (defun make-adjustable-string () (make-array '(0) :element-type 'base-char :fill-pointer 0 :adjustable t)) (defun read-next-word (stream &key (eow #\Space) (eol #\Newline)) "`eow': end-of-word; `eol': end-of-line Returns: :eof if end-of-file; :eol if end-of-line; word otherwise" (discard-chars-if stream (lambda (ch) (eq ch eow))) (let ((next (peek-next-char stream nil :eof))) (cond ((eq next :eof) (return-from read-next-word :eof)) ((eq next eol) (progn (discard-next-char stream) (return-from read-next-word :eol))))) (let ((word (make-adjustable-string))) (with-output-to-string (wstream word) (do-char-until (chr stream (lambda (x) (or (eq x eow) (eq x eol)))) (write-char chr wstream)) word))) (defmacro do-word ((word stream &key (eow #\Space) (eol #\Newline)) &body body) "`word' will be :eol if end-of-line" `(do ((,word (read-next-word ,stream :eow ,eow :eol ,eol) (read-next-word ,stream :eow ,eow :eol ,eol))) ((eq ,word :eof)) ,@body))
1,670
Common Lisp
.lisp
41
35.073171
79
0.612724
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
943879957ff02845c4813ab87be7d591a27f01c465840344fe5032492be120ec
17,318
[ -1 ]
17,319
sim-file.lisp
jnjcc_cl-ml/io/sim-file.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; file io (in-package #:cl-ml/io) (defun read-file-content (fpath) (with-open-file (stream fpath :direction :input :if-does-not-exist nil) (unless stream (error "error reading file ~A~%" fpath)) (let ((content (make-string (file-length stream)))) (read-sequence content stream) content))) (defun read-file-lines (fpath) ;; there will be an extra empty line (butlast (split-string (read-file-content fpath) #\Newline)))
529
Common Lisp
.lisp
14
34.285714
73
0.681641
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
6fbaed94bc72f8de0990afe10331c26df96ffea6ff844781684f69c77c1bd4ba
17,319
[ -1 ]
17,320
sim-char.lisp
jnjcc_cl-ml/io/sim-char.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Character (in-package #:cl-ml/io) (defun space-char-p (chr) (or (char= chr #\Space) (char= chr #\Tab) (char= chr #\Newline) (char= chr #\Return))) (defun peek-non-space (stream &optional (eof-error-p t) (eof-value nil)) "peek next non-whitespace character" (peek-char t stream eof-error-p eof-value)) (defun peek-next-char (stream &optional (eof-error-p t) (eof-value nil)) "peek next char, maybe whitespace" (peek-char nil stream eof-error-p eof-value)) (defun discard-next-char (stream &optional (eof-error-p t) (eof-value nil)) "read next char and discard it by returning `nil'" (read-char stream eof-error-p eof-value) nil) (defun stream-eof-p (stream) (let ((next (peek-next-char stream nil :eof))) (eq next :eof))) (defun read-next-char (stream) "Returns: :eof if end-of-file; char otherwise" (read-char stream nil :eof)) (defun read-chars-if (stream predicate) (let ((chars nil)) (do ((next (peek-next-char stream nil :eof) (peek-next-char stream nil :eof))) ((or (eq next :eof) (not (funcall predicate next)))) (push (read-char stream nil :eof) chars)) (nreverse chars))) (defun discard-chars-if (stream predicate) (do ((next (peek-next-char stream nil :eof) (peek-next-char stream nil :eof))) ((or (eq next :eof) (not (funcall predicate next)))) (discard-next-char stream nil))) (defun read-chars-until (stream predicate) (let ((chars nil)) (do ((next (peek-next-char stream nil :eof) (peek-next-char stream nil :eof))) ((or (eq next :eof) (funcall predicate next))) (push (read-char stream nil :eof) chars)) (nreverse chars))) (defun discard-chars-until (stream predicate) (do ((next (peek-next-char stream nil :eof) (peek-next-char stream nil :eof))) ((or (eq next :eof) (funcall predicate next))) (discard-next-char stream nil))) (defmacro do-char ((char stream) &body body) (let ((next (gensym "NEXT-"))) `(do ((,next (peek-next-char ,stream nil :eof) (peek-next-char ,stream nil :eof)) (,char nil)) ((eq ,next :eof)) (setf ,char (read-char ,stream nil :eof)) ,@body))) (defmacro do-char-if ((char stream predicate) &body body) (let ((next (gensym "NEXT-")) (pred (gensym "PRED-"))) `(do ((,next (peek-next-char ,stream nil :eof) (peek-next-char ,stream nil :eof)) (,pred ,predicate) (,char nil)) ((or (eq ,next :eof) (not (funcall ,pred ,next)))) (setf ,char (read-char ,stream nil :eof)) ,@body))) (defmacro do-char-until ((char stream predicate) &body body) (let ((next (gensym "NEXT-")) (pred (gensym "PRED-"))) `(do ((,next (peek-next-char ,stream nil :eof) (peek-next-char ,stream nil :eof)) (,pred ,predicate) (,char nil)) ((or (eq ,next :eof) (funcall ,pred ,next))) (setf ,char (read-char ,stream nil :eof)) ,@body)))
3,064
Common Lisp
.lisp
74
35.716216
85
0.617272
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
b28dd3579cf6a3753a060d44e6f388d8211fdf96ddd15525cb00b531ee3495ef
17,320
[ -1 ]
17,321
sim-matrix.lisp
jnjcc_cl-ml/io/sim-matrix.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Simple io: read smatrix from csv file (in-package #:cl-ml/io) (defun read-matrix (fpath &key (start 0) end (header-p nil) (delimiter #\,) colclass (label -1) labclass) "Read from row [`start', `end') of `fpath'; `header-p' if the first line is header; `colclass' as class of columns: :string being string, otherwise numeric; `label' as the label column index; `labclass' as label class" (let* ((examples (read-file-lines fpath)) (nrow (length examples)) (vars (split-string (nth 0 examples) delimiter)) (ncol (length vars)) (ma nil) (vy nil)) ;; header as the first row (when header-p (incf start) (decf nrow)) (when (and start end (< (- end start) nrow)) (setf nrow (- end start))) (when label (when (< label 0) (incf label ncol)) (decf ncol) (setf vy (make-vector nrow))) (setf ma (make-matrix nrow ncol)) (do-example-row (example ridx examples :start start :end end) (setf vars (split-string example delimiter)) (when label (if (eq labclass :string) (setf (vref vy ridx) (nth label vars)) (setf (vref vy ridx) (read-from-string (nth label vars))))) (do-variable-col (var cidx vars :label label) (if (eq (nth cidx colclass) :string) (setf (mref ma ridx cidx) var) (setf (mref ma ridx cidx) (read-from-string var))))) (values ma vy)))
1,545
Common Lisp
.lisp
38
33.552632
85
0.601464
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
7953937b02f2bc703dd3169b32e695e87378e3b0e7227420668c2e4bc07d1b11
17,321
[ -1 ]
17,322
sim-example.lisp
jnjcc_cl-ml/io/sim-example.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Simple io for training examples (in-package #:cl-ml/io) (defun %canonize-bound (bound len &optional (default 0)) (cond ((null bound) default) ((integerp bound) (cond ((<= 0 bound len) bound) ((<= (- len) bound -1) (+ bound len)) (t (error "malformed bound ~A: range [~A, ~A] expected" bound (- len) len)))) (t (error "malformed bound ~A: not supported" bound)))) (defun %canonize-start (start len) (%canonize-bound start len 0)) (defun %canonize-end (end len) (%canonize-bound end len len)) ;; collect training example from file (defmacro do-example-from-file ((example index fpath &key (start 0) end rows) &body body) "[`start', `end') can be variable or value; `rows' must be variable; `index' is the index of the collected examples by now" (let ((examples-sym (gensym "EXAMPLES-")) (len-sym (gensym "LEN-")) (start-sym (gensym "START-")) ;; start might be value (end-sym (gensym "END-")) ;; end might be value (idx-sym (gensym "IDX-"))) `(let* ((,examples-sym (read-file-lines ,fpath)) (,len-sym (length ,examples-sym)) (,start-sym (%canonize-start ,start ,len-sym)) (,end-sym (%canonize-end ,end ,len-sym)) (,example nil) (,index nil)) (do ((,idx-sym ,start-sym (1+ ,idx-sym))) ((>= ,idx-sym ,end-sym)) ,@(when rows `((setf ,rows (+ ,idx-sym 1)))) (setf ,example (nth ,idx-sym ,examples-sym)) (setf ,index (- ,idx-sym ,start-sym)) ,@body)))) (defmacro do-example-row ((example index examples &key (start 0) end rows) &body body) "loop across rows of [`start', `end'); `example' as current row; `index' as current index; `rows' as number of rows collected" (let ((len-sym (gensym "LEN-")) (start-sym (gensym "START-")) (end-sym (gensym "END-")) (idx-sym (gensym "IDX-"))) `(let* ((,len-sym (length ,examples)) (,start-sym (%canonize-start ,start ,len-sym)) (,end-sym (%canonize-end ,end ,len-sym)) (,example nil) (,index nil)) (do ((,idx-sym ,start-sym (1+ ,idx-sym))) ((>= ,idx-sym ,end-sym)) ,@(when rows `((setf ,rows (+ ,idx-sym 1)))) (setf ,example (nth ,idx-sym ,examples)) (setf ,index (- ,idx-sym ,start-sym)) ,@body)))) (defmacro do-variable-col ((var index vars &key (start 0) end (label -1)) &body body) "loop across columns [`start', `end'), excluding `label'; `var' as current variable; `index' as current index" (let ((len-sym (gensym "LEN-")) (start-sym (gensym "START-")) (end-sym (gensym "END-")) (labidx-sym (gensym "LABIDX-")) (idx-sym (gensym "IDX-"))) `(let* ((,len-sym (length ,vars)) (,start-sym (%canonize-start ,start ,len-sym)) (,end-sym (%canonize-end ,end ,len-sym)) (,labidx-sym ,label) (,var nil) (,index nil)) (when (and ,labidx-sym (< ,labidx-sym 0)) (incf ,labidx-sym ,len-sym)) (do ((,idx-sym ,start-sym (1+ ,idx-sym))) ((>= ,idx-sym ,end-sym)) (when (or (not ,labidx-sym) (/= ,idx-sym ,labidx-sym)) (setf ,var (nth ,idx-sym ,vars)) (setf ,index (- ,idx-sym ,start-sym)) ,@body)))))
3,518
Common Lisp
.lisp
80
35.2125
89
0.540076
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
102412c7d10cdc08264fc662ae099c9da546653b6f5d59176c72bc8316cf81f4
17,322
[ -1 ]
17,323
sim-synt.lisp
jnjcc_cl-ml/io/sim-synt.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Syntactic analysis, with #\Space being word delimiter, #\Newline being sentence delimiter (in-package #:cl-ml/io) (defun read-next-sentence (stream &key (max-len nil) (eow #\Space) (eol #\Newline)) "Returns: :eof if no more sentence; or list of words (could be empty list) if `max-len' non-nil, only `max-len' words allowed" (let ((sentence nil) (eof-word nil)) (do ((word (read-next-word stream :eow eow :eol eol) (read-next-word stream :eow eow :eol eol))) ((or (eq word :eol) (and max-len (> (length sentence) max-len)))) (when (eq word :eof) (setf eof-word t) (return)) (push word sentence)) (if (and eof-word (null sentence)) :eof (nreverse sentence)))) (defmacro do-sentence ((sentence stream &key (eow #\Space) (eol #\Newline)) &body body) "`sentence' will be NIL if empty sentence" `(do ((,sentence (read-next-sentence ,stream :eow ,eow :eol ,eol) (read-next-sentence ,stream :eow ,eow :eol ,eol))) ((eq ,sentence :eof)) ,@body))
1,153
Common Lisp
.lisp
26
38.038462
94
0.614769
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
8155de34eb022f0a666277a5b587d0c964d4ee3a30bc8980c0b84ed457eea534
17,323
[ -1 ]
17,324
sim-graph.lisp
jnjcc_cl-ml/io/sim-graph.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Simple io: read graph from csv file (in-package #:cl-ml/io) (defun read-graph (fpath &key (type :undirected) (start 0) end (delimiter #\,)) (let ((graph (make-graph type))) (do-example-from-file (example indx fpath :start start :end end) (let* ((varlst (split-string example delimiter)) (unode (read-from-string (car varlst))) (vnode (read-from-string (second varlst))) (weight (third varlst))) (if (>= (length varlst) 3) (add-edge graph unode vnode (read-from-string weight)) (add-edge graph unode vnode)))) graph))
683
Common Lisp
.lisp
15
38.6
79
0.615616
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
3a15fe2717881190ae0fca1dc37c16cad06db786088f0843c05bc9afd59f12d9
17,324
[ -1 ]
17,325
packages.lisp
jnjcc_cl-ml/io/packages.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-user) (defpackage #:cl-ml/io (:nicknames #:ml/io) (:use #:cl #:cl-ml/linalg #:cl-ml/algo #:cl-ml/graph) (:export #:space-char-p #:peek-non-space #:peek-next-char #:discard-next-char #:stream-eof-p #:read-next-char #:read-chars-if #:read-chars-until #:discard-chars-if #:discard-chars-until #:do-char #:do-char-if #:do-char-until #:alpha-word-p #:upper-word-p #:lower-word-p #:title-word-p #:digit-word-p #:alnum-word-p #:read-next-word #:do-word #:read-next-sentence #:do-sentence #:split-string #:read-file-content #:read-file-lines #:do-example-from-file #:do-example-row #:do-variable-col #:read-matrix #:read-graph))
842
Common Lisp
.lisp
18
38.444444
100
0.592186
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
36e3beb932e008a287860bda9baa59526e62365692b44655de0f253c27434d7a
17,325
[ -1 ]
17,326
scaler.lisp
jnjcc_cl-ml/preprocess/scaler.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Min-max scaler and standard-scaler (in-package #:cl-ml) (defclass min-max-scaler (transformer) ()) (defclass standard-scaler (transformer) ((mu-vector :initarg nil :reader mu-vector :type smatrix) (sigma-vector :initarg nil :reader sigma-vector :type smatrix))) (defmethod print-object ((stand standard-scaler) stream) (with-slots (mu-vector sigma-vector) stand (format stream "mu-vector: ~A~%" mu-vector) (format stream "sigma-vector: ~A~%" sigma-vector))) (defmethod fit ((stand standard-scaler) X &optional y) (declare (type smatrix X) (ignore y)) (with-slots (mu-vector sigma-vector) stand (setf mu-vector (make-row-vector (ncol X))) (setf sigma-vector (make-row-vector (ncol X))) (do-matrix-row (i X) (v+= mu-vector (mrv X i))) (v/= mu-vector (nrow X)) (do-matrix-row (i X) (labels ((square (e) (* e e))) (v+= sigma-vector (vmap (v- (mrv X i) mu-vector) #'square)))) (v/= sigma-vector (nrow X)))) (defmethod transform ((stand standard-scaler) X) (declare (type smatrix X)) (with-slots (mu-vector sigma-vector) stand (do-matrix-row (i X) (v-= (mrv X i) mu-vector) (v/= (mrv X i) sigma-vector))) X) (defmethod fit-transform ((stand standard-scaler) X) (fit stand X) (transform stand X)) (defmethod inv-transform ((stand standard-scaler) X) (with-slots (mu-vector sigma-vector) stand (do-matrix-row (i X) (v*= (mrv X i) sigma-vector) (v+= (mrv X i) mu-vector))) X)
1,563
Common Lisp
.lisp
41
34.219512
69
0.654557
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
0c78b056ada5d1236b3f22fba52aa341aeb979d1d12846e8abaed5544c4a57d6
17,326
[ -1 ]
17,327
label.lisp
jnjcc_cl-ml/preprocess/label.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Label Encoder: encode label to index (in-package #:cl-ml) ;;; TODO: association list might also do the trick? (defclass label-encoder (transformer) ((label-hash :initform nil :reader label-hash) (inver-hash :initform nil :reader inver-hash) (label-nums :initform 0 :reader label-nums))) (defmethod print-object ((lab label-encoder) stream) (with-slots (label-hash label-nums) lab (if (<= label-nums 0) (format stream "~A labels" label-nums) (labels ((print-entry (key value) (format stream "~A: ~A, " key value))) (format stream "~A labels:~% {" label-nums) (maphash #'print-entry label-hash) (format stream "}~%"))))) (defmethod %init-parameters ((lab label-encoder)) (with-slots (label-hash inver-hash label-nums) lab (setf label-hash (make-hash-table :test 'equal) inver-hash (make-hash-table :test 'equal) label-nums 0))) ;; x is a vector (defmethod fit ((lab label-encoder) x &optional y) (declare (type smatrix x) (ignore y)) (%init-parameters lab) (with-slots (label-hash inver-hash label-nums) lab (do-vector (i x) (multiple-value-bind (val exists-p) (gethash (vref x i) label-hash) (declare (ignore val)) (unless exists-p (setf (gethash (vref x i) label-hash) label-nums) (setf (gethash label-nums inver-hash) (vref x i)) (incf label-nums)))))) (defmethod transform ((lab label-encoder) x) (do-vector (i x) (setf (vref x i) (gethash (vref x i) (label-hash lab)))) x) (defmethod fit-transform ((lab label-encoder) x) (%init-parameters lab) (with-slots (label-hash inver-hash label-nums) lab (do-vector (i x) (multiple-value-bind (val exists-p) (gethash (vref x i) label-hash) (declare (ignore val)) (unless exists-p (setf (gethash (vref x i) label-hash) label-nums) (setf (gethash label-nums inver-hash) (vref x i)) (incf label-nums))) (setf (vref x i) (gethash (vref x i) label-hash)))) x) (defmethod inv-transform ((lab label-encoder) x) (do-vector (i x) (setf (vref x i) (gethash (vref x i) (inver-hash lab)))) x) (defmethod get-encoder-index ((lab label-encoder) label) "label -> index" (with-slots (label-hash) lab (gethash label label-hash))) (defmethod get-encoder-label ((lab label-encoder) index) "index -> label" (with-slots (inver-hash) lab (gethash index inver-hash)))
2,544
Common Lisp
.lisp
63
34.984127
73
0.643464
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
96fa5ad82086f023b43b99992f2a706732659bb9b00c412b0558c83f34cb751e
17,327
[ -1 ]
17,328
polynomial.lisp
jnjcc_cl-ml/preprocess/polynomial.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Polynomial Feature Transformer (in-package #:cl-ml) (defclass poly-transformer (transformer) ((degree :initform 1 :initarg :degree :reader degree) (expand-bias :initform t :initarg :expand-bias :reader expand-bias :documentation "first column as bias") (indices-list :initform nil :reader indices-list :type list))) ;; Problem: given `ncol' variables, list all possibles combination of variables up to `degree' ;; by adding an extra bias of 1, and "assign" some degree to the bias, we can make ;; the sum of the total degree "equal to" `degree', and thus we can make a call to ;; (combination-with-replacement) (defun %visit-comb-indices-poly (ncol degree &optional visit) (visit-combinations-indices (+ ncol 1) degree :replace t :visit visit)) (defun %comb-indices-poly (ncol degree) (combinations-indices (+ ncol 1) degree :replace t)) (defmethod fit ((poly poly-transformer) X &optional y) (declare (type smatrix X) (ignore y)) (with-slots (degree indices-list) poly (setf indices-list (%comb-indices-poly (ncol X) degree)))) (defun %factorial (n) (let ((fact 1)) (dotimes (i n fact) (setf fact (* fact (+ i 1)))))) (defun %make-poly-matrix (X degree &optional (expand-bias t)) "initialize polynomial feature matrix from X, up to `degree' degree" (let* ((n (ncol X)) (d degree) ;; (n+d)! / (n! d!) (newcol (/ (%factorial (+ n d)) (* (%factorial n) (%factorial d))))) (unless expand-bias (decf newcol)) (make-matrix (nrow X) newcol :initial-element 1))) (defun %fill-poly-matrix (x-poly colidx X indices &optional (expand-bias t)) "fill column `colidx' of polynomial feature matrix from columns `indices' of X Return t if we updated the corresponding column, NIL otherwise" (let ((fill-bias-p t)) (dolist (i indices) ;; column 0 as bias when expand-bias (unless (= i 0) ;; we are filling some column other than the bias column (setf fill-bias-p nil) (setf (mcv x-poly colidx) (v* (mcv x-poly colidx) (mcv X (- i 1)))))) (or (not fill-bias-p) expand-bias))) (defmethod transform ((poly poly-transformer) X) (declare (type smatrix X)) (with-slots (degree expand-bias indices-list) poly (let ((x-poly (%make-poly-matrix X degree expand-bias)) (colidx 0)) (dolist (indices indices-list) (when (%fill-poly-matrix x-poly colidx X indices expand-bias) (incf colidx))) x-poly))) (defmethod fit-transform ((poly poly-transformer) X) (declare (type smatrix X)) (let ((x-poly (%make-poly-matrix X (degree poly) (expand-bias poly))) ;; column index of x-poly (colidx 0)) (with-slots (expand-bias indices-list) poly (setf indices-list nil) (labels ((intersect (indices) (push (copy-list indices) indices-list) (when (%fill-poly-matrix x-poly colidx X indices expand-bias) (incf colidx)))) (%visit-comb-indices-poly (ncol X) (degree poly) #'intersect) (setf indices-list (nreverse indices-list)))) x-poly))
3,196
Common Lisp
.lisp
69
40.710145
94
0.655438
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
5e45d73dba945eea5165017a361a85186a649ce2fd7428b46d0803e0c7cc7a52
17,328
[ -1 ]
17,329
onehot.lisp
jnjcc_cl-ml/preprocess/onehot.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; OneHot Encoder (in-package #:cl-ml) (defclass onehot-encoder (transformer) ())
160
Common Lisp
.lisp
6
25
66
0.690789
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
4ca44360a696ae2201bec4184521201feca4206455452074335777c4a903d5ba
17,329
[ -1 ]
17,330
combination.lisp
jnjcc_cl-ml/probs/combination.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Combinations and Permutations (n, k) (in-package #:cl-ml/probs) ;;; Combinations ;; combinations-with-replacement (defun %visit-comb-indices-replace (n k &optional visit) "given a set of `n' elements, `visit' all the `k'-length combinations of element indices with replacement" (let ((indices (make-list k :initial-element 0))) (when visit (funcall visit indices)) (block forever-loop (do ((idx (- k 1))) (nil) (do ((i (- k 1) (1- i))) ((< i 0) (return-from forever-loop)) (when (/= (nth i indices) (- n 1)) (setf idx i) (return))) (do ((j idx (1+ j)) (next (+ (nth idx indices) 1))) ((>= j k)) (setf (nth j indices) next)) (when visit (funcall visit indices)))))) (defun %comb-indices-with-replace (n k) (let ((indices-list nil)) (labels ((collect (indices) ;; we will change the content of `indices' during ;; (%visit-comb-indices-replace), copy needed! (push (copy-list indices) indices-list))) (%visit-comb-indices-replace n k #'collect)) (nreverse indices-list))) (defun %comb-with-replacement (lst k) "Elements are treated as unique based on their position, not on their value" (let ((combinations nil)) (labels ((collect (indices) (let ((comb nil)) (dolist (ind indices) (push (nth ind lst) comb)) (push (nreverse comb) combinations)))) (%visit-comb-indices-replace (length lst) k #'collect)) (nreverse combinations))) ;; combinations-without-replacement (defun %visit-comb-indices-no-replace (n k &optional visit) (let ((indices (make-indices k))) (when visit (funcall visit indices)) (block forever-loop (do ((idx (- k 1))) (nil) (do ((i (- k 1) (1- i))) ((< i 0) (return-from forever-loop)) ;; the max index of i-th position is (n-k+i) (when (/= (nth i indices) (+ (- n k) i)) (setf idx i) (return))) (incf (nth idx indices) 1) (do ((j (+ idx 1) (1+ j))) ((>= j k)) (setf (nth j indices) (+ (nth (- j 1) indices) 1))) (when visit (funcall visit indices)))))) (defun %comb-indices-no-replace (n k) (let ((indices-list nil)) (labels ((collect (indices) (push (copy-list indices) indices-list))) (%visit-comb-indices-no-replace n k #'collect)) (nreverse indices-list))) (defun %comb-with-no-replace (lst k) (let ((comb-lst nil)) (labels ((collect (indices) (let ((comb nil)) (dolist (ind indices) (push (nth ind lst) comb)) (push (nreverse comb) comb-lst)))) (%visit-comb-indices-no-replace (length lst) k #'collect)) (nreverse comb-lst))) (defun visit-combinations-indices (n k &key (visit #'princ) (replace t)) (if replace (%visit-comb-indices-replace n k visit) (%visit-comb-indices-no-replace n k visit))) (defun combinations (lst k &key (replace t)) (if replace (%comb-with-replacement lst k) (%comb-with-no-replace lst k))) (defun combinations-indices (n k &key (replace t)) (if replace (%comb-indices-with-replace n k) (%comb-indices-with-no-replace n k))) ;;; Permutations (defun visit-permutations-indices (n k &key (visit #'princ)) (let ((indices (make-indices n)) ;; (n-i-1) choices for position i: [i+1, i+2, ..., n-1] (choices (make-step-range (- n 1) (- n k 1) -1))) (when visit (funcall visit (subseq indices 0 k))) (block forever-loop (do () (nil) (do ((i (- k 1) (1- i))) ((< i 0) (return-from forever-loop)) (if (= (nth i choices) 0) ;; now that there are no available choices for position i, we should restore ;; the original lexicographic order for position (i-1)'s sake; since we came ;; from position (i+1) in the loop, so we know for sure indices[i+1:] already ;; in lexicographic order (let ((tmp (nth i indices))) (when (< i (- n 1)) (setf (subseq indices i) (subseq indices (+ i 1)) (nth (- n 1) indices) tmp) ;; also restore choices (setf (nth i choices) (- n i 1)))) ;; again, we know for sure indices[i+1:] already in lexicographic order ;; choice index: [i+1, i+2, ..., n-1] = [n-(n-i-1), ...] (let ((choidx (- n (nth i choices))) (tmp (nth i indices))) (setf (nth i indices) (nth choidx indices) (nth choidx indices) tmp) ;; we've used up one choice (decf (nth i choices)) (when visit (funcall visit (subseq indices 0 k))) (return)))))))) (defun permutations (lst k) (let ((permut-lst nil)) (labels ((collect (indices) (let ((permut nil)) (dolist (ind indices) (push (nth ind lst) permut)) (push (nreverse permut) permut-lst)))) (visit-permutation-indices (length lst) k :visit #'collect)) (nreverse permut-lst))) (defun permutations-indices (n k) (let ((indices-list nil)) (labels ((collect (indices) (push (copy-list indices) indices-list))) (visit-permutation-indices n k :visit #'collect)) (nreverse indices-list)))
5,662
Common Lisp
.lisp
137
32.10219
91
0.548984
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
9918518e018a551357ba8ece92a5d55333633c8d428e384cea32527cab2f4873
17,330
[ -1 ]
17,331
stats.lisp
jnjcc_cl-ml/probs/stats.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Statistics stuff on list (in-package #:cl-ml/probs) (defun sum (lst) (reduce #'+ lst :initial-value 0)) (defun mean (lst) (/ (sum lst) (length lst))) (defun quantile-positions (len &optional (quad 0.5)) "(values left-idx left-ratio right-idx right-ratio)" (cond ((= len 1) (values 0 1.0 0 0.0)) ((<= quad 0) (values 0 1.0 0 0)) ((>= quad 1) (values (- len 1) 1.0 0 0)) (t (let* ((diff (- len 1)) (loc (* quad diff))) (multiple-value-bind (idx ratio) (floor loc) (values idx (- 1.0 ratio) (+ idx 1) ratio)))))) (defun quantile (lst &optional (quant 0.5)) "NOTICE: will modify `lst', copy-list if necessary" (setf lst (sort lst #'<)) (unless (consp quant) (setf quant (list quant))) (let ((retlst nil)) (dolist (qua quant) (multiple-value-bind (i ir j jr) (quantile-positions (length lst) qua) (if (>= ir 1) (push (nth i lst) retlst) (push (+ (* ir (nth i lst)) (* jr (nth j lst))) retlst)))) (if (= (length retlst) 1) (car retlst) (nreverse retlst))))
1,165
Common Lisp
.lisp
32
31.125
76
0.570922
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
25104f1987f75d3c42c92d550fbc7cbe8117e9327b51807cebf9fbb4006101fe
17,331
[ -1 ]
17,332
bins.lisp
jnjcc_cl-ml/probs/bins.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; bin: lightweight "hash-table" using association list ;;;; - `bincount': ((k1 . count1) ...) ;;;; - `binlist': ((k1 (v1 v2 ...)) ...) (in-package #:cl-ml/probs) (defun make-bins () nil) (defun copy-bins (bins) (copy-list bins)) ;;; on `bincount' (defun binkey (bins key) (assoc key bins)) (defun binvalue (bins key) (cdr (assoc key bins))) ;; NOTICE: using macro to mimic `incf', `decf' and `push' (defmacro binincf (bins key &optional (value 1)) `(if (assoc ,key ,bins) (incf (cdr (assoc ,key ,bins)) ,value) (push (cons ,key ,value) ,bins))) (defmacro bindecf (bins key &optional (value 1)) `(when (assoc ,key ,bins) (decf (cdr (assoc ,key ,bins)) ,value) (remove-if (lambda (x) (<= x 0)) ,bins :key #'cdr))) ;;; on `binlist' (defmacro binpush (bins key value) `(if (assoc ,key ,bins) (push ,value (cdr (assoc ,key ,bins))) (push (cons ,key (list ,value)) ,bins))) (defmacro do-bins ((key value bins) &body body) (let ((item-sym (gensym "ITEM-"))) `(let ((,key nil) (,value nil)) (dolist (,item-sym ,bins) (setf ,key (car ,item-sym)) (setf ,value (cdr ,item-sym)) ,@body)))) (defun bincount (lst &optional (start 0) end) "bin and count: (values ((key . count) ...) sum(count)))" (unless end (setf end (length lst))) (let ((bins nil)) (do ((i start (1+ i))) ((>= i end)) (binincf bins (nth i lst))) (values (nreverse bins) (- end start)))) (defun density (bins &optional count) "density of frequency: ((key . count) ...)" (unless count (setf count (reduce #'+ (mapcar #'cdr bins) :initial-value 0))) (labels ((conv2prob (elem) (cons (car elem) (/ (cdr elem) count)))) (mapcar #'conv2prob bins))) (defun probability (bins &optional count) (mapcar #'cdr (density bins count))) (defun bindensity (lst &optional (start 0) end) "bin and density: ((key . density) ...)" (multiple-value-bind (bins cnt) (bincount lst start end) (density bins cnt))) (defun %argfun (bins cmp &optional (start 0) end (key #'car) (value #'cdr)) "`bins' default input from (bincount)" (unless end (setf end (length bins))) (let ((maxkey nil) (maxval nil) (curpair nil)) (do ((i start (1+ i))) ((>= i end)) (setf curpair (nth i bins)) (when (or (null maxval) (funcall cmp (funcall value curpair) maxval)) (if (eq key value) ;; argmax the index! (setf maxkey i) (setf maxkey (funcall key curpair))) (setf maxval (funcall value curpair)))) (values maxkey maxval))) (defun argmax (bins &key (start 0) end (key #'car) (value #'cdr)) (%argfun bins #'> start end key value)) (defun argmin (bins &key (start 0) end (key #'car) (value #'cdr)) (%argfun bins #'< start end key value))
2,925
Common Lisp
.lisp
80
31.8375
75
0.594203
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
e42af7cb7b865cc9a16381acb06f227c1412437730b3a9d6693c03e18a5858db
17,332
[ -1 ]
17,333
precision.lisp
jnjcc_cl-ml/probs/precision.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Floating Point Precision (in-package #:cl-ml/probs) ;;; float equal (defvar *float-zero-epsilon* 1.0e-10) (defun float= (a b &optional (epsilon *float-zero-epsilon*)) (<= (abs (- a b)) epsilon)) (defun float/= (a b &optional (epsilon *float-zero-epsilon*)) (> (abs (- a b)) epsilon)) (defun float< (a b &optional (epsilon *float-zero-epsilon*)) (and (float/= a b epsilon) (< (- a b) 0))) (defun float> (a b &optional (epsilon *float-zero-epsilon*)) (and (float/= a b epsilon) (> (- a b) 0)))
597
Common Lisp
.lisp
16
34.5625
66
0.626087
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
0914b1bceb625d55e3ea90ba5f21f3c8d10cc7901ceae9c40ba0f2238ffc377f
17,333
[ -1 ]
17,334
paramdist.lisp
jnjcc_cl-ml/probs/paramdist.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Parametric Probability Distributions (in-package #:cl-ml/probs) ;;; Normal distribution (defun cumsum (p) (let ((cdf (make-list (length p))) (sum 0.0)) (dotimes (i (length p)) (incf sum (nth i p)) (setf (nth i cdf) sum)) cdf))
337
Common Lisp
.lisp
12
24.333333
66
0.618012
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
a9dbc42bcb2ec1fcead134f85096812cbbe29141ef8b8fca26aa28b227109bf5
17,334
[ -1 ]
17,335
randoms.lisp
jnjcc_cl-ml/probs/randoms.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Probability stuff (in-package #:cl-ml/probs) (defun %random-generator (shape randfn &rest args) (let ((randret nil)) (cond ((null shape) (setf randret (apply randfn args))) ((integerp shape) (dotimes (i shape) (push (apply randfn args) randret))) ((consp shape) (dotimes (i (car shape)) (let ((randcur nil)) (dotimes (j (cadr shape)) (push (apply randfn args) randcur)) (push randcur randret))))) randret)) ;;; Random integers (defun %randint (low high &optional (state *random-state*)) "random int [low, high)" (let* ((len (- high low)) (idx (random len state))) (+ low idx))) (defun randint (low &optional high shape (state *random-state*)) (if (null high) (%random-generator shape #'%randint 0 low state) (%random-generator shape #'%randint low high state))) ;;; Uniform distribution (defun randuni (limit &optional shape (state *random-state*)) "Uniform distribution" (%random-generator shape #'random limit state)) ;;; Normal Distribution (defun randnorm (mu sigma) "random number from Gaussian Distribution" (+ mu sigma))
1,255
Common Lisp
.lisp
35
30.571429
66
0.637562
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
dd71f5c5ab499ef1697396a07f9d88d441a748c7732f8f7fec16d9191a14a3c2
17,335
[ -1 ]
17,336
shuffle.lisp
jnjcc_cl-ml/probs/shuffle.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Generate a random permutation of a finite (sub-)sequence: ;;;; choose random $k$ elements from a sequence of size $n$ (in-package #:cl-ml/probs) (defun %subseq-values (lst start end) "Returns (actual start, acutal length, acutal end, full length)" (let (subbeg subend) (if start (setf subbeg start) (setf subbeg 0)) (if end (setf subend end) (setf subend (length lst))) (values subbeg (- subend subbeg) subend (length lst)))) (defun %fisher-yates (lst &optional start end) "NOTICE: will modify `lst', copy-list if necessary" (let ((shuflst nil) k last) (multiple-value-bind (sbeg slen send llen) (%subseq-values lst start end) (dotimes (idx sbeg) (push (nth idx lst) shuflst)) (do ((size slen (- size 1))) ((<= size 0)) (setf k (random size)) (incf k sbeg) (push (nth k lst) shuflst) (setf last (+ sbeg (- size 1))) ;; "struck out" k-th element (setf (nth k lst) (nth last lst))) (do ((idx send (+ idx 1))) ((>= idx llen)) (push (nth idx lst) shuflst)) (nreverse shuflst)))) (defun %swap-list (lst i j &optional start) (when start (setf i (+ start i)) (setf j (+ start j))) (let ((tmp (nth i lst))) (setf (nth i lst) (nth j lst)) (setf (nth j lst) tmp))) (defun %knuth-shuffle (lst &optional start end) "NOTICE: will modify `lst', copy-list if necessary" (let (k) (multiple-value-bind (sbeg slen) (%subseq-values lst start end) (do ((size slen (- size 1))) ((<= size 0)) ;; `size' is the sub-list length (setf k (random size)) (%swap-list lst k (- size 1) sbeg)) lst))) (defun shuffle-indices (n) (let ((indices (make-indices n))) (%knuth-shuffle indices))) (defun shuffle (lst &optional start end) "NOTICE: will modify `lst', copy-list if necessary" (%knuth-shuffle lst start end))
2,027
Common Lisp
.lisp
57
29.912281
77
0.599184
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
ca7541945e26a4ed22636eb093f3b444ba170ba75bc121f2810d915b592e93a0
17,336
[ -1 ]
17,337
indices.lisp
jnjcc_cl-ml/probs/indices.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-ml/probs) (defun make-step-range (start end &optional (step 1)) (let ((lst nil) (endfn #'>=)) (when (< step 0) (setf endfn #'<=)) (do ((val start (+ val step))) ((funcall endfn val end)) (push val lst)) (nreverse lst))) (defun make-indices (n) (make-step-range 0 n))
403
Common Lisp
.lisp
14
24.428571
66
0.580311
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
3a72781589606a905f121a66af7602f764ea5f9a7cb001f04b26f62eea453e01
17,337
[ -1 ]
17,338
packages.lisp
jnjcc_cl-ml/probs/packages.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Probability and Statistics (in-package #:cl-user) (defpackage #:cl-ml/probs (:nicknames #:ml/probs) (:use #:cl) (:export #:float= #:float/= #:float< #:float> #:cumsum #:randint #:randuni #:randnorm ;; range and indices #:make-step-range #:make-indices ;; combinations and permutations #:combinations #:combinations-indices #:visit-combinations-indices #:permutations #:permutations-indices #:visit-permutations-indices ;; shuffle #:shuffle #:shuffle-indices ;; sampling #:simple-sampling #:simple-indices #:weighted-sampling #:weighted-indices #:alias-initialize #:alias-draw-index #:alias-draw-element #:alias-sampling #:alias-indices #:bootstrap-sampling #:bootstrap-indices #:pasting-sampling #:pasting-indices ;; bin operations #:binkey #:binvalue #:bincount #:binincf #:bindecf #:binpush #:do-bins #:density #:probability #:bindensity #:argmax #:argmin ;; statistics #:quantile-positions #:quantile ))
1,306
Common Lisp
.lisp
36
26.333333
69
0.569731
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
e3d649f0ffa6da331e12cdfebbe78f4eefa3ea81268469c3c718038dd75df788
17,338
[ -1 ]
17,339
sampling.lisp
jnjcc_cl-ml/probs/sampling.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Random sampling (through indices) (in-package #:cl-ml/probs) ;;; Simple random sampling (using reservoir sampling) (defun simple-sampling (lst &optional k) (unless k (setf k (length lst))) (let ((sampl nil)) (dotimes (i (length lst)) (if (< i k) (push (nth i lst) sampl) (let ((ridx (randint 0 i))) (when (< ridx k) (setf (nth ridx sampl) (nth i lst)))))) sampl)) (defun simple-indices (n &optional k) (unless k (setf k n)) (let ((sampl nil)) (dotimes (i n) (if (< i k) (push i sampl) (let ((ridx (randint 0 i))) (when (< ridx k) (setf (nth ridx sampl) i))))) sampl)) ;;; Stratified random sampling (defun stratified-sampling (lst &optional k) ) (defun stratified-indices (n &optional k) ) ;;; Cluster random sampling (defun cluster-sampling (lst &optional k) ) (defun cluster-indices (n &optional k) ) ;;; Weighted random sampling (defun weighted-sampling (lst weights &optional k) (unless k (setf k (length lst))) (let* ((len (length weights)) (cdf (cumsum weights)) (tot (car (last cdf))) (rnd (randuni 1.0 k)) ;; result sampling list (spl nil)) (unless (= tot 1.0) ;; in case total weight not equal to 1.0 (setf cdf (mapcar (lambda (val) (/ val tot)) cdf))) (dotimes (i k) (dotimes (j len) (when (>= (nth j cdf) (nth i rnd)) (when (<= (nth i rnd) (nth j cdf)) (push (nth j lst) spl) (return))))) spl)) (defun weighted-indices (weights &optional k) (unless k (setf k (length weights))) (let* ((len (length weights)) (cdf (cumsum weights)) (tot (car (last cdf))) (rnd (randuni 1.0 k)) (spl nil)) (unless (= tot 1.0) (setf cdf (mapcar (lambda (val) (/ val tot)) cdf))) (dotimes (i k) (dotimes (j len) (when (>= (nth j cdf) (nth i rnd)) (push j spl) (return)))) spl)) ;;; Alias method sampling (defun alias-initialize (weights) "NOTICE: Requires: all(weights != 0)" (let* ((len (length weights)) (sweight (sum weights)) (probs-table (make-list len)) (alias-table (make-list len)) underfull overfull) (unless (float= sweight 1.0) ;; in case sum(weights) != 0 (setf weights (mapcar (lambda (x) (/ x sweight)) weights))) (dotimes (i len) (setf (nth i probs-table) (* len (nth i weights))) (setf (nth i alias-table) i) (cond ((float< (nth i probs-table) 1.0) (push i underfull)) ((float> (nth i probs-table) 1.0) (push i overfull)))) (do ((uidx nil) (oidx nil)) ((and (null underfull) (null overfull))) (setf uidx (pop underfull)) (setf oidx (pop overfull)) (setf (nth uidx alias-table) oidx) (decf (nth oidx probs-table) (- 1.0 (nth uidx probs-table))) (cond ((float< (nth oidx probs-table) 1.0) (push oidx underfull)) ((float> (nth oidx probs-table) 1.0) (push oidx overfull)))) (values probs-table alias-table))) (defun alias-draw-index (probs-table alias-table) (let ((len (length probs-table)) ridx prob) (setf ridx (randint len)) (setf prob (random 1.0)) (when (>= prob (nth ridx probs-table)) (setf ridx (nth ridx alias-table))) ridx)) (defun alias-draw-element (lst probs-table alias-table) (let ((ridx (alias-draw-index probs-table alias-table))) (nth ridx lst))) (defun alias-sampling (lst weights &optional k) (unless k (setf k (length lst))) (multiple-value-bind (probs-table alias-table) (alias-initialize weights) (let ((ridx nil) (spl nil)) (dotimes (i k) (setf ridx (alias-draw-index probs-table alias-table)) (push (nth ridx lst) spl)) spl))) (defun alias-indices (weights &optional k) (unless k (setf k (length weights))) (multiple-value-bind (probs-table alias-table) (alias-initialize weights) (let ((len (length weights)) (ridx nil) (prob nil) (spl nil)) (dotimes (i k) (setf ridx (randint len)) (setf prob (random 1.0)) (when (>= prob (nth ridx probs-table)) (setf ridx (nth ridx alias-table))) (push ridx spl)) spl))) ;;; Bootstrap sampling (defun bootstrap-sampling (lst &optional k) "sampling with replacement" (let ((n (length lst)) (ridx nil) (samples nil)) (unless k (setf k (length lst))) (dotimes (i k) (setf ridx (random n)) (push (nth ridx lst) samples)) (nreverse samples))) (defun bootstrap-indices (n &optional k) "(values sampled-indices unsampled-indices)" (unless k (setf k n)) (let ((samples nil) (unsamples nil) (indices (make-indices n)) (idx nil)) (dotimes (i k) (setf idx (random n)) (setf (nth idx indices) nil) (push idx samples)) (dolist (ind indices) (when ind (push ind unsamples))) (values (nreverse samples) (nreverse unsamples)))) (defun pasting-sampling (lst &optional k) "sampling without replacement NOTICE: will modify `lst', copy-list if necessary" (unless k (setf k (length lst))) (shuffle lst) (subseq lst 0 k)) (defun pasting-indices (n &optional k) (let ((indices (make-indices n))) (pasting indices k)))
5,507
Common Lisp
.lisp
174
25.655172
75
0.589652
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
9064e6be311ce1534ed1c9c6fe15aadd98e14caee1871785ab869e43a3876e51
17,339
[ -1 ]
17,340
binary-tree.lisp
jnjcc_cl-ml/algo/binary-tree.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Common Data Structure: Binary Tree (in-package #:cl-ml/algo) ;;; Binary tree with the list form (data ltree rtree) ;;; so that (copy-tree) (tree-equal) works fine (defun make-binary-tree (data &optional (ltree nil) (rtree nil)) (list data ltree rtree)) (defun get-tree-data (root) (when root (car root))) (defun get-left-tree (root) (when root (cadr root))) (defun get-left-data (root) (get-tree-data (get-left-tree root))) (defun get-right-tree (root) (when root (caddr root))) (defun get-right-data (root) (get-tree-data (get-right-tree root))) (defun is-tree-leaf (root) (and (null (get-left-tree root)) (null (get-right-tree root)))) (defun set-tree-data (root data) (when root (setf (car root) data))) (defun set-left-tree (root ltree) (when root (setf (cadr root) ltree))) (defun set-right-tree (root rtree) (when root (setf (caddr root) rtree))) (defun set-left-data (root data) (if (get-left-tree root) (set-tree-data (get-left-tree root) data) (set-left-tree root (make-binary-tree data)))) (defun set-right-data (root data) (if (get-right-tree root) (set-tree-data (get-right-tree root) data) (set-right-tree root (make-binary-tree data)))) (defun inorder-visit (root &optional (visit #'princ)) (when root (inorder-visit (get-left-tree root) visit) (funcall visit (get-tree-data root)) (inorder-visit (get-right-tree root) visit))) (defun preorder-visit (root &optional (visit #'princ)) (when root (funcall visit (get-tree-data root)) (preorder-visit (get-left-tree root) visit) (preorder-visit (get-right-tree root) visit))) (defun postorder-visit (root &optional (visit #'princ)) (when root (postorder-visit (get-left-tree root) visit) (postorder-visit (get-right-tree root) visit) (funcall visit (get-tree-data root))))
1,942
Common Lisp
.lisp
55
31.945455
66
0.684126
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
9e693607ea17026a1fa0201210c8627e479767d83799bfe297111d7b01d04446
17,340
[ -1 ]
17,341
queue.lisp
jnjcc_cl-ml/algo/queue.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Common Data Structure: FIFO queue (in-package #:cl-ml/algo) ;;; FIFO queue with list (defun make-queue () nil) (defmacro queue-enque (queue data) "(macroexpand-1 '(push 1 stack)" `(setq ,queue (nconc ,queue (list ,data)))) (defmacro queue-deque (queue) "(macroexpand-1 '(pop stack))" `(prog1 (car ,queue) (setq ,queue (cdr ,queue)))) (defun queue-front (queue) (car queue)) (defun queue-empty (queue) (= (length queue) 0))
532
Common Lisp
.lisp
19
25.315789
66
0.66075
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
21844b6d6e408e2f8997f04e5526d5ab529f3449241b6df12f35c12f05d0616c
17,341
[ -1 ]
17,342
kmp.lisp
jnjcc_cl-ml/algo/kmp.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Knuth¨CMorris¨CPratt string search algorithm (in-package #:cl-ml/algo)
149
Common Lisp
.lisp
4
36
66
0.715278
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
e6c6d6fb8b5cf02294e2c5db87c6875125787119a41893ca3ec226ff1059ac61
17,342
[ -1 ]
17,343
huffman.lisp
jnjcc_cl-ml/algo/huffman.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Common Data Structure: Huffman Tree (in-package #:cl-ml/algo) (defun choose-min-node (nodes nleaf lpos ipos &key (freqfn #'cdr)) "[0, `nleaf'] of `nodes' being leafs with default form ((word . freq) ...), while [`nleaf', ) being inner nodes of the form (freq freq ...)" (let (lfreq ifreq midx mfreq) (if (< lpos nleaf) (progn (setf lfreq (funcall freqfn (nth lpos nodes)) ifreq (nth ipos nodes)) (cond ((or (null ifreq) (< lfreq ifreq)) (progn ;; use up one leaf node (setf midx lpos mfreq lfreq) (incf lpos))) ((>= lfreq ifreq) (progn (setf midx ipos mfreq ifreq) (incf ipos))))) (progn ;; no more leafs left! (setf midx ipos mfreq (nth ipos nodes)) (incf ipos))) (values midx mfreq lpos ipos))) (defun enque-merged-tree (tree-que nodes nleaf midx1 midx2 pfreq) (cond ((and (< midx1 nleaf) (< midx2 nleaf)) ;; merge two leafs (queue-enque tree-que (make-binary-tree pfreq (make-binary-tree (nth midx1 nodes)) (make-binary-tree (nth midx2 nodes))))) ((and (< midx1 nleaf) (>= midx2 nleaf)) (let ((rtree (queue-deque tree-que))) (queue-enque tree-que (make-binary-tree pfreq (make-binary-tree (nth midx1 nodes)) rtree)))) ((and (>= midx1 nleaf) (< midx2 nleaf)) (let ((ltree (queue-deque tree-que))) (queue-enque tree-que (make-binary-tree pfreq ltree (make-binary-tree (nth midx2 nodes)))))) ((and (>= midx1 nleaf) (>= midx2 nleaf)) (let ((ltree (queue-deque tree-que)) (rtree (queue-deque tree-que))) (queue-enque tree-que (make-binary-tree pfreq ltree rtree))))) tree-que) (defun get-huffman-coding (nodes nleaf parents binarys &key (keyfn nil)) (let ((huff-coding nil) (cur-coding nil)) (dotimes (i nleaf) (setf cur-coding nil) (do ((idx i)) ((null (nth idx parents))) (push (nth idx binarys) cur-coding) (setf idx (nth idx parents))) (if keyfn (push (cons (funcall keyfn (nth i nodes)) cur-coding) huff-coding) (push (cons (nth i nodes) cur-coding) huff-coding))) huff-coding)) (defun huffman-from-list (lsts &key (coded nil) (keyfn #'car) (freqfn #'cdr) (sorted nil)) "Huffman tree from list with default form ((word . freq) ...), thus `freqfn' being #'cdr Requires: `sorted' in ascending order NOTICE: might modify `lsts', copy-list if necessary" (let* ((nleaf (length lsts)) (leafs lsts) ;; there will only be (n-1) inner nodes for huffman tree, in fact (inner (make-list nleaf :initial-element nil)) (nodes nil)) (unless sorted (setf leafs (sort leafs #'< :key freqfn))) (setf nodes (append leafs inner)) (let (;;; Two-way merge sort: leaf index and inner node index (lpos 0) (ipos nleaf) ;; left/right child index and frequency; parent index and frequency midx1 mfreq1 midx2 mfreq2 pidx pfreq (tree-que nil) ;;; Huffman coding when `coded' (parents nil) (binarys nil) (huff-coding nil)) (when coded (setf parents (make-list (length nodes) :initial-element nil)) (setf binarys (make-list (length nodes) :initial-element 0))) (dotimes (i (- nleaf 1)) (multiple-value-setq (midx1 mfreq1 lpos ipos) (choose-min-node nodes nleaf lpos ipos :freqfn freqfn)) (multiple-value-setq (midx2 mfreq2 lpos ipos) (choose-min-node nodes nleaf lpos ipos :freqfn freqfn)) ;; i-th inner node! (setf pidx (+ i nleaf)) (setf pfreq (+ mfreq1 mfreq2)) (setf (nth pidx nodes) pfreq) (when coded (setf (nth midx1 parents) pidx) (setf (nth midx2 parents) pidx) ;; midx2 as the right child (setf (nth midx2 binarys) 1)) (setf tree-que (enque-merged-tree tree-que nodes nleaf midx1 midx2 pfreq))) (when coded (setf huff-coding (get-huffman-coding nodes nleaf parents binarys :keyfn keyfn))) (values (car tree-que) huff-coding parents binarys)))) (defun preorder-huffman (root &optional (depth 0) (stream t)) (when root (format stream "~A" (repeat-string "| " depth)) (format stream "~A" (get-tree-data root)) (format stream "~%") (preorder-huffman (get-left-tree root) (+ depth 1) stream) (preorder-huffman (get-right-tree root) (+ depth 1) stream))) (defun inorder-huffman (root &optional (depth 0) (stream t) (level #\Tab)) "not quite inorder: right-tree -> parent -> left-tree" (when root (inorder-huffman (get-right-tree root) (+ depth 1) stream level) (let* ((data (format nil "~A" (get-tree-data root))) (dlen (length data))) (format stream "~A~A/~%" (repeat-string level depth) (repeat-string #\Space dlen)) (format stream "~A~A~%" (repeat-string level depth) data) (format stream "~A~A\\~%" (repeat-string level depth) (repeat-string #\Space dlen))) (inorder-huffman (get-left-tree root) (+ depth 1) stream level)))
5,569
Common Lisp
.lisp
123
35.430894
90
0.574738
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
6b90abaf94c89f5870cb4823e9522035c45a6b4cf4c57374793fa81865c6cdb5
17,343
[ -1 ]
17,344
packages.lisp
jnjcc_cl-ml/algo/packages.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Common data structure and algorithms for Machine Learning and NLP (in-package #:cl-user) (defpackage #:cl-ml/algo (:nicknames #:ml/algo) (:use #:cl) (:export #:repeat-string #:join-strings #:split-string #:split-string-if #:replace-string #:replace-string-if ;; binary tree #:make-binary-tree #:is-tree-leaf #:get-tree-data #:get-left-tree #:get-left-data #:get-right-tree #:get-right-data #:set-tree-data #:set-left-tree #:set-left-data #:set-right-tree #:set-right-data #:inorder-visit #:preorder-visit #:postorder-visit ;; stack #:make-stack #:stack-empty #:stack-top #:stack-push #:stack-pop ;; FIFO queue #:make-queue #:queue-empty #:queue-front #:queue-enque #:queue-deque ;; Huffman Tree #:huffman-from-list #:preorder-huffman #:inorder-huffman ))
1,049
Common Lisp
.lisp
27
29.814815
92
0.57451
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
39ea3520e43f23d72389bf14ce4a36eab8187efb06409d11ba8ef88d855a2c3e
17,344
[ -1 ]
17,345
stack.lisp
jnjcc_cl-ml/algo/stack.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Common Data Structure: Stack (in-package #:cl-ml/algo) ;;; Stack with list (defun make-stack () nil) (defmacro stack-push (stack data) `(setq ,stack (cons ,data ,stack))) (defmacro stack-pop (stack) `(prog1 (car ,stack) (setq ,stack (cdr ,stack)))) (defun stack-top (stack) (car stack)) (defun stack-empty (stack) (= (length stack) 0))
441
Common Lisp
.lisp
17
23.294118
66
0.657895
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
9d2f2614ccde0cb983d38c25aaae79aa97d95c4cbf55c7ab5c3f98ab89fb01cd
17,345
[ -1 ]
17,346
cost.lisp
jnjcc_cl-ml/metrics/cost.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-ml) ;;; MSE (Mean squared error): ;;; - 1/2m \sum_{i=1}^{m}(x^{(i)}w - y(i))^{2} ;;; - 1/2(Xw - y)(Xw - y) (defun mse-cost (y ypred) (let ((sv (v- y ypred))) (* (/ 1 2) (vdot sv sv)))) (defun mse-gradient (theta X y) ;; 1/m * X^{T} * (Xw - y) (m* (/ 1 (nrow X)) (mt X) (m- (m* X theta) y))) (defun sigmoid (tval) (/ 1 (+ 1 (exp (- tval))))) (defun log-loss (y ypred) "Logistic Regression cost function, cross entropy, or log loss" ;; -1/m * \sum_{i=1}^{m}[y * log(p) + (1 - y) * log(1 - p)] (- (* (/ 1 (nrow y)) (+ (vdot y (vmap ypred #'log)) (vdot (v- 1 y) (vmap (v- 1 ypred) #'log)))))) (defun log-gradient (theta X y) ;; 1/m * X^{T} * (a - y) => ;; 1/m * X^{T} * [sigmoid(X * w) - y] (m* (/ 1 (nrow X)) (mt X) (v- (vmap (m* X theta) #'sigmoid) y))) ;;; entropy (defun log2 (x) (if (= x 0) 0.0 (log x 2))) (defun entropy (p) (let ((ent 0.0) (vpi 0.0)) (do-vector (i p) (setf vpi (vref p i)) (incf ent (- (* vpi (log2 vpi))))) ent)) (defun entropy-list (p) (let ((ent 0.0)) (dolist (lpi p) (incf ent (- (* lpi (log2 lpi))))) ent)) ;;; gini (defun gini-impurity (p) (let ((gni 1.0) (vpi 0.0)) (do-vector (i p) (setf vpi (vref p i)) (decf gni (* vpi vpi))) gni)) (defun gini-list (p) (let ((gni 1.0)) (dolist (lpi p) (decf gni (* lpi lpi))) gni))
1,511
Common Lisp
.lisp
56
22.910714
66
0.481994
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
83b38bb4e977352ac47b22e78beeb95b590cd948e95e008febfdcc36175933a4
17,346
[ -1 ]
17,347
classifier.lisp
jnjcc_cl-ml/metrics/classifier.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-ml) (defun print-confusion-matrix (cmatrix labenc &optional (stream t)) (format stream "A\\P") (dotimes (j (label-nums labenc)) (format stream "~A~A" #\Tab (get-encoder-label labenc j))) (format stream "~%") (do-matrix-row (i cmatrix) (format stream "~A" (get-encoder-label labenc i)) (do-matrix-col (j cmatrix) (format stream "~A~A" #\Tab (mref cmatrix i j))) (format stream "~%"))) (defun confusion-matrix (ylabel ypred) "row: actual class; column: predicted class" (let ((labenc (make-instance 'label-encoder))) (fit labenc ylabel) (let ((cmatrix (make-square-matrix (label-nums labenc) :initial-element 0)) i j) (do-vector (iy ylabel) (setf i (get-encoder-index labenc (vref ylabel iy))) (setf j (get-encoder-index labenc (vref ypred iy))) (incf (mref cmatrix i j))) (values cmatrix labenc)))) ;;; TODO: multiclass precision (defun binary-confusion (ylabel ypred &optional (positive +1)) (let ((tp 0) (fn 0) (fp 0) (tn 0)) (do-vector (i ylabel) (let ((y (vref ylabel i)) (yhat (vref ypred i))) (cond ((and (= yhat positive) (= y positive)) (incf tp)) ((and (= yhat positive) (/= y positive)) (incf fp)) ((and (/= yhat positive) (= y positive)) (incf fn)) ((and (/= yhat positive) (/= y positive)) (incf tn))))) (values tp fn fp tn))) (defun precision-score (ylabel ypred &optional (positive +1)) (multiple-value-bind (tp fn fp tn) (binary-confusion ylabel ypred positive) (declare (ignore fn tn)) (float (/ tp (+ tp fp))))) (defun recall-score (ylabel ypred &optional (positive +1)) (multiple-value-bind (tp fn fp tn) (binary-confusion ylabel ypred positive) (declare (ignore fp tn)) (float (/ tp (+ tp fn))))) (defun f1-score (ylabel ypred &optional (positive +1)) "F1 = 2 / (1/prec + 1/reca) = 2 * prec * reca / (prec + reca) = tp / (tp + (fn + fp)/2)" (multiple-value-bind (tp fn fp tn) (binary-confusion ylabel ypred positive) (declare (ignore tn)) (float (/ tp (+ tp (/ (+ fn fp) 2)))))) (defun accuracy-score (ylabel ypred) (let ((acc 0) (num (nrow ylabel))) (do-vector (i ylabel) (when (= (vref ypred i) (vref ylabel i)) (incf acc))) (float (/ acc num)))) ;;; roc-curve roc-auc-score (defun roc-curve (ylabel ypred &optional (positive +1)) (let ((tpnums nil) ;; true positive nums for each threshold (fpnums nil) ;; will be converted to TPR and FPR (thresh nil) ;; threshold list (indices (make-indices (nrow ypred)))) (setf indices (sort-indices indices ypred :predicate #'>)) ;; for each (unique) threshold, in descending order (let ((prev-thresh nil) (curr-thresh nil) (tpcumsum 0.0) ;; cumsum of true positive (fpcumsum 0.0)) (do-ia-access (indx indices) (setf curr-thresh (vref ypred indx)) (when (or (null prev-thresh) (/= curr-thresh prev-thresh)) (push tpcumsum tpnums) (push fpcumsum fpnums) (if (null prev-thresh) (push 1.0 thresh) (push prev-thresh thresh)) (setf prev-thresh curr-thresh)) (if (= (vref ylabel indx) positive) (incf tpcumsum 1.0) (incf fpcumsum 1.0))) (push tpcumsum tpnums) (push fpcumsum fpnums) (push prev-thresh thresh)) (setf tpnums (mapcar (lambda (x) (/ x (car tpnums))) tpnums)) (setf fpnums (mapcar (lambda (x) (/ x (car fpnums))) fpnums)) (values (nreverse fpnums) (nreverse tpnums) (nreverse thresh)))) (defun auc-score (x y) "(x[i], y[i]) being points of trapezoid; where X an Y are lists Requires: X, Y in ascending order" (let ((len (length x)) (auc 0.0)) (dotimes (i (- len 1)) ;; 1/2 * (x[i+1] - x[i]) * (y[i] + y[i+1]) (incf auc (* 1/2 (- (nth (+ i 1) x) (nth i x)) (+ (nth i y) (nth (+ i 1) y))))) auc)) (defun roc-auc-score (ylabel ypred &optional (positive +1)) (multiple-value-bind (fpr tpr) (roc-curve ylabel ypred positive) (auc-score fpr tpr)))
4,187
Common Lisp
.lisp
97
37.123711
90
0.602599
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
90451af6e18446fed4973194062432cad22489b2069c9b353733cf0a9c7ada0f
17,347
[ -1 ]
17,348
regressor.lisp
jnjcc_cl-ml/metrics/regressor.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-ml) (defun mean-squared-error (y ypred) (let ((sqerr 0.0) (sub 0.0)) (do-vector (i y) (setf sub (- (vref y i) (vref ypred i))) (incf sqerr (* sub sub))) (/ sqerr (nrow y))))
295
Common Lisp
.lisp
10
25.3
66
0.565371
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
4d6bf7b4cc51e2e09bb1200303df6fc93330b8a431b81d232aed4be0c0bb8421
17,348
[ -1 ]
17,349
cluster.lisp
jnjcc_cl-ml/metrics/cluster.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-ml) ;;; Distances for clustering (defun minkowski-distance (x y p) (let ((sum 0)) (do-vector (i x) (incf sum (expt (abs (- (vref x i) (vref y i))) p))) (expt sum (/ 1 p)))) (defun euclidean-distance (x y) (let ((sum 0) (cur nil)) (do-vector (i x) (setf cur (- (vref x i) (vref y i))) (incf sum (* cur cur))) (expt sum 1/2))) (defun euclidean-squared (x y) (let ((sum 0) (cur nil)) (do-vector (i x) (setf cur (- (vref x i) (vref y i))) (incf sum (* cur cur))) sum)) (defun manhattan-distance (x y) (let ((sum 0)) (do-vector (i x) (incf sum (abs (- (vref x i) (vref y i))))) sum)) (defun chebyshev-distance (x y) (let ((sum nil) (cur nil)) (do-vector (i x) (setf cur (abs (- (vref x i) (vref y i)))) (when (or (null sum) (< sum cur)) (setf sum cur))) sum)) (defun mahalanobis-distance (x y sigma) "X Y can be row or column vectors; `sigma': covariance matrix" (let ((dif (m- x y)) (sqdiff nil)) (ecase (svector-type dif) (:row (setf sqdiff (m* dif (minv sigma) (mt dif)))) (:column (setf sqdiff (m* (mt dif) (minv sigma) dif)))) (expt (mref sqdiff 0 0) 1/2))) (defun correlation-coefficient (x y) (let ((xbar 0) (ybar 0) (xysum 0) (xqsum 0) (yqsum 0) ;; might be row vector (size (* (nrow x) (ncol x)))) (do-vector (i x) (incf xbar (vref x i)) (incf ybar (vref y i))) (setf xbar (/ xbar size)) (setf ybar (/ ybar size)) (do-vector (i x) (let ((xdiff (- (vref x i) xbar)) (ydiff (- (vref y i) ybar))) (incf xysum (* xdiff ydiff)) (incf xqsum (* xdiff xdiff)) (incf yqsum (* ydiff ydiff)))) (/ xysum (expt (* xqsum yqsum) 1/2)))) (defun cosine-distance (x y) (let ((xysum 0) (xqsum 0) (yqsum 0)) (do-vector (i x) (let ((xi (vref x i)) (yi (vref y i))) (incf xysum (* xi yi)) (incf xqsum (* xi xi)) (incf yqsum (* yi yi)))) (/ xysum (expt (* xqsum yqsum) 1/2))))
2,210
Common Lisp
.lisp
75
23.626667
66
0.520696
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
9734b6edca538b9c8580336672b0752b4a897c0f2d9f311f32067b05584b8218
17,349
[ -1 ]
17,350
ksvc.lisp
jnjcc_cl-ml/linear/ksvc.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Non-Linear Support Vector Machine for classification (in-package #:cl-ml) (deftype kernel-type () '(member :linear :poly :rbf :sigmoid)) (defclass kernel-svc (estimator) ((yalpha :initform nil :type smatrix :documentation "y[i] * alpha[i]") (rho :initform nil) (spvectors :initform nil :type smatrix :documentation "support vectors") (spvectnum :initform 0) (penalty :initform 1 :initarg :penalty :reader penalty :documentation "penalty in primal problem, a.k.a, the C parameter") (kernel :initform :linear :initarg :kernel :type kernel-type :documentation "kernel parameters") (gamma :initform 1 :initarg :gamma) (coef0 :initform 0 :initarg :coef0) (degree :initform 1 :initarg :degree) (tolerance :initform 1.0e-3 :initarg :tolerance) (epochs :initform 1000 :initarg :epochs))) (defun linear-kernel (va vb) "<a, b>" (vdot va vb)) (defun poly-kernel (va vb &optional (gamma 1) (coef0 0) (degree 1)) "(gamma * <a, b> + coef0)^{degree}" (expt (+ (* gamma (vdot va vb)) coef0) degree)) (defun rbf-kernel (va vb &optional (gamma 1)) "exp(-gamma * ||a - b||^{2})" (let ((vminus (v- va vb))) (exp (* (- gamma) (vdot vminus vminus))))) (defun sigmoid-kernel (va vb &optional (gamma 1) (coef0 0)) "tanh(gamma * <a, b> + coef0)" (tanh (+ (* gamma (vdot va vb)) coef0))) (defmethod kernel-fn-matrix ((ksvc kernel-svc)) (with-slots (kernel gamma coef0 degree) ksvc (ecase kernel (:linear (lambda (X i j) (linear-kernel (mrv X i) (mrv X j)))) (:poly (lambda (X i j) (poly-kernel (mrv X i) (mrv X j) gamma coef0 degree))) (:rbf (lambda (X i j) (rbf-kernel (mrv X i) (mrv X j) gamma))) (:sigmoid (lambda (X i j) (sigmoid-kernel (mrv X i) (mrv X j) gamma coef0)))))) (defmethod kernel-fn-vectors ((ksvc kernel-svc)) (with-slots (kernel gamma coef0 degree) ksvc (ecase kernel (:linear #'linear-kernel) (:poly #'poly-kernel) (:rbf #'rbf-kernel) (:sigmoid #'sigmoid-kernel)))) ;;; There are so many parameters to maintain, we need a class! (defclass smo-solver () ((penalty :initform 1) (tolerance :initform 1.0e-3) (m :initform nil) (alpha-status :initform nil :type smatrix) ;; the diagonal element of kernel matrix (qdiag :initform nil :type smatrix) (kernel-fn :initform nil :type smatrix) ;; the gradient vector (grad :initform nil :type smatrix) (gbar :initform nil :type smatrix) (tau :initform 1.0e-12) ;; the shrink indices (indices :initform nil :type list) (nactive :initform nil))) (defmethod %update-alpha-status ((smo smo-solver) alpha i) (with-slots (penalty alpha-status) smo (let ((ai (vref alpha i))) (cond ((>= ai penalty) (setf (vref alpha-status i) :ubound)) ((<= ai 0) (setf (vref alpha-status i) :lbound)) (t (setf (vref alpha-status i) :free)))))) ;; TODO: caching and shrinking (defmethod %qmatrix-row ((smo smo-solver) X y i) (with-slots (indices nactive kernel-fn) smo (let ((Qrowi (make-vector nactive :initial-element 0)) (yi (vref y i)) yj) (do-active-alphas (j indices nactive) (setf yj (vref y j)) (setf (vref Qrowi j) (* yi yj (funcall kernel-fn X i j)))) Qrowi))) (defmethod initialize-solver ((smo smo-solver) alpha X y pvec ksvc) "initialize solver from kernel-svc and training set" (with-slots (penalty m alpha-status qdiag grad gbar indices nactive kernel-fn) smo (setf m (nrow X)) (setf kernel-fn (kernel-fn-matrix ksvc)) (setf alpha-status (make-vector m :initial-element :free)) (setf qdiag (make-vector m :initial-element 0)) (do-vector (i qdiag) (setf (vref qdiag i) (funcall kernel-fn X i i))) (do-vector (i alpha-status) (%update-alpha-status smo alpha i)) (setf indices (make-indices m)) (setf nactive m) ;; initialize gradient (setf grad (copy-matrix pvec)) (setf gbar (make-vector m :initial-element 0)) (dotimes (i m) (let ((status (vref alpha-status i))) (unless (eq status :lbound) (let ((Qrowi (%qmatrix-row smo X y i)) (alphi (vref alpha i))) (dotimes (j m) (incf (vref grad j) (* alphi (vref Qrowi j)))) (when (eq status :ubound) (dotimes (j m) (incf (vref gbar j) (* penalty (vref Qrowi j))))))))))) (defmethod select-working-set ((smo smo-solver) alpha X y) "Returns (values T nil nil) if optimal" (with-slots (alpha-status qdiag grad indices nactive tolerance tau) smo (let ((gmax :ninfty) ;; m(alpha) (gmax2 :ninfty) ;; -M(alpha) ival jval) (do-active-alphas (it indices nactive) (if (= (vref y it) +1) (unless (eq (vref alpha-status it) :ubound) (when (inf>= (- (vref grad it)) gmax) (setf gmax (- (vref grad it))) (setf ival it))) (unless (eq (vref alpha-status it) :lbound) (when (inf>= (vref grad it) gmax) (setf gmax (vref grad it)) (setf ival it))))) (let ((Qrowi (%qmatrix-row smo X y ival)) ;; a[t][s], b[t][s] quadcoef gradiff (objdiff-min :infty) (objdiff nil)) (do-active-alphas (it indices nactive) (if (= (vref y it) +1) (unless (eq (vref alpha-status it) :lbound) (setf gradiff (+ gmax (vref grad it))) (when (inf>= (vref grad it) gmax2) (setf gmax2 (vref grad it))) (when (> gradiff 0) (setf quadcoef (+ (vref Qdiag ival) (vref Qdiag it) (* -2.0 (vref y ival) (vref Qrowi it)))) (if (> quadcoef 0) (setf objdiff (- (/ (* gradiff gradiff) quadcoef))) (setf objdiff (- (/ (* gradiff gradiff) tau)))) (when (inf<= objdiff objdiff-min) (setf jval it) (setf objdiff-min objdiff)))) (unless (eq (vref alpha-status it) :ubound) (setf gradiff (- gmax (vref grad it))) (when (inf>= (- (vref grad it)) gmax2) (setf gmax2 (- (vref grad it)))) (when (> gradiff 0) (setf quadcoef (+ (vref Qdiag ival) (vref Qdiag it) (* 2.0 (vref y ival) (vref Qrowi it)))) (if (> quadcoef 0) (setf objdiff (- (/ (* gradiff gradiff) quadcoef))) (setf objdiff (- (/ (* gradiff gradiff) tau)))) (when (inf<= objdiff objdiff-min) (setf jval it) (setf objdiff-min objdiff)))))) (when (or (< (+ gmax gmax2) tolerance) (= jval -1)) (return-from select-working-set (values t nil nil))) (return-from select-working-set (values nil ival jval)))))) (defmethod reconstruct-gradient ((smo smo-solver) alpha X y) (with-slots (grad alpha-status gbar pvec indices nactive tolerance tau) smo (when (= nactive (length indices)) (return-from reconstruct-gradient)) (do-shrunk-alphas (j indices nactive) (setf (vref grad j) (+ (vref gbar j) (vref pvec j)))) (let ((m (nrow X)) (nfree 0) Qrowi alphi) (do-active-alphas (j indices nactive) (when (eq (vref alpha-status j) :free) (incf nfree))) (if (> (* nfree m) (* 2 nactive (- m nactive))) (do-shrunk-alphas (i indices nactive) (setf Qrowi (%qmatrix-row smo X y i)) (do-active-alphas (j indices nactive) (when (eq (vref alpha-status j) :free) (incf (vref grad j) (* (vref alpha j) (vref Qrowi j)))))) (do-active-alphas (i indices nactive) (when (eq (vref alpha-status i) :free) (setf Qrowi (%qmatrix-row smo X y i)) (setf alphi (vref alpha i)) (do-shrunk-alphas (j indices nactive) (incf (vref grad j) (* alphi (vref Qrowi j)))))))))) (defmethod shrink-alphas ((smo smo-solver)) ) (defmethod alphas-shrunk-p ((smo smo-solver)) (with-slots (nactive m) smo (< nactive m))) (defmethod unshrink-alphas ((smo smo-solver)) (with-slots (nactive m) smo (setf nactive m))) (defmethod two-variable-solve ((smo smo-solver) alpha i j Qrowi y) "Solve the two-variable sub-problem, update alpha[i], alpha[j]" (with-slots (penalty tau grad qdiag) smo (let (quadcoef delta) (if (/= (vref y i) (vref y j)) (let (diff) (setf quadcoef (+ (vref Qdiag i) (vref Qdiag j) (* 2 (vref Qrowi j)))) (when (<= quadcoef 0) (setf quadcoef tau)) (setf delta (/ (- (+ (vref grad i) (vref grad j))) quadcoef)) (setf diff (- (vref alpha i) (vref alpha j))) (incf (vref alpha i) delta) (incf (vref alpha j) delta) (if (> diff 0) (when (< (vref alpha j) 0) (setf (vref alpha j) 0) (setf (vref alpha i) diff)) (when (< (vref alpha i) 0) (setf (vref alpha i) 0) (setf (vref alpha j) (- diff)))) (if (> diff 0) ;; TODO: diff > C[i] - C[j] (when (> (vref alpha i) penalty) ;; alpha[i] > C[i] (setf (vref alpha i) penalty) (setf (vref alpha j) (- penalty diff))) (when (> (vref alpha j) penalty) (setf (vref alpha j) penalty) (setf (vref alpha i) (+ penalty diff))))) (let (sum) (setf quadcoef (+ (vref Qdiag i) (vref Qdiag j) (* -2 (vref Qrowi j)))) (when (<= quadcoef 0) (setf quadcoef tau)) (setf delta (/ (- (vref grad i) (vref grad j)) quadcoef)) (setf sum (+ (vref alpha i) (vref alpha j))) (decf (vref alpha i) delta) (incf (vref alpha j) delta) (if (> sum penalty) ;; TODO: sum > C[i] (when (> (vref alpha i) penalty) (setf (vref alpha i) penalty) (setf (vref alpha j) (- sum penalty))) (when (< (vref alpha j) 0) (setf (vref alpha j) 0) (setf (vref alpha i) sum))) (if (> sum penalty) ;; TODO: sum > C[j] (when (> (vref alpha j) penalty) (setf (vref alpha j) penalty) (setf (vref alpha i) (- sum penalty))) (when (< (vref alpha i) 0) (setf (vref alpha i) 0) (setf (vref alpha j) sum)))))))) (defmethod maintain-gradient ((smo smo-solver) alpha i j Qrowi Qrowj alphi alphj) "`alphi' and `alphj' being the old alpha before (two-variable-solve)" (with-slots (m penalty alpha-status grad gbar indices nactive) smo (let ((deltai (- (vref alpha i) alphi)) (deltaj (- (vref alpha j) alphj))) ;; update gradient (do-active-alphas (k indices nactive) (incf (vref grad k) (+ (* (vref Qrowi k) deltai) (* (vref Qrowj k) deltaj))))) (labels ((ubound-p (idx) (eq (vref alpha-status idx) :ubound))) ;; update gbar (let ((uboundi (ubound-p i)) (uboundj (ubound-p j))) (%update-alpha-status smo alpha i) (%update-alpha-status smo alpha j) (unless (eq uboundi (ubound-p i)) (if uboundi (dotimes (k m) (decf (vref gbar k) (* penalty (vref Qrowi k)))) (dotimes (k m) (incf (vref gbar k) (* penalty (vref Qrowi k)))))) (unless (eq uboundj (ubound-p j)) (if uboundj (dotimes (k m) (decf (vref gbar k) (* penalty (vref Qrowj k)))) (dotimes (k m) (incf (vref gbar k) (* penalty (vref Qrowj k)))))))))) (defmethod calculate-rho ((smo smo-solver) y) (with-slots (alpha-status grad indices nactive) smo (let ((nfree 0) (ygrad 0) (ygsum 0) (upbound :infty) (lobound :ninfty)) (do-active-alphas (i indices nactive) (setf ygrad (* (vref y i) (vref grad i))) (ecase (vref alpha-status i) (:ubound (if (= (vref y i) -1) (setf upbound (infmin upbound ygrad)) (setf lobound (infmax lobound ygrad)))) (:lbound (if (= (vref y i) +1) (setf upbound (infmin upbound ygrad)) (setf lobound (infmax lobound ygrad)))) (:free (progn (incf nfree) (incf ygsum ygrad))))) (if (> nfree 0) (/ ygsum nfree) (/ (+ upbound lobound) 2))))) (defmethod %smo-dual ((ksvc kernel-svc) X y) "Working Set Selection Using Second Order Information for Training Support Vector Machines" (with-slots (yalpha rho spvectors spvectnum epochs) ksvc (let* ((m (nrow X)) ;; 1/2 * alpha^{T} * Q * alpha + p^{T} * alpha (alpha (make-vector m :initial-element 0)) (pvec (make-vector m :initial-element -1)) (smo (make-instance 'smo-solver)) (m (nrow X)) (iters 0) ;; shrinking counter; working set {i, j} shrink-counter wi wj) (initialize-solver smo alpha X y pvec ksvc) (setf shrink-counter (min m 1000)) (dotimes (epoch epochs) (setf iters epoch) (decf shrink-counter) (when (= shrink-counter 0) (setf shrink-counter (min m 1000))) (let ((optimal nil)) (multiple-value-setq (optimal wi wj) (select-working-set smo alpha X y)) (when optimal (reconstruct-gradient smo alpha X y) (unshrink-alphas smo) (multiple-value-setq (optimal wi wj) (select-working-set smo alpha X y))) (if optimal ;; break out of iterations (return) ;; do shrinking the next iteration (setf shrink-counter 1))) (let ((Qrowi (%qmatrix-row smo X y wi)) (Qrowj (%qmatrix-row smo X y wj)) (alphi (vref alpha wi)) (alphj (vref alpha wj))) (two-variable-solve smo alpha wi wj Qrowi y) ;; TODO: here `Qrowi' and `Qrowj' must be full! (maintain-gradient smo alpha wi wj Qrowi Qrowj alphi alphj))) (when (>= iters epochs) ;; not optimal (when (alphas-shrunk-p smo) (reconstruct-gradient smo alpha X y) (unshrink-alphas smo))) ;; decision function: rho and alpha's (setf rho (calculate-rho smo y)) (setf spvectnum 0) (do-vector (i alpha) (setf (vref alpha i) (* (vref y i) (vref alpha i))) (when (> (abs (vref alpha i)) 0) (incf spvectnum))) (setf spvectors (make-matrix spvectnum (ncol X) :initial-element 0)) (setf yalpha (make-vector spvectnum :initial-element 0)) (let ((j 0)) (do-vector (i alpha) (when (> (abs (vref alpha i)) 0) (setf (mrv spvectors j) (mrv X i)) (setf (vref yalpha j) (vref alpha i)) (incf j))))))) (defmethod fit ((ksvc kernel-svc) X &optional y) (declare (type smatrix X)) (%smo-dual ksvc X y)) (defmethod predict-one ((ksvc kernel-svc) X i) (with-slots (yalpha rho spvectors spvectnum) ksvc (let ((kfn (kernel-fn-vectors ksvc)) (fval 0)) (dotimes (j spvectnum) (incf fval (* (vref yalpha j) (funcall kfn (mrv X i) (mrv spvectors j))))) (decf fval rho) (values (signfn fval) fval)))) (defmethod predict ((ksvc kernel-svc) X) (let ((pred (make-vector (nrow X) :initial-element +1))) (do-matrix-row (i X) (setf (vref pred i) (predict-one ksvc X i))) pred))
16,067
Common Lisp
.lisp
366
33.901639
86
0.547636
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
7db532e5128ec2a594295f3a12003ca9794e11c9a77ffefbb0ea86b6393a0a18
17,350
[ -1 ]
17,351
regression.lisp
jnjcc_cl-ml/linear/regression.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Linear Regression / Ridge Regression / Lasso Regression ;;;; - X * w = y, where row of X is an example, w and y are column vectors (in-package #:cl-ml) (deftype linear-solver () '(member :normal :pseudo)) (defclass linear-regressor (estimator) ((theta :initform nil :reader theta :type smatrix) (expand-bias :initform t :initarg :expand-bias :reader expand-bias) (solver :initform :normal :initarg :solver :reader solver :type linear-solver))) (deftype ridge-solver () '(member :normal :cholesky)) (defclass ridge-regressor (linear-regressor) ((solver :initform :normal :initarg :solver :reader solver :type ridge-solver) (alpha :initform 1.0 :initarg :alpha :reader alpha :documentation "weight for the L2 regularization term"))) (defmethod %normal-equation ((linear linear-regressor) X y) "fit using The Normal Equation" (with-slots (theta) linear ;; (X^{T} * X)^{-1} * X^{T} * y (setf theta (m* (minv (m* (mt X) X)) (mt X) y)) nil)) ;; TODO: pseudo-inverse (defmethod %pseudo-inverse ((linear linear-regressor) X y) (with-slots (theta) linear (setf theta (m* (mpinv X) y)) nil)) (defmethod %normal-equation ((ridge ridge-regressor) X y) (with-slots (theta expand-bias alpha) ridge (let ((idm (make-identity-matrix (ncol X)))) (when expand-bias (setf (mref idm 0 0) 0)) ;; (X^{T} * X + alpha * A)^{-1} * X^{T} * y (setf theta (m* (minv (m+ (m* (mt X) X) (m* alpha idm))) (mt X) y)) nil))) (defmethod fit ((linear linear-regressor) X &optional y) (declare (type smatrix X)) (let ((solver-fn (ecase (solver linear) (:normal #'%normal-equation) (:pseudo #'%pseudo-inverse)))) (when (expand-bias linear) (setf X (%expand-bias X))) (funcall solver-fn linear X y))) (defmethod fit ((ridge ridge-regressor) X &optional y) (declare (type smatrix X)) (let ((solver-fn (ecase (solver ridge) (:normal #'%normal-equation) (:cholesky #'%cholesky-solver)))) (when (expand-bias ridge) (setf X (%expand-bias X))) (funcall solver-fn ridge X y))) (defmethod predict ((linear linear-regressor) X) (with-slots (theta expand-bias) linear (if expand-bias (m* (%expand-bias X) theta) (m* X theta))))
2,401
Common Lisp
.lisp
57
36.859649
83
0.633248
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
6e5e30df6d90f6c2c70698c84f8fc00a922110df6f7ed2525e21c2760c9f3877
17,351
[ -1 ]
17,352
ksvr.lisp
jnjcc_cl-ml/linear/ksvr.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Non-Linear Support Vector Machine for regression (in-package #:cl-ml) (defclass kernel-svr (estimator) ((yalpha :initform nil :reader yalpha :type smatrix)))
239
Common Lisp
.lisp
6
38.166667
66
0.727273
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
227531fb2094f5dc21a645e588b846037a132e81b019e904b6e5356eed0eba4b
17,352
[ -1 ]
17,353
sgd.lisp
jnjcc_cl-ml/linear/sgd.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Gradient Descent (in-package #:cl-ml) (deftype sgd-loss () ":mse - Mean Squared Error" '(member :mse)) (deftype sgd-regularizer () '(member :none :l1 :l2)) (deftype sgd-btype () "batch-type: batch sgd mini-batch" '(member :batch :sgd :mini)) (defclass sgd-regressor (estimator) ((theta :initform nil :initarg :theta :reader theta :type smatrix) (loss :initform :mse :initarg :loss :reader loss :type sgd-loss) (regularizer :initform :none :initarg :regularizer :reader regularizer :type sgd-regularizer) (alpha :initform 1.0 :initarg :alpha :reader alpha) (epochs :initform 10 :initarg :epochs :reader epochs) (eta0 :initform 0.1 :initarg :eta0 :reader eta0) (btype :initform :batch :initarg :btype :reader btype :type sgd-btype) (expand-bias :initform t :initarg :expand-bias :reader expand-bias))) (defun %sign-vector (theta expand-bias) (declare (type smatrix theta)) (let ((vsign (make-vector (nrow theta) :initial-element 1))) (dotimes (i (nrow vsign) vsign) (cond ((and expand-bias (= i 0)) (setf (vref sign 0) 0)) ((< (vref theta i) 0) (setf (vref vsign i) -1)) ((= (vref theta i) 0) (setf (vref vsign i) 0)))))) (defmethod gradient ((sgd sgd-regressor) X y) (declare (type smatrix X y)) (with-slots (loss regularizer alpha theta expand-bias) sgd (let ((grad (ecase loss (:mse (mse-gradient theta X y))))) (case loss (:l1 (incf grad (m* alpha (%sign-vector theta expand-bias)))) (:l2 (incf grad (m* alpha theta)))) grad))) ;; TODO: theta-initialization & mini-batch gradient descent ;; - random initialize theta (defmethod %init-theta ((sgd sgd-regressor) nrow) (with-slots (theta) sgd (setf theta (make-rand-vector nrow 1.0)))) (defmethod %get-batch ((sgd sgd-regressor) X y) (declare (type smatrix X y)) (ecase (btype sgd) (:batch (values X y)) (:sgd (values X y)) (:mini (values X y)))) ;; TODO: ;; - learning rate schedule ;; - stopping criterion: loss tolerance (defmethod fit ((sgd sgd-regressor) X &optional y) (declare (type smatrix X)) (when (expand-bias sgd) (setf X (%expand-bias X))) (%init-theta sgd (ncol X)) (with-slots (theta epochs eta0) sgd (dotimes (i epochs) (multiple-value-bind (xbatch ybatch) (%get-batch sgd X y) (setf theta (m- theta (m* eta0 (gradient sgd xbatch ybatch)))))))) (defmethod predict ((sgd sgd-regressor) X) (declare (type smatrix X)) (with-slots (theta expand-bias) sgd (if expand-bias (m* (%expand-bias X) theta) (m* X theta))))
2,663
Common Lisp
.lisp
67
35.626866
96
0.656878
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
8b193c4abe76886f62bd786c64ea454120f23c0e495601761dfee59119f366e3
17,353
[ -1 ]
17,354
linsvc.lisp
jnjcc_cl-ml/linear/linsvc.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Linear Support Vector Machine for classification (in-package #:cl-ml) (deftype svc-loss () "L2-regularized L1-loss SVC; L2-regularized L2-loss SVC" '(member :l2reg-l1 :l2reg-l2)) (defclass linear-svc (estimator) ((theta :initform nil :reader theta :type smatrix) (loss :initform :l2reg-l1 :initarg :loss :reader loss :type svc-loss) (penalty :initform 1 :initarg :penalty :reader penalty :documentation "penalty in soft margin SVM, a.k.a, the C parameter") (tolerance :initform 0.1 :initarg :tolerance :documentation "tolerance \epsilon") (epochs :initform 100 :initarg :epochs) (expand-bias :initform t :initarg :expand-bias :reader expand-bias))) (defmethod %coord-descent-dual ((linsvc linear-svc) X y) "A Dual Coordinate Descent Method for Large-scale Linear SVM" (with-slots (theta loss penalty tolerance epochs) linsvc (let* ((m (nrow X)) (n (ncol X)) (alpha (make-vector m :initial-element 0)) upper diag (Qdiag (make-vector m :initial-element 0)) grad pgrad ;; permutation indices of alpha's (indices (make-indices m)) ;; the number of active `indices' after shrinking (nactive m) ;; shrinking (pgmax :infty) (pgmin :ninfty) pgmax-inner pgmin-inner) (setf theta (make-vector n :initial-element 0)) (ecase loss ;; L1-SVM: U = C; D[i][i] = 0 (:l2reg-l1 (setf upper penalty diag 0)) ;; L2-SVM: U = infty; D[i][i] = 1/2C (:l2reg-l2 (setf upper :infty diag (* 0.5 penalty)))) ;;; Q[i][i] diagonal elements (do-vector (i Qdiag) (setf (vref Qdiag i) (+ (vdot (mrv X i) (mrv X i)) diag))) (dotimes (epoch epochs) (setf pgmax-inner :ninfty) (setf pgmin-inner :infty) (shuffle indices 0 nactive) ;; `nactive' will change during the loop! (do-active-indices (i indx indices nactive) ;; G = y[i] * w * x[i] - 1 + D[i][i] * alpha[i] (setf grad (- (* (vref y indx) (vdot (mt theta) (mrv X indx))) 1)) (incf grad (* diag (vref alpha indx))) (setf pgrad 0) (cond ((= (vref alpha indx) 0) (cond ((inf> grad pgmax) (progn (shrink-indices indices i nactive) (go end-of-inner-loop))) ((< grad 0) (setf pgrad grad)))) ((inf= (vref alpha indx) upper) (cond ((inf< grad pgmin) (progn (shrink-indices indices i nactive) (go end-of-inner-loop))) ((> grad 0) (setf pgrad grad)))) (t (setf pgrad grad))) (setf pgmax-inner (infmax pgmax-inner pgrad)) (setf pgmin-inner (infmin pgmin-inner pgrad)) (when (float/= grad 0) (let ((alpold (vref alpha indx))) (setf (vref alpha indx) (infmin (max (- (vref alpha indx) (/ grad (vref Qdiag indx))) 0.0) upper)) (m+= theta (mt (m* (- (vref alpha indx) alpold) (vref y indx) (mrv X indx)))))) end-of-inner-loop) ;; it is possible that `pgmax-inner' be :ninfty and `pgmin-inner' be :infty (when (and (numberp pgmax-inner) (numberp pgmin-inner) (< (- pgmax-inner pgmin-inner) tolerance)) (if (= nactive m) ;; return-from outer-loop (return) (setf nactive m pgmax :infty pgmin :ninfty))) (setf pgmax pgmax-inner) (setf pgmin pgmin-inner) (when (inf<= pgmax-inner 0) (setf pgmax :infty)) (when (inf>= pgmin-inner 0) (setf pgmin :ninfty)))))) (defmethod fit ((linsvc linear-svc) X &optional y) (declare (type smatrix X)) (when (expand-bias linsvc) (setf X (%expand-bias X))) (%coord-descent-dual linsvc X y)) (defun signfn (elem) (if (>= elem 0) +1 -1)) (defmethod predict ((linsvc linear-svc) X) (with-slots (theta expand-bias) linsvc (if expand-bias (vmap (m* (%expand-bias X) theta) #'signfn) (vmap (m* X theta) #'signfn))))
4,426
Common Lisp
.lisp
102
32.529412
104
0.542169
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
ee52bd4ba31ad205cdbc9eac5b6460ee12bfce5c991e230bbf27b496e5e67d0d
17,354
[ -1 ]
17,355
linsvr.lisp
jnjcc_cl-ml/linear/linsvr.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Linear Support Vector Machine for regression (in-package #:cl-ml) (defclass linear-svr (estimator) ((theta :initform nil :reader theta :type smatrix) (expand-bias :initform t :initarg :expand-bias :reader expand-bias)))
304
Common Lisp
.lisp
7
41.428571
72
0.728814
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
b1d0bb6378b8fba1c65efc1ddfc5efd510c1200055fb884d59ca153933382697
17,355
[ -1 ]
17,356
logistic.lisp
jnjcc_cl-ml/linear/logistic.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Logistic Regression (in-package #:cl-ml) (deftype logistic-loss () '(member :logistic)) (defclass logistic-regression (sgd-regressor) ((loss :initform :logistic :initarg :loss :reader loss :type logistic-loss))) (defmethod gradient ((lreg logistic-regression) X y) (declare (type smatrix X y)) (with-slots (loss theta) lreg (ecase loss (:logistic (log-gradient theta X y))))) (defmethod predict ((lreg logistic-regression) X) (declare (type smatrix X)) (with-slots (theta expand-bias) lreg (if expand-bias (vmap (m* (%expand-bias X) theta) #'sigmoid) (vmap (m* X theta) #'sigmoid))))
708
Common Lisp
.lisp
19
33.789474
79
0.684211
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
2545005ecb16e8174b1afcbe31890e96416e901a7f96edc3d04575aa71d38a36
17,356
[ -1 ]
17,357
svm.lisp
jnjcc_cl-ml/linear/svm.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Support Vector Machine, the common algorithm (in-package #:cl-ml) ;;; TODO: Shrinking, how about a class of shrinking? (defmacro shrink-indices (indices i nactive) "struck out i-th index" ;; NOTICE: not necessary to do gensym, there are no &body `(progn (swap-indices ,indices ,i (- ,nactive 1)) (setf ,nactive (- ,nactive 1)))) (defmacro do-active-alphas ((indx indices nactive) &body body) "`indx' is the index of alpha's NOTICE: the `nactive' might change during loop" `(do-mutable-iacess (,indx ,indices ,nactive) ,@body)) (defmacro do-active-indices ((i indx indices nactive) &body body) "`indx' is the index of alpha's, I is the index of `indices' NOTICE: the `nactive' might change during loop" `(do-mutable-indices (,i ,indx ,indices ,nactive) ,@body)) (defmacro do-shrunk-alphas ((indx indices nactive) &body body) "`indx' is the index of alpha's NOTICE: change of `nactive' won't take effect" `(do-ia-access (,indx ,indices :start ,nactive) ,@body)) (defmacro do-shrunk-indices ((i indx indices nactive) &body body) "`indx' is the index of alpha's, I is the index of `indices' NOTICE: change of `nactive' won't take effect" `(do-indices (,i ,indx ,indices :start ,nactive) ,@body))
1,327
Common Lisp
.lisp
31
39.935484
66
0.697674
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
79af6c9a90d2ad2fd8812a60d9616f63535a5479acbaac68561a4057919d068b
17,357
[ -1 ]
17,358
cart.lisp
jnjcc_cl-ml/trees/cart.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Classification and Regression Tree (in-package #:cl-ml) (defmethod print-verbose ((dtree-est dtree-estimator) &optional (stream t) feaname labenc) (let ((feafun #'identity) (labelfun #'identity)) (when feaname (setf feafun (lambda (fidx) (nth fidx feaname)))) (when labenc (setf labelfun (lambda (value) (get-encoder-label labenc value)))) (with-slots (droot) dtree-est (print-dtree-depth droot stream 0 feafun labelfun)))) (defmethod predict-leaf ((dtree-est dtree-estimator) X i) (with-slots (droot) dtree-est (do ((tree droot) (data nil)) (data tree) (multiple-value-setq (tree data) (get-dtree-child tree X i))))) (defmethod leaf-regions ((dtree-est dtree-estimator) X) (let ((cur-leaf nil) (leaf-bins nil)) (do-matrix-row (i X) (setf cur-leaf (predict-leaf dtree-est X i)) (binpush leaf-bins cur-leaf i)) leaf-bins)) (defmethod %predict-one ((dtree-est dtree-estimator) X i) (with-slots (droot) dtree-est (do ((tree droot) (data nil)) (data data) (multiple-value-setq (tree data) (get-dtree-child tree X i))))) (defmethod predict-one ((dtree-est dtree-estimator) X i) (let ((node-data (%predict-one dtree-est X i))) (with-slots (value binfreqs nsamples) node-data (values value (density binfreqs nsamples))))) (defmethod predict ((dtree-est dtree-estimator) X) (let ((pred (make-vector (nrow X) :initial-element 0))) (do-matrix-row (i X) (setf (vref pred i) (predict-one dtree-est X i))) pred)) (defmethod feature-importance ((dtree-est dtree-estimator)) (with-slots (droot nfeat vimps) dtree-est (unless vimps (setf vimps (make-vector nfeat :initial-element 0.0))) (labels ((update-imp (node) (let* ((data (get-tree-data node)) (fidx (feature data))) (when fidx (incf (vref vimps fidx) (- (* (nsamples data) (impurity data)) (* (nsamples (get-left-data node)) (impurity (get-right-data node))) (* (nsamples (get-right-data node)) (impurity (get-right-data node))))) (update-imp (get-left-tree node)) (update-imp (get-right-tree node)))))) (update-imp droot)) vimps)) ;;; classifier (deftype impurity-type () '(member :gini :entropy :gain-ratio)) (defclass dtree-classifier (dtree-estimator) ((criterion :initform :gini :initarg :criterion :type impurity-type) (max-features :initform :all) (nclasses :initform 0))) (defmethod fit ((dtree-clf dtree-classifier) X &optional y) (with-slots (droot depth nfeat nclasses) dtree-clf (setf nfeat (ncol X)) (setf nclasses (length (mbincount y))) (let ((dframe (make-data-frame X y)) (splitter (make-root-splitter dtree-clf X))) (setf depth (split-node splitter dframe dtree-clf))))) (defmethod predict-proba ((dtree-clf dtree-classifier) X) (with-slots (nclasses) dtree-clf (let ((pred (make-matrix (nrow X) nclasses :initial-element 0.0))) (do-matrix-row (i X) (multiple-value-bind (fval binprobs) (predict-one dtree-clf X i) (declare (ignore fval)) (dolist (pair binprobs) (setf (mref pred i (car pair)) (cdr pair))))) pred))) ;;; regressor (deftype dtree-reg-type () '(member :mse)) (defclass dtree-regressor (dtree-estimator) ((criterion :initform :mse :type dtree-reg-type) (max-features :initform :all))) (defmethod fit ((dtree-reg dtree-regressor) X &optional y) (with-slots (droot depth nfeat) dtree-reg (setf nfeat (ncol X)) (let ((dframe (make-data-frame X y)) (splitter (make-root-splitter dtree-reg X))) (setf depth (split-node splitter dframe dtree-reg)))))
3,977
Common Lisp
.lisp
94
35.117021
90
0.624871
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
36c10ab23643305106d9a4e385a2e1742ff96462b53b75f5ba43cde33d247bab
17,358
[ -1 ]
17,359
forest.lisp
jnjcc_cl-ml/trees/forest.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Random Forest Estimator (in-package #:cl-ml) (defclass rforest-estimator (estimator) ((estimators :initform nil :documentation "list of decision tree estimators") (nestimators :initform 10 :initarg :nestimators) (bootstrap :initform t :initarg :bootstrap :documentation "if NIL, the whole dataset is used to build each tree") (oob-score :initform nil :documentation "oob score only works when BOOTSTRAP") (max-samples :initform nil :initarg :max-samples :documentation "number of samples to draw from training set if BOOTSTRAP") (max-features :initform :log2 :initarg :max-features :type rand-feature-type :documentation "number of features to consider when looking for the best split") (max-depth :initform nil :initarg :max-depth :reader max-depth) (min-samples-split :initform 2 :initarg :min-samples-split :reader min-samples-split) (min-samples-leaf :initform 1 :initarg :min-samples-leaf :reader min-samples-leaf) (max-leaf-nodes :initform nil :initarg :max-leaf-nodes :reader max-leaf-nodes) (criterion :initform :gini :type criterion-type))) (defmethod %get-samples ((rfest rforest-estimator) X y) (with-slots (bootstrap max-samples) rfest (if bootstrap (let* ((n (nrow X)) (nsamples (cond ((null max-samples) n) ((< 0 max-samples 1) (* max-samples n)) (t n)))) (multiple-value-bind (indices unindices) (bootstrap-indices nsamples) (values (make-matrix-view X :row-view indices) (make-matrix-view y :row-view indices) (make-matrix-view X :row-view unindices) (make-matrix-view y :row-view unindices) unindices indices))) (values X y nil nil nil nil)))) (defmethod predict-one ((rfest rforest-estimator) X i) (with-slots (estimators) rfest (let ((preds nil)) (dolist (dtest estimators) (push (predict-one dtest X i) preds)) (argmax (bincount preds))))) (defmethod predict ((rfest rforest-estimator) X) (let ((pred (make-vector (nrow X) :initial-element 0))) (do-matrix-row (i X) (setf (vref pred i) (predict-one rfest X i))) pred)) (defmethod feature-importance ((rfest rforest-estimator)) (with-slots (estimators) rfest (let ((vimps nil)) (dolist (dest estimators) (if vimps (m+= vimps (feature-importance dest)) (setf vimps (feature-importance dest)))) (m/= vimps (length estimators)) vimps))) ;;; Random Forest Classifier (defclass rforest-classifier (rforest-estimator) ((criterion :initform :gini :initarg :criterion :type impurity-type) (nclasses :initform 0) (oob-score :initform nil :initarg :oob-score :reader oob-score))) (defmethod initialize-instance :after ((rfclf rforest-classifier) &rest args) (declare (ignore args)) (with-slots (estimators nestimators max-features) rfclf (with-slots (max-depth min-samples-split min-samples-leaf max-leaf-nodes) rfclf (dotimes (i nestimators) (push (make-instance 'dtree-classifier :max-features max-features :max-depth max-depth :min-samples-split min-samples-split :min-samples-leaf min-samples-leaf :max-leaf-nodes max-leaf-nodes) estimators))))) (defmethod fit ((rfclf rforest-classifier) X &optional y) (with-slots (estimators bootstrap oob-score max-samples nclasses) rfclf (setf nclasses (length (mbincount y))) (let ((oob-preds nil)) (when oob-score (setf oob-preds (make-matrix (nrow X) nclasses :initial-element 0.0))) (dolist (dtclf estimators) (multiple-value-bind (Xv yv Xob yob oob-indices) (%get-samples rfclf X y) (declare (ignore yob)) (fit dtclf Xv yv) (when oob-score ;; TODO: what if `oob-view' & `predict-proba' has different shape? (with-matrix-view (oob-view :row-view oob-indices) oob-preds (m+= oob-view (predict-proba dtclf Xob)))))) ;; TODO: it is possible some examples have no `oob-preds' values (when oob-score (setf oob-preds (margmax oob-preds :axis 1)) (setf oob-score (accuracy-score y oob-preds)))))) ;;; Random Forest Regressor (defclass rforest-regressor (rforest-estimator) ((criterion :initform :mse :type dtree-reg-type))) (defmethod initialize-instance :after ((rfreg rforest-regressor) &rest args) (declare (ignore args)) (with-slots (estimators nestimators max-features) rfreg (with-slots (max-depth min-samples-split min-samples-leaf max-leaf-nodes) rfreg (dotimes (i nestimators) (push (make-instance 'dtree-regressor :max-features max-features :max-depth max-depth :min-samples-split min-samples-split :min-samples-leaf min-samples-leaf :max-leaf-nodes max-leaf-nodes) estimators))))) (defmethod fit ((rfreg rforest-regressor) X &optional y) (with-slots (estimators bootstrap max-samples) rfreg (dolist (dtreg estimators) (multiple-value-bind (Xv yv) (%get-samples rfreg X y) (fit dtreg Xv yv))))) (defmethod predict-one ((rfreg rforest-regressor) X i) (with-slots (estimators) rfreg (let ((preds nil)) (dolist (dtest estimators) (push (predict-one dtest X i) preds)) (/ (reduce #'+ preds :initial-value 0.0) (length preds)))))
5,673
Common Lisp
.lisp
112
41.946429
88
0.646539
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
d5d53cbb1d0697de1e100fd6c49561f2cb140feb89ce7aa357677b757a50a460
17,359
[ -1 ]
17,360
xgboost.lisp
jnjcc_cl-ml/trees/xgboost.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Extreme Gradient Boosting Trees (in-package #:cl-ml) (defclass xgboost-tree (gboost-estimator) ()) (defmethod initialize-instance :after ((xgtree xgboost-tree) &rest args) (declare (ignore args)) (with-slots (estimators nestimators loss) xgtree (with-slots (max-depth min-samples-split min-samples-leaf max-leaf-nodes) xgtree (dotimes (i nestimators) (push (make-instance 'xgb-regressor :max-depth max-depth :min-samples-split min-samples-split :min-samples-leaf min-samples-leaf :max-leaf-nodes max-leaf-nodes) estimators))))) ;;; XGBoost classifier (defclass xgboost-classifier (xgboost-tree) ()) (defmethod fit ((xgclf xgboost-classifier) X &optional y) ) ;;; XGBoost regressor (defclass xgboost-regressor (xgboost-tree) ((loss :initform :xgleast))) (defmethod initialize-instance :after ((xgreg xgboost-regressor) &rest args) (declare (ignore args)) (with-slots (loss) xgreg (setf loss (make-xgloss loss)))) (defmethod fit ((xgreg xgboost-regressor) X &optional y) (with-slots (estimators loss eta) xgreg (let ((fx (init-fit-and-predict loss y))) (dolist (xgreg estimators) (let ((ghgrad (negative-gradient loss y fx))) (fit xgreg X ghgrad) (setf fx (update-leaf-and-predict loss xgreg X y ghgrad fx eta)))))))
1,479
Common Lisp
.lisp
35
35.914286
84
0.666435
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
8b4d84f8639ed694227d62fffd9de67ed0893c8b86d07dcd937d1d1af5af0243
17,360
[ -1 ]
17,361
xgframe.lisp
jnjcc_cl-ml/trees/xgframe.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; "Data Frame" for XGBoost (in-package #:cl-ml) ;;; `ylabels' is a m x 2 matrix, with first column being first-order derivative, ;;; second column being second-order derivative (defclass xgb-frame (data-frame) ()) (defmethod get-first-order ((xframe xgb-frame) i) "i-th first-order derivative" (with-slots (ylabels sindice) xframe (let ((idx (nth i sindice))) (mref ylabels idx 0)))) (defmethod get-second-order ((xframe xgb-frame) i) (with-slots (ylabels sindice) xframe (let ((idx (nth i sindice))) (mref ylabels idx 1)))) (defun make-xgframe (X y &optional feaname) (let ((xframe (make-instance 'xgb-frame :xmatrix X :ylabels y :feaname feaname))) (with-slots (sindice findice) xframe (setf sindice (make-indices (nrow X))) (setf findice (make-indices (ncol X)))) xframe))
908
Common Lisp
.lisp
23
36.086957
83
0.684091
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
a565b5b1f5d70e9c1ee57c00b3a80a1c03819b3e5b7d846a254bc9b9ad6149df
17,361
[ -1 ]
17,362
xgcart.lisp
jnjcc_cl-ml/trees/xgcart.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; XGBoost Regression Tree Estimator (in-package #:cl-ml) (defclass xgb-regressor (dtree-regressor) ((criterion :initform :xgb))) (defmethod fit ((xgreg xgb-regressor) X &optional y) "NOTICE: y is a mx2 matrix" (unless (= (ncol y) 2) (error "xgb-regressor expect a mx2 matrix as y")) (with-slots (droot depth nfeat) xgreg (setf nfeat (ncol X)) (let ((xframe (make-xgframe X y)) (splitter (make-root-splitter xgreg X))) (setf depth (split-node splitter xframe xgreg)))))
583
Common Lisp
.lisp
15
35.266667
66
0.676106
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
7f0692f83088355b3498e8b071398e8a912f1a6a57097c32d739111a617461f4
17,362
[ -1 ]
17,363
xgloss.lisp
jnjcc_cl-ml/trees/xgloss.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; XGBoost Losses (in-package #:cl-ml) (defclass xgloss-least (gbloss-least) ()) (defmethod negative-gradient ((xgleast xgloss-least) y f) ;; second order derivative being 1 (let ((grad (make-matrix (nrow y) 2 :initial-element 1.0))) (do-vector (i y) (setf (mref grad i 0) (- (vref f i) (vref y i)))) grad)) (defmethod update-leaf-and-predict ((xgleast xgloss-least) xgreg X y residual fx eta) (let ((curpred (predict xgreg X))) (m*= curpred eta) (m+= fx curpred)) fx) ;;; make-* functions (defun make-xgloss (type) (ecase type (:xgleast (make-instance 'xgloss-least))))
688
Common Lisp
.lisp
21
29.714286
85
0.661631
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
77b2f94025424b484b416b533b330f23df60983db7b6b1b8f8ec38a9f86a3f2a
17,363
[ -1 ]
17,364
gbtree.lisp
jnjcc_cl-ml/trees/gbtree.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Gradient Boosting Trees (in-package #:cl-ml) (defclass gboost-estimator (estimator) ((estimators :initform nil :documentation "list of decision tree estimators") (nestimators :initform 20 :initarg :nestimators) (loss :initform :least :documentation "gboost loss type") (eta :initform 0.1 :initarg :eta :documentation "shrink the contribution of each tree") (max-depth :initform nil :initarg :max-depth :reader max-depth) (min-samples-split :initform 2 :initarg :min-samples-split :reader min-samples-split) (min-samples-leaf :initform 1 :initarg :min-samples-leaf :reader min-samples-leaf) (max-leaf-nodes :initform nil :initarg :max-leaf-nodes :reader max-leaf-nodes))) (defmethod predict ((gbest gboost-estimator) X) (with-slots (estimators loss eta) gbest (let ((pred (init-predict loss X))) (dolist (dtest estimators) (m+= pred (m* eta (predict dtest X)))) pred))) ;;; Gradient Boosting Tree with regression tree as base estimator (defclass gboost-tree (gboost-estimator) ()) ;;; NOTICE: all trees are regression tree (defmethod initialize-instance :after ((gbtree gboost-tree) &rest args) (declare (ignore args)) (with-slots (estimators nestimators loss) gbtree (with-slots (max-depth min-samples-split min-samples-leaf max-leaf-nodes) gbtree (dotimes (i nestimators) (push (make-instance 'dtree-regressor :max-depth max-depth :min-samples-split min-samples-split :min-samples-leaf min-samples-leaf :max-leaf-nodes max-leaf-nodes) estimators))))) ;;; Gradient Boosting Classifier (deftype gbclf-loss-type () '(member :deviance :exponential)) (defclass gboost-classifier (gboost-tree) ((loss :initform :deviance :initarg :loss :type gbclf-loss-type) (nclasses :initform 0))) (defmethod initialize-instance :after ((gbclf gboost-classifier) &rest args) (declare (ignore args)) (with-slots (loss) gbclf (setf loss (make-gbloss loss)))) (defmethod fit ((gbclf gboost-classifier) X &optional y) (with-slots (estimators loss eta nclasses) gbclf (setf nclasses (length (mbincount y))) (let ((fx (init-fit-and-predict loss y))) (dolist (dtreg estimators) (let ((residual (negative-gradient loss y fx))) (fit dtreg X residual) (setf fx (update-leaf-and-predict loss dtreg X y residual fx eta))))))) (defmethod predict-proba ((gbclf gboost-classifier) X) (with-slots (estimators loss eta) gbclf (let ((pred (init-predict loss X))) (dolist (dtest estimators) (m+= pred (m* eta (predict dtest X)))) (mmap pred #'sigmoid) pred))) (defmethod predict ((gbclf gboost-classifier) X) (let ((pred (predict-proba gbclf X))) (labels ((posfun (val) (if (> val 0.5) +1 0))) (mmap pred #'posfun)) pred)) ;;; Gradient Boosting Regressor (deftype gbreg-loss-type () '(member :least :lad :huber :quantile)) (defclass gboost-regressor (gboost-tree) ((loss :initform :least :initarg :loss :type 'gbreg-loss-type))) (defmethod initialize-instance :after ((gbreg gboost-regressor) &rest args) (declare (ignore args)) (with-slots (loss) gbreg (setf loss (make-gbloss loss)))) (defmethod fit ((gbreg gboost-regressor) X &optional y) (with-slots (estimators loss eta) gbreg (let ((fx (init-fit-and-predict loss y))) (dolist (dtreg estimators) (let ((residual (negative-gradient loss y fx))) (fit dtreg X residual) (setf fx (update-leaf-and-predict loss dtreg X y residual fx eta)))))))
3,697
Common Lisp
.lisp
80
40.675
90
0.681011
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
9c38cbc8256feb0f48ff99a38a3912c4ae3f96d2ec5bab73027fed7b2d5e3f2e
17,364
[ -1 ]
17,365
dtcrite.lisp
jnjcc_cl-ml/trees/dtcrite.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Decision Tree impurity criterion for node split (in-package #:cl-ml) (defclass criterion-base () ((sbeg :initform 0 :initarg :sbeg :documentation "the first sample to be used on this node") (send :initform nil :initarg :send) (spos :initform 0 :documentation "[`sbeg', `spos') on left; [`spos', `send') on right"))) (defgeneric init-position-and-summary (cbase dframe) (:documentation "init and summarize statistics on this node from `dframe'")) (defgeneric const-label-p (cbase dframe) (:documentation "(values const-label-p label-class)")) (defgeneric reset-position (cbase) (:documentation "reset split point at sample `sbeg' for a new feature")) (defgeneric update-position (cbase dframe newpos) (:documentation "set split point at sample `newpos' of `dframe': [sbeg, newpos)")) (defgeneric proxy-impurity-gain (cbase) (:documentation "the proxy impurity which neglects all constant terms")) (defgeneric node-impurity (cbase)) (defgeneric children-impurity (cbase dframe)) (defgeneric impurity-gain (cbase impurity dframe) (:documentation "the actual (unweighted) impurity gain when a split occurs: impurity - Dl / D * left_impurity - Dr / D * right_impurity the final weight as (D / Dtotal)")) (defgeneric node-value (cbase) (:documentation "(values label bincount) for classifier or (values pred nil) for regressor")) (defmethod impurity-gain ((cbase criterion-base) impurity dframe) (with-slots (sbeg send spos) cbase (let ((psize (- send sbeg)) (lsize (- spos sbeg)) (rsize (- send spos))) (multiple-value-bind (limp rimp) (children-impurity cbase dframe) (- impurity (* (/ lsize psize) limp) (* (/ rsize psize) rimp)))))) ;;; regressor: mean suqared error impurity criterion (defclass criterion-mse (criterion-base) ((psum :initform 0) (sqsum :initform 0) ;; squared parent sum (lsum :initform 0) (rsum :initform 0))) (defmethod const-label-p ((cmse criterion-mse) dframe) (with-slots (sbeg send) cmse (let ((label0 (get-label dframe sbeg))) (do ((i sbeg (1+ i))) ((>= i send)) (unless (float= label0 (get-label dframe i)) (return-from const-label-p (values nil nil)))) (return-from const-label-p (values t label0))))) (defmethod init-position-and-summary ((cmse criterion-mse) dframe) (with-slots (sbeg send spos psum sqsum lsum rsum) cmse (let ((cur nil)) (do ((idx sbeg (+ idx 1))) ((>= idx send)) (setf cur (get-label dframe idx)) (incf psum cur) (incf sqsum (* cur cur)))) (setf spos sbeg) (setf lsum 0) (setf rsum psum))) (defmethod reset-position ((cmse criterion-mse)) (with-slots (sbeg spos psum lsum rsum) cmse (setf spos sbeg) (setf lsum 0) (setf rsum psum))) (defmethod update-position ((cmse criterion-mse) dframe newpos) (with-slots (spos psum lsum rsum) cmse (do ((idx spos (+ idx 1))) ((>= idx newpos)) (incf lsum (get-label dframe idx))) (setf rsum (- psum lsum)) (setf spos newpos))) (defmethod proxy-impurity-gain ((cmse criterion-mse)) (with-slots (sbeg send spos lsum rsum) cmse (+ (/ (* lsum lsum) (- spos sbeg)) (/ (* rsum rsum) (- send spos))))) (defmethod node-impurity ((cmse criterion-mse)) "E[y2] - (E[y])2" (with-slots (psum sqsum sbeg send) cmse (let ((sz (- send sbeg))) (- (/ sqsum sz) (* (/ psum sz) (/ psum sz)))))) (defmethod children-impurity ((cmse criterion-mse) dframe) (with-slots (sqsum lsum rsum sbeg send spos) cmse (let ((lsqsum 0) (rsqsum 0) (lsz (- spos sbeg)) (rsz (- send spos))) (do ((idx sbeg (+ idx 1))) ((>= idx spos)) (incf lsqsum (* (get-label dframe idx) (get-label dframe idx)))) (setf rsqsum (- sqsum lsqsum)) (values (- (/ lsqsum lsz) (* (/ lsum lsz) (/ lsum lsz))) (- (/ rsqsum rsz) (* (/ rsum rsz) (/ rsum rsz))))))) (defmethod node-value ((cmse criterion-mse)) (with-slots (psum sbeg send) cmse (values (/ psum (- send sbeg)) nil))) ;;; classifier: classifier impurity criterion (defclass criterion-classifier (criterion-base) ((pbins :initform nil) (lbins :initform nil) (rbins :initform nil))) (defmethod const-label-p ((crclf criterion-classifier) dframe) (with-slots (sbeg send) crclf (let ((class0 (get-label dframe sbeg))) (do ((i sbeg (1+ i))) ((>= i send)) (unless (eq class0 (get-label dframe i)) (return-from const-label-p (values nil nil)))) (return-from const-label-p (values t class0))))) (defmethod init-position-and-summary ((crclf criterion-classifier) dframe) (with-slots (sbeg send spos pbins lbins rbins) crclf (setf pbins (count-label dframe sbeg send)) (setf spos sbeg) (setf lbins nil) (setf rbins (copy-tree pbins)))) (defmethod reset-position ((crclf criterion-classifier)) (with-slots (sbeg spos pbins lbins rbins) crclf (setf spos sbeg) (setf lbins nil) (setf rbins (copy-tree pbins)))) (defmethod update-position ((crclf criterion-classifier) dframe newpos) (with-slots (spos lbins rbins) crclf (let ((cur nil)) (do ((idx spos (+ idx 1))) ((>= idx newpos)) (setf cur (get-label dframe idx)) (binincf lbins cur) (bindecf rbins cur))) (setf spos newpos))) (defmethod node-value ((crclf criterion-classifier)) (with-slots (pbins) crclf (values (argmax pbins) pbins))) ;;; entropy impurity criterion (defclass criterion-entropy (criterion-classifier) ()) (defmethod proxy-impurity-gain ((crent criterion-entropy)) (with-slots (sbeg send spos lbins rbins) crent (let* ((lsize (- spos sbeg)) (rsize (- send spos)) (lprob (probability lbins lsize)) (rprob (probability rbins rsize))) (+ (- (* lsize (entropy-list lprob))) (- (* rsize (entropy-list rprob))))))) (defmethod node-impurity ((crent criterion-entropy)) (with-slots (sbeg send pbins) crent (entropy-list (probability pbins (- send sbeg))))) (defmethod children-impurity ((crent criterion-entropy) dframe) (declare (ignore dframe)) (with-slots (sbeg send spos lbins rbins) crent (let* ((lsize (- spos sbeg)) (rsize (- send spos)) (lprob (probability lbins lsize)) (rprob (probability rbins rsize))) (values (entropy-list lprob) (entropy-list rprob))))) ;;; gini impurity criterion (defclass criterion-gini (criterion-classifier) ()) (defmethod proxy-impurity-gain ((cgini criterion-gini)) (with-slots (sbeg send spos lbins rbins) cgini (let* ((lsize (- spos sbeg)) (rsize (- send spos)) (lprob (probability lbins lsize)) (rprob (probability rbins rsize))) (+ (- (* lsize (gini-list lprob))) (- (* rsize (gini-list rprob))))))) (defmethod node-impurity ((cgini criterion-gini)) (with-slots (sbeg send pbins) cgini (gini-list (probability pbins (- send sbeg))))) (defmethod children-impurity ((cgini criterion-gini) dframe) (declare (ignore dframe)) (with-slots (sbeg send spos lbins rbins) cgini (let* ((lsize (- spos sbeg)) (rsize (- send spos)) (lprob (probability lbins lsize)) (rprob (probability rbins rsize))) (values (gini-list lprob) (gini-list rprob)))))
7,432
Common Lisp
.lisp
177
36.79096
84
0.651079
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
9b587a18161b17f78859cf00eab5310bfbc9f40fecd833d10f1cc1f59cb981a8
17,365
[ -1 ]
17,366
dtree.lisp
jnjcc_cl-ml/trees/dtree.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Decision Tree Estimator ;;;; TODO: multiclass support; algorithm optimization (in-package #:cl-ml) ;;; Decision Tree ;; Decision Tree: node data (payload of the Binary Tree data structure) (defclass dtree-node-data () ((feature :initform nil :initarg :feature :reader feature :documentation "feature index, if NIL, then leaf") (threshold :initform nil :initarg :threshold :reader threshold :documentation "feature threshold") (value :initform 0.0 :initarg :value :reader value) ;; frequency of each label in classifier (binfreqs :initform nil :initarg :binfreqs :reader binfreqs) (impurity :initform 0.0 :initarg :impurity :reader impurity :documentation "node impurity, or MSE in regression tasks") (nsamples :initform 0 :initarg :nsamples :reader nsamples :documentation "number of samples in this node"))) (defmethod print-object ((ddata dtree-node-data) stream) (with-slots (feature threshold value nsamples) ddata (if feature (format stream "~A <= ~A (~A)" feature threshold nsamples) (format stream "leaf: ~A (~A)" value nsamples)))) (defmethod print-verbose ((ddata dtree-node-data) &optional (stream t) (feafun #'identity) (labelfun #'identity)) (with-slots (feature threshold value nsamples) ddata (if feature (format stream "~A <= ~A (~A)" (funcall feafun feature) threshold nsamples) (format stream "leaf: ~A (~A)" (funcall labelfun value) nsamples)))) ;; Decision Tree: Binary Tree with dtree-node-data payload (defun set-dtree-data (root &key feature threshold impurity nsamples value binfreqs) (let ((data (make-instance 'dtree-node-data :feature feature :threshold threshold :impurity impurity :nsamples nsamples :value value :binfreqs binfreqs))) (set-tree-data root data))) (defun update-dtree-data-value (root newval) (let ((data (get-tree-data root))) (with-slots (value) data (setf value newval)))) (defun get-dtree-child (root X i) "(values leaf-tree node-data) OR (values child-tree nil)" (let ((node-data (get-tree-data root))) (with-slots (feature threshold) node-data (if (null feature) (values root node-data) (let ((fval (mref X i feature))) (if (<= fval threshold) (values (get-left-tree root) nil) (values (get-right-tree root) nil))))))) (defun print-dtree-depth (root depth &optional (stream t) (feafun #'identity) (labelfun #'identity)) (when root (format stream "~A" (repeat-string "| " depth)) (print-verbose (get-tree-data root) stream feafun labelfun) (format stream "~%") (print-dtree-depth (get-left-tree root) (+ depth 1) stream feafun labelfun) (print-dtree-depth (get-right-tree root) (+ depth 1) stream feafun labelfun))) ;;; Decision Tree Estimator (deftype criterion-type () '(member :gini :entropy :gain-ratio :mse)) ;; for Random Forest (deftype rand-feature-type () '(member :all :log2 :sqrt)) ;;; TODO: max-leaf-nodes (defclass dtree-estimator (estimator) ((droot :initform nil :reader droot :documentation "decision tree root node") (depth :initform 0 :reader depth) (nfeat :initform nil) (vimps :initform nil) (max-depth :initform nil :initarg :max-depth :reader max-depth) (min-samples-split :initform 2 :initarg :min-samples-split :reader min-samples-split :documentation "minimum number of samples a node must have before it can split") (min-samples-leaf :initform 1 :initarg :min-samples-leaf :reader min-samples-leaf :documentation "minimum number of samples a leaf node must have") (max-leaf-nodes :initform nil :initarg :max-leaf-nodes :reader max-leaf-nodes :documentation "maximum number of leaf nodes: best-first-splitter") (max-features :initform :all :initarg :max-features :type rand-feature-type :documentation "feature selection for Random Forest") (criterion :initform :gini :type criterion-type))) (defmethod print-object ((dtree-est dtree-estimator) stream) (with-slots (droot) dtree-est (print-dtree-depth droot 0 stream))) ;;; Decision Tree Splitter (defclass dtree-splitter () ((dnode :initform nil :initarg :dnode :documentation "decision tree node") (criterion :initform nil :initarg :criterion) (crite-obj :initform nil :initarg :crite-obj :documentation "the `criterion-base' object") (rf-maxfeats :initform -1 :initarg :rf-maxfeats :documentation "maximum number of features to consider, for Random Forest") (depth :initform 1 :initarg :depth) (sbeg :initform 0 :initarg :sbeg :documentation "begin of sample index, indirect access") (send :initform nil :initarg :send) (fbeg :initform 0 :initarg :fbeg :documentation "begin of (non-constant) feature index, indirect access") (fend :initform nil :initarg :fend))) (defun %get-max-feature (rand-feature n) (ecase rand-feature (:all n) ;; -1 means all the features (:log2 (log2 n)) (:sqrt (sqrt n)))) (defun make-root-splitter (dtree-est X) "make the root splitter for dtree-estimator on training set X" (with-slots (droot criterion max-features) dtree-est (setf droot (make-binary-tree nil)) (make-instance 'dtree-splitter :dnode droot :depth 1 :criterion criterion :crite-obj (make-criterion criterion 0 (nrow X)) :rf-maxfeats (%get-max-feature max-features (ncol X)) :sbeg 0 :send (nrow X) :fbeg 0 :fend (ncol X)))) (defun make-left-splitter (splitter smid) "generate the left child [sbeg, smid) and make the corresponding splitter" (with-slots (dnode criterion rf-maxfeats depth sbeg fbeg fend) splitter (set-left-tree dnode (make-binary-tree nil)) (make-instance 'dtree-splitter :dnode (get-left-tree dnode) :depth (+ depth 1) :criterion criterion :crite-obj (make-criterion criterion sbeg smid) :rf-maxfeats rf-maxfeats :sbeg sbeg :send smid :fbeg fbeg :fend fend))) (defun make-right-splitter (splitter smid) "generate the right child [smid, send) and make the corresponding splitter" (with-slots (dnode criterion rf-maxfeats depth send fbeg fend) splitter (set-right-tree dnode (make-binary-tree nil)) (make-instance 'dtree-splitter :dnode (get-right-tree dnode) :depth (+ depth 1) :criterion criterion :crite-obj (make-criterion criterion smid send) :rf-maxfeats rf-maxfeats :sbeg smid :send send :fbeg fbeg :fend fend))) (defmethod shrink-feature ((splitter dtree-splitter) dframe j) (with-slots (fend) splitter (swap-feature dframe j (- fend 1)) (decf fend 1))) (defun %feature-equal (dframe fidx i j) (float= (get-feature-value dframe i fidx) (get-feature-value dframe j fidx))) (defmethod choose-feature ((splitter dtree-splitter) dframe) (with-slots (crite-obj rf-maxfeats sbeg send fbeg fend depth) splitter (let ((bfidx nil) ;; best feature idx (bsidx nil) ;; best sample split point [`sbeg', `bsidx') (bgain nil) ;; best gain (bthrh nil) ;; best threshold (rf-fend fend)) ;; feature end for Random Forest (when (< 0 rf-maxfeats (- fend fbeg)) (shuffle-feature dframe fbeg fend) ;; `rf-maxfeats' features to consider for Random Forest (setf rf-fend (+ fbeg rf-maxfeats))) (do ((fidx fbeg (1+ fidx))) ((>= fidx rf-fend)) (reset-position crite-obj) (sort-frame dframe fidx sbeg send) (if (%feature-equal dframe fidx sbeg (- send 1)) (shrink-feature splitter dframe fidx) (do ((sidx sbeg (1+ sidx))) ((>= sidx (- send 1))) (unless (%feature-equal dframe fidx sidx (+ sidx 1)) (update-position crite-obj dframe (+ sidx 1)) (let ((gain (proxy-impurity-gain crite-obj))) (when (or (null bgain) (< bgain gain)) (setf bgain gain) (setf bfidx fidx) ;; `bsidx' belongs to the right child (setf bsidx (+ sidx 1)) (setf bthrh (/ (+ (get-feature-value dframe sidx fidx) (get-feature-value dframe (+ sidx 1) fidx)) 2.0)))))))) (when bfidx ;; found a good split feature, reorder data frame again! (sort-frame dframe bfidx sbeg send)) (values bfidx bsidx bthrh bgain)))) (defmethod fill-dtree-data ((splitter dtree-splitter) dframe &key feature threshold) "(feature & threshold) OR leaf node" (with-slots (dnode sbeg send crite-obj) splitter (multiple-value-bind (value binfreqs) (node-value crite-obj) (if feature (set-dtree-data dnode :feature feature :threshold threshold :nsamples (- send sbeg) :impurity (node-impurity crite-obj)) (set-dtree-data dnode :value value :binfreqs binfreqs :nsamples (- send sbeg) :impurity (node-impurity crite-obj)))))) (defmethod fill-dtree-const ((splitter dtree-splitter) dframe value) "special case of fill-dtree-data: all label is same" (with-slots (dnode sbeg send crite-obj) splitter (let ((nsamples (- send sbeg))) (set-dtree-data dnode :value value :binfreqs (list (cons value nsamples)) :nsamples nsamples :impurity (node-impurity crite-obj))))) (defmethod split-node ((splitter dtree-splitter) dframe dtree-est) (with-slots (dnode depth sbeg send fbeg fend crite-obj) splitter (init-position-and-summary crite-obj dframe) ;; MAX-DEPTH, MIN-SAMPLES-SPLIT (when (or (and (max-depth dtree-est) (>= depth (max-depth dtree-est))) (and (min-samples-split dtree-est) (< (- send sbeg) (min-samples-split dtree-est)))) (fill-dtree-data splitter dframe) (return-from split-node depth)) ;; all sample belongs to the same class (multiple-value-bind (same-label label0) (const-label-p crite-obj dframe) (when same-label (fill-dtree-const splitter dframe label0) (return-from split-node depth))) ;; all feature is constant (when (>= fbeg fend) (fill-dtree-data splitter dframe) (return-from split-node depth)) ;; best feature, best split point, best threshold (multiple-value-bind (bfidx bsidx bthrh) (choose-feature splitter dframe) (when bfidx ;; if found a best split (when (and (min-samples-leaf dtree-est) (or (< (- bsidx sbeg) (min-samples-leaf dtree-est)) (< (- send bsidx) (min-samples-leaf dtree-est)))) (fill-dtree-data splitter dframe) (return-from split-node depth)) (fill-dtree-data splitter dframe :feature (get-feature-name dframe bfidx) :threshold bthrh) (let (ldepth rdepth) ;; generate the left child and continue splitting (setf ldepth (split-node (make-left-splitter splitter bsidx) dframe dtree-est)) (setf rdepth (split-node (make-right-splitter splitter bsidx) dframe dtree-est)) (return-from split-node (max ldepth rdepth)))) (unless bfidx ;; if not found a best split (fill-dtree-data splitter dframe) (return-from split-node depth)))))
11,667
Common Lisp
.lisp
219
44.639269
98
0.647141
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
8f443efffa824e113cfdd83455cca9ed965079821fcad50c136294e9caba6384
17,366
[ -1 ]
17,367
xgcrite.lisp
jnjcc_cl-ml/trees/xgcrite.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; XGBoost Decision Tree impurity criterion for node split (in-package #:cl-ml) (defclass criterion-xgb (criterion-base) ;; `gamma' * J + 1/2 * `lambd' * sum(c^{2}) ((gamma :initform 0 :initarg :gamma) (lambd :initform 1 :initarg :lambd) (pgsum :initform 0) ;; sum of first-order derivative, for parent (phsum :initform 0) (lgsum :initform 0) (lhsum :initform 0) ;; sum of second-order derivative, for left child (rgsum :initform 0) (rhsum :initform 0))) (defmethod init-position-and-summary ((cxgb criterion-xgb) xframe) (with-slots (sbeg send spos pgsum phsum lgsum lhsum rgsum rhsum) cxgb (do ((idx sbeg (1+ idx))) ((>= idx send)) (incf pgsum (get-first-order xframe idx)) (incf phsum (get-second-order xframe idx))) (setf spos sbeg) (setf lgsum 0) (setf lhsum 0) (setf rgsum pgsum) (setf rhsum phsum))) (defmethod const-label-p ((cxgb criterion-xgb) xframe) "`xframe' is type of xgb-frame" (with-slots (sbeg send gamma lambd pgsum phsum) cxgb (let ((g0 (get-first-order xframe sbeg)) (h0 (get-second-order xframe sbeg))) (do ((idx sbeg (1+ idx))) ((>= idx send)) (unless (and (float= g0 (get-first-order xframe idx)) (float= h0 (get-second-order xframe idx))) (return-from const-label-p (values nil nil)))) ;; c* = -G / (H + lambda) (return-from const-label-p (values t (- (/ pgsum (+ phsum lambd)))))))) (defmethod reset-position ((cxgb criterion-xgb)) (with-slots (sbeg spos pgsum phsum lgsum lhsum rgsum rhsum) cxgb (setf spos sbeg) (setf lgsum 0) (setf lhsum 0) (setf rgsum pgsum) (setf rhsum phsum))) (defmethod update-position ((cxgb criterion-xgb) xframe newpos) (with-slots (spos pgsum phsum lgsum lhsum rgsum rhsum) cxgb (do ((idx spos (1+ idx))) ((>= idx newpos)) (incf lgsum (get-first-order xframe idx)) (incf lhsum (get-second-order xframe idx))) (setf rgsum (- pgsum lgsum)) (setf rhsum (- phsum lhsum)) (setf spos newpos))) (defmethod proxy-impurity-gain ((cxgb criterion-xgb)) (with-slots (lgsum lhsum rgsum rhsum lambd) cxgb ;; Gl^{2} / (Hl + lambda) + Gr^{2} / (Hr + lambda) (+ (/ (* lgsum lgsum) (+ lhsum lambd)) (/ (* rgsum rgsum) (+ rhsum lambd))))) (defmethod node-impurity ((cxgb criterion-xgb)) (with-slots (pgsum phsum lambd) cxgb ;; G^{2} / (H + lambd) (/ (* pgsum pgsum) (+ phsum lambd)))) (defmethod children-impurity ((cxgb criterion-xgb) xframe) (declare (ignore xframe)) (with-slots (lgsum lhsum rgsum rhsum lambd) cxgb (values (/ (* lgsum lgsum) (+ lhsum lambd)) (/ (* rgsum rgsum) (+ rhsum lambd))))) (defmethod impurity-gain ((cxgb criterion-xgb) impurity xframe) (with-slots (gamma) cxgb (multiple-value-bind (limp rimp) (children-impurity cxgb xframe) (- (* 1/2 (+ limp rimp (- impurity))) gamma)))) (defmethod node-value ((cxgb criterion-xgb)) (with-slots (pgsum phsum lambd) cxgb (- (/ pgsum (+ phsum lambd))))) ;;; make-* functions (defun make-criterion (type sbeg send &optional (gamma 0) (lambd 1)) (ecase type (:gini (make-instance 'criterion-gini :sbeg sbeg :send send)) (:entropy (make-instance 'criterion-entropy :sbeg sbeg :send send)) (:mse (make-instance 'criterion-mse :sbeg sbeg :send send)) (:xgb (make-instance 'criterion-xgb :sbeg sbeg :send send :gamma gamma :lambd lambd))))
3,528
Common Lisp
.lisp
82
38.121951
91
0.644438
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
2e6e60bfd74af658d73c2f73106e124bec2b4a24056ce63ca2745ce213c2cb6f
17,367
[ -1 ]
17,368
gbloss.lisp
jnjcc_cl-ml/trees/gbloss.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Gradient Boosting Lossess (in-package #:cl-ml) (deftype gbloss-type () ;; squared loss, exp '(member :square :exp)) (defclass gbloss-base () ;; gradient boosting loss function ((init-estimator :initform nil :documentation "initial estimator to predict X"))) (defgeneric init-fit-and-predict (gbase y) (:documentation "initial \hat{y} to minimize loss function")) (defgeneric init-predict (gbase X)) (defgeneric negative-gradient (gbase y f) (:documentation "`y' as the original label; `f' as the additive model by this stage")) (defgeneric update-leaf-and-predict (gbase dtreg X y residual fx eta) (:documentation "update leaf region, and update the additive model `fx'")) ;;; Least Squares Error (defclass gbloss-least (gbloss-base) ()) (defmethod init-fit-and-predict ((gbleast gbloss-least) y) (with-slots (init-estimator) gbleast (setf init-estimator (mmean y :axis nil)) (make-vector (nrow y) :initial-element init-estimator))) (defmethod init-predict ((gbleast gbloss-least) X) (with-slots (init-estimator) gbleast (make-vector (nrow X) :initial-element init-estimator))) (defmethod negative-gradient ((gbleast gbloss-least) y f) (m- y f)) (defmethod update-leaf-and-predict ((gbleast gbloss-least) dtreg X y residual fx eta) "Least Squares Error does not need to update leaf values" (let ((curpred (predict dtreg X))) (m*= curpred eta) (m+= fx curpred)) fx) ;;; Least Absolute Deviation (defclass gbloss-lad (gbloss-base) ()) (defmethod init-fit-and-predict ((gblad gbloss-lad) y) (with-slots (init-estimator) gblad (setf init-estimator (mquantile y 0.5)) (make-vector (nrow y) :initial-element init-estimator))) (defmethod init-predict ((gblad gbloss-lad) X) (with-slots (init-estimator) gblad (make-vector (nrow X) :initial-element init-estimator))) (defmethod negative-gradient ((gblad gbloss-lad) y f) (let ((grad (make-vector (nrow y) :initial-element 1.0))) (do-vector (i y) (when (<= (vref y i) (vref f i)) (setf (vref grad i) -1.0))) grad)) (defmethod update-leaf-and-predict ((gblad gbloss-lad) dtreg X y residual fx eta) (let ((leaf-regs (leaf-regions dtreg X)) (yv (make-matrix-view y)) (fxv (make-matrix-view fx)) cur-leaf newval) (dolist (pair leaf-regs) (setf cur-leaf (car pair)) (update-matrix-view yv :row-view (cdr pair)) (update-matrix-view fxv :row-view (cdr pair)) (setf newval (mquantile (m- yv fxv) 0.5)) (update-dtree-data-value cur-leaf newval) (m+= fxv (* newval eta)))) fx) ;;; Huber Loss (defclass gbloss-huber (gbloss-base) ((alpha :initform 0.9 :initarg :alpha :documentation "quantile at which to extract score") (delta :initform nil))) (defmethod init-fit-and-predict ((ghuber gbloss-huber) y) (with-slots (init-estimator) ghuber (setf init-estimator (mquantile y 0.5)) (make-vector (nrow y) :initial-element init-estimator))) (defmethod init-predict ((ghuber gbloss-huber) X) (with-slots (init-estimator) ghuber (make-vector (nrow X) :initial-element init-estimator))) (defmethod negative-gradient ((ghuber gbloss-huber) y f) (let ((diff (make-vector (nrow y)))) ;; diff = |y - f| (do-vector (i y) (if (>= (vref y i) (vref f i)) (setf (vref diff i) (- (vref y i) (vref f i))) (setf (vref diff i) (- (vref f i) (vref y i))))) (with-slots (alpha delta) ghuber (setf delta (mquantile diff alpha)) (do-vector (i diff) (if (<= (vref diff i) delta) (setf (vref diff i) (- (vref y i) (vref f i))) (setf (vref diff i) (* delta (signfn (vref diff i))))))) diff)) (defmethod update-leaf-and-predict ((ghuber gbloss-huber) dtreg X y residual fx eta) (error "TODO to implement...")) ;;; Binomial deviance (defclass gbloss-binom (gbloss-base) ()) (defmethod init-fit-and-predict ((gbinom gbloss-binom) y) (with-slots (init-estimator) gbinom (let* ((class-probs (density (mbincount y))) (class1 (binvalue class-probs 1))) (setf init-estimator (log (/ class1 (- 1 class1)))) (make-vector (nrow y) :initial-element init-estimator)))) (defmethod init-predict ((gbinom gbloss-binom) X) (with-slots (init-estimator) gbinom (make-vector (nrow X) :initial-element init-estimator))) (defmethod negative-gradient ((gbinom gbloss-binom) y f) (mmap f #'sigmoid) (m- y f)) (defmethod update-leaf-and-predict ((gbinom gbloss-binom) dtreg X y residual fx eta) (let ((leaf-regs (leaf-regions dtreg X)) (yv (make-matrix-view y)) (fxv (make-matrix-view fx)) (rv (make-matrix-view residual)) cur-leaf newval) (dolist (pair leaf-regs) (setf cur-leaf (car pair)) (update-matrix-view yv :row-view (cdr pair)) (update-matrix-view rv :row-view (cdr pair)) (update-matrix-view fxv :row-view (cdr pair)) (setf newval 0.0) ;; (y - residual) * (1 - y + residual) (do-vector (i yv) (incf newval (* (- (vref yv i) (vref rv i)) (+ 1 (- (vref yv i)) (vref rv i))))) (unless (float= newval 0.0) (setf newval (/ (msum rv) newval))) (update-dtree-data-value cur-leaf newval) (m+= fxv (* newval eta)))) fx) ;;; make-* functions (defun make-gbloss (type &optional (alpha 0.9)) (ecase type (:least (make-instance 'gbloss-least)) (:lad (make-instance 'gbloss-lad)) (:huber (make-instance 'gbloss-huber :alpha alpha)) (:deviance (make-instance 'gbloss-binom))))
5,621
Common Lisp
.lisp
134
37.253731
92
0.659524
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
34f43d429e3b18abed31152af8d3ad7b247148a3a93568d14ed629e36dc57139
17,368
[ -1 ]
17,369
sim-base.lisp
jnjcc_cl-ml/graph/sim-base.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Graph base class (in-package #:cl-ml/graph) (defclass graph-base () ((node-eq :initform #'equal :initarg :node-eq :reader node-eq) (node-le :initform #'<= :initarg :node-le) ;; edges using hash-table of hash-table's (edge-hash :initform nil :reader edge-hash) (edge-nums :initform 0) ;; nodes using hash-table, used to hold attribute of node's (node-hash :initform nil :reader node-hash))) (defmethod initialize-instance :after ((graph graph-base) &rest args) (declare (ignore args)) (with-slots (node-eq edge-hash node-hash) graph (setf edge-hash (make-hash-table :test node-eq)) (setf node-hash (make-hash-table :test node-eq)))) (defmethod graph-type ((graph graph-base)) (error "not implemented in base class")) (defmethod node-count ((graph graph-base)) (with-slots (node-hash) graph (hash-table-count node-hash))) (defmethod edge-count ((graph graph-base)) (with-slots (edge-nums) graph edge-nums)) (defmethod same-node ((graph graph-base) unode vnode) (with-slots (node-eq) graph (funcall node-eq unode vnode))) (defmethod print-object ((graph graph-base) stream) (format stream "~A with ~A nodes and ~A edges" (type-of graph) (node-count graph) (edge-count graph))) ;; TODO: this macro cannot do (RETURN) right (defmacro do-graph-nodes ((node value graph) &body body) `(loop with ,value = nil for ,node being the hash-keys of (node-hash ,graph) do (progn (setf ,value (gethash ,node (node-hash ,graph))) ,@body))) ;; TODO: this macro cannot do (RETURN) right (defmacro do-graph-edges ((unode vnode weight graph) &body body) (let ((hash-sym (gensym "HASH-")) (neigh-sym (gensym "NEIGHBOR-"))) `(loop with ,hash-sym = (edge-hash ,graph) with ,weight = nil for ,unode being the hash-keys of ,hash-sym for ,neigh-sym being the hash-values of ,hash-sym do (loop for ,vnode being the hash-keys of ,neigh-sym do (progn (setf ,weight (gethash ,vnode ,neigh-sym)) ,@body))))) (defmethod get-nodes ((graph graph-base) &key (valued t)) (let ((nodes nil)) (do-graph-nodes (node value graph) (if valued (push (list node value) nodes) (push node nodes))) nodes)) (defmethod get-edges ((graph graph-base) &key (weighted t)) (let ((edges nil)) (do-graph-edges (unode vnode weight graph) (if weighted (push (list unode vnode weight) edges) (push (list unode vnode) edges))) edges)) (defun %hash-contains (htable key) (nth-value 1 (gethash key htable))) (defmethod has-node ((graph graph-base) node) (with-slots (node-hash) graph (%hash-contains node-hash node))) (defmethod get-node-value ((graph graph-base) node) (with-slots (node-hash) graph (gethash node node-hash))) (defmethod has-edge ((graph graph-base) unode vnode) (with-slots (edge-hash) graph (multiple-value-bind (neighbors exists-p) (gethash unode edge-hash) (when exists-p (%hash-contains neighbors vnode))))) (defmethod get-edge-weight ((graph graph-base) unode vnode) (with-slots (edge-hash) graph (gethash vnode (gethash unode edge-hash)))) (defmethod gref ((graph graph-base) unode vnode) "counterpart of `mref'" (with-slots (edge-hash) graph (gethash vnode (gethash unode edge-hash)))) (defmethod has-neighbors ((graph graph-base) node) (with-slots (edge-hash) graph (multiple-value-bind (neighbors exists-p) (gethash node edge-hash) (when exists-p (> (hash-table-count neighbors) 0))))) (defmethod get-neighbors ((graph graph-base) node &key (weighted t)) "list of list: ((neighbor weight) ...) if `weighted'" (with-slots (edge-hash) graph (let ((nbr-lst nil)) (labels ((collect (nbr weight) (if weighted (push (list nbr weight) nbr-lst) (push nbr nbr-lst)))) (multiple-value-bind (neighbors exists-p) (gethash node edge-hash) (when exists-p (maphash #'collect neighbors)))) nbr-lst))) (defmethod sorted-neighbors ((graph graph-base) node &key (weighted t)) "sorted list of list: ((neighbor weight) ...) if `weighted'" (with-slots (node-le) graph (let ((neighbors (get-neighbors graph node :weighted weighted))) (if weighted (sort neighbors node-le :key #'car) (sort neighbors node-le))))) (defmethod add-node-safe ((graph graph-base) node value) "Requires: `node' not in `graph' yet" (error "not implemented in base class")) ;;; TODO: should we update value if node exists? (defmethod add-node ((graph graph-base) node &optional (value t)) "add `node' to `graph', if already exists, do nothing" (with-slots (node-eq edge-hash node-hash) graph (unless (has-node graph node) (add-node-safe graph node value)))) (defmethod add-edge-safe ((graph graph-base) unode vnode weight) "Requires: `edge' not in `graph' yet" (error "not implemented in base class")) ;;; TODO: should we udpate weight if edge exists? (defmethod add-edge ((graph graph-base) unode vnode &optional (weight 1)) "add `edge' to `graph', if already exists, do nothing" (unless (has-node graph unode) (add-node graph unode)) (unless (has-node graph vnode) (add-node graph vnode)) (unless (has-edge graph unode vnode) (add-edge-safe graph unode vnode weight))) (defmethod remove-edge-safe ((graph graph-base) unode vnode) "Requires: `edge' already in `graph'" (error "not implemented in base class")) (defmethod remove-edge ((graph graph-base) unode vnode) (when (has-edge graph unode vnode) (remove-edge-safe graph unode vnode))) (defmethod remove-node ((graph graph-base) node) (with-slots (edge-hash node-hash) graph (when (has-node graph node) (remhash node node-hash) (let ((neighbors (gethash node edge-hash))) (maphash (lambda (vnode weight) (declare (ignore weight)) (remove-edge-safe graph vnode node)) neighbors)))))
6,162
Common Lisp
.lisp
143
37.657343
74
0.663495
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
5367c24e3cfb0582358f85b05b45b1bfed836d2e8cfceb985314b4422617e84e
17,369
[ -1 ]
17,370
sim-graph.lisp
jnjcc_cl-ml/graph/sim-graph.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Undirected Graph and Directed Graph (in-package #:cl-ml/graph) ;;; Undirected Graph (defclass ungraph (graph-base) ()) (defmethod graph-type ((graph ungraph)) :undirected) (defmethod add-node-safe ((graph ungraph) node value) (with-slots (node-eq edge-hash node-hash) graph (setf (gethash node node-hash) value) (setf (gethash node edge-hash) (make-hash-table :test node-eq)))) (defmethod add-edge-safe ((graph ungraph) unode vnode weight) (with-slots (edge-nums edge-hash) graph (incf edge-nums) (setf (gethash vnode (gethash unode edge-hash)) weight) (setf (gethash unode (gethash vnode edge-hash)) weight))) (defmethod remove-edge-safe ((graph ungraph) unode vnode) (with-slots (edge-nums edge-hash) graph (decf edge-nums) (remhash vnode (gethash unode edge-hash)) (remhash unode (gethash vnode edge-hash)))) ;;; Directed Graph (defclass digraph (graph-base) ;; previous node of directed edge ((prev-hash :initform nil :reader prev-hash))) (defmethod graph-type ((graph digraph)) :directed) (defmethod initialize-instance :after ((graph digraph) &rest args) (declare (ignore args)) (with-slots (node-eq prev-hash) graph (setf prev-hash (make-hash-table :test node-eq)))) (defmethod has-in-neighbors ((graph digraph) node) "(pnode -> node) edges" (with-slots (prev-hash) graph (multiple-value-bind (in-neighbors exists-p) (gethash node prev-hash) (when exists-p (> (hash-table-count in-neighbors) 0))))) (defmethod get-in-neighbors ((graph digraph) node &key (weighted nil)) "for (pnode -> node) edges, return list of pnode's" (with-slots (prev-hash) graph (let ((in-lst nil)) (labels ((collect (prev weight) (if weighted (push (list prev weight) nbr-lst) (push prev in-lst)))) (multiple-value-bind (in-neighbors exists-p) (gethash node prev-hash) (when exists-p (maphash #'collect in-neighbors)))) in-lst))) (defmethod add-node-safe ((graph digraph) node value) (with-slots (node-eq edge-hash node-hash prev-hash) graph (setf (gethash node node-hash) value) (setf (gethash node edge-hash) (make-hash-table :test node-eq)) (setf (gethash node prev-hash) (make-hash-table :test node-eq)))) (defmethod add-edge-safe ((graph digraph) unode vnode weight) (with-slots (edge-nums edge-hash prev-hash) graph (incf edge-nums) (setf (gethash vnode (gethash unode edge-hash)) weight) (setf (gethash unode (gethash vnode prev-hash)) weight))) (defmethod remove-edge-safe ((graph digraph) unode vnode) (with-slots (edge-nums edge-hash prev-hash) graph (decf edge-nums) (remhash vnode (gethash unode edge-hash)) (remhash unode (gethash vnode prev-hash)))) ;;; make-* functions (defun make-graph (&optional (type :undirected) (node-eq #'equal)) (ecase type (:undirected (make-instance 'ungraph :node-eq node-eq)) (:directed (make-instance 'digraph :node-eq node-eq)))) (defun make-ungraph (&optional (node-eq #'equal)) (make-instance 'ungraph :node-eq node-eq)) (defun make-digraph (&optional (node-eq #'equal)) (make-instance 'digraph :ndoe-eq node-eq)) (defun copy-graph (graph) (let ((copy (make-instance (type-of graph)))) (do-graph-edges (unode vnode weight graph) (add-edge copy unode vnode weight)) copy))
3,455
Common Lisp
.lisp
80
38.725
77
0.687817
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
d927fa886ab4a0ba2c8170da99c404fdb6ef9456f5081879de465f3131a25a9d
17,370
[ -1 ]
17,371
packages.lisp
jnjcc_cl-ml/graph/packages.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Simple Graph (in-package #:cl-user) (defpackage #:cl-ml/graph (:nicknames #:ml/graph) (:use #:cl #:cl-ml/probs) (:export #:ungraph #:digraph #:graph-type #:same-node #:make-graph #:copy-graph #:node-count #:edge-count #:do-graph-nodes #:do-graph-edges #:get-nodes #:get-edges #:has-node #:get-node-value #:has-edge #:get-edge-weight #:gref #:has-neighbors #:get-neighbors #:sorted-neighbors #:add-node #:add-edge #:remove-node #:remove-edge ))
639
Common Lisp
.lisp
18
27.944444
74
0.567044
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
40778c35e5f49d5aa37e783de70241e896d92ce66bab5db2b3db0cedc05d4818
17,371
[ -1 ]
17,372
losses.lisp
jnjcc_cl-ml/neural/losses.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Neural Network > Loss functions (in-package #:cl-ml) ;;; Cross Entropy for binary classifier (defun cross-entropy-gradient (A y) "broadcasting y accros columns of A: A - y" (do-matrix (i j A) (decf (mref A i j) (vref y i))) A) ;;; Square Error for Regression
349
Common Lisp
.lisp
11
29.545455
66
0.680597
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
01e2c4396868f22ce222bbac3150a54edf120dc51394fe80916114916df728f8
17,372
[ -1 ]
17,373
activations.lisp
jnjcc_cl-ml/neural/activations.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Neural Network > Activation Functions (in-package #:cl-ml) (deftype activation-type () '(member :sigmoid :relu)) (defclass activation-base () ()) (defgeneric activate-matrix (act X) (:documentation "call activation on X")) (defgeneric activate-gradient-matrix (act A) (:documentation "first-order derivative on A")) ;;; Sigmoid Activation (defclass activation-sigmoid (activation-base) ()) (defmethod activate-matrix ((sigmoid activation-sigmoid) X) (mmap X #'sigmoid) X) (defmethod activate-gradient-matrix ((sigmoid activation-sigmoid) A) (labels ((gradsig (z) (let ((sig (sigmoid z))) (* sig (- 1 sig))))) (mmap A #'gradsig)) A) ;;; ReLu (defclass activation-relu (activation-base) ()) (defmethod activate-matrix ((relu activation-relu) X) (labels ((relufn (z) (if (> z 0) z 0))) (mmap X #'relufn)) X) (defmethod activate-gradient-matrix ((relu activation-relu) A) (labels ((gradrelu (z) (if (> z 0) 1 0))) (mmap A #'gradrelu)) A) ;;; Softmax (defclass activation-softmax (activation-base) ()) (defun softmax-on-matrix (mA) (do-matrix-row (i mA) (softmax-on-vector (mrv mA i))) mA) ;;; make-* functions (defun make-activation (type &optional args) (ecase type (:sigmoid (make-instance 'activation-sigmoid)) (:relu (make-instance 'activation-relu))))
1,458
Common Lisp
.lisp
49
26.142857
68
0.66595
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
a80856402d0ab77be8e452f343d81378b4d746bd93a9b6f184cbbf2f396953c9
17,373
[ -1 ]
17,374
mlp.lisp
jnjcc_cl-ml/neural/mlp.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Neural Network > Network architecture > Multilayer perceptron (in-package #:cl-ml) ;;; tf.contrib.learn.DNNClassifier (defclass multilayer-perceptron (estimator) ((hidden-units :initform '(16) :initarg :hidden-units :type list :documentation "list of number of units per hidden layer, with length being (nlayers - 2): excluding input layer and output layer") (layer-nums :initform nil :reader layer-nums) (activation :initform :relu :initarg :activation :documentation "activation function") (optimizer :initform :sgd :initarg :optimizer :documentation "optimizer") (batch-size :initform 32 :initarg :batch-size) (epochs :initform 200 :initarg :epochs) (learn-rate :initform 0.01 :initarg :learn-rate) (mWi :initform nil :documentation "weights connecting input and 1st hidden layer") (mBi :initform nil) ;; NROW being hidden units of prev layer; NCOL being of next layer (mWhs :initform nil :documentation "list of weight matrices per layer, with length being (nlayers - 1): exluding output layer") ;; row vector, with NCOL being hidden units of next layer (mBhs :initform nil) (mZcache :initform nil :documentation "cached Z for backward propagation") (mAcache :initform nil :documentation "cached A for backward propagation") (mWo :initform nil :documentation "connecting last hidden and outputy layer") (mBo :initform nil))) (defmethod initialize-instance :after ((mlp multilayer-perceptron) &rest args) "skip input and output layer, as we do not know the input/output shape yet..." (declare (ignore args)) (with-slots (hidden-units layer-nums activation mWhs mBhs mBi) mlp (setf layer-nums (+ (length hidden-units) 2)) (setf activation (make-activation activation)) (setf mBi (make-rand-row-vector (car hidden-units) 1.0)) (dotimes (i (- layer-nums 3)) (push (make-rand-matrix (nth i hidden-units) (nth (+ i 1) hidden-units) 1.0) mWhs) (push (make-rand-row-vector (nth (+ i 1) hidden-units) 1.0) mBhs)) (setf mWhs (nreverse mWhs)) (setf mBhs (nreverse mBhs)))) (defmethod input-layer ((mlp multilayer-perceptron)) 0) (defmethod last-hidden-layer ((mlp multilayer-perceptron)) (with-slots (layer-nums) mlp (- layer-nums 2))) (defmethod output-layer ((mlp multilayer-perceptron)) (with-slots (layer-nums) mlp (- layer-nums 1))) (defmethod layer-weights ((mlp multilayer-perceptron) i) "input layer being 0, has no associated weights; output layer being (layer-nums - 1)" (with-slots (layer-nums mWi mBi mWhs mBhs mWo mBo) mlp (cond ((or (< i 0) (> (+ i 1) layer-nums)) (error "no such layer ~A in MLP" (+ i 1))) ((= i 0) (error "no weights associated with layer 0")) ((= i 1) (values mWi mBi)) ((= (+ i 1) layer-nums) (values mWo mBo)) ;; output layer (t (values (nth (- i 2) mWhs) (nth (- i 2) mBhs)))))) (defmacro do-layers ((i mlp) &body body) "we have no interest in the input layer" `(do ((,i 1 (1+ ,i))) ((>= ,i (layer-nums ,mlp))) ,@body)) (defmacro do-layers-reverse ((i mlp) &body body) "we have no interest in the input layer" `(do ((,i (- (layer-nums ,mlp) 1) (1- ,i))) ((< ,i 1)) ,@body)) (defmacro do-layer-weights ((mW mB mlp) &body body) (let ((idx-sym (gensym "IDX-"))) `(let ((,mW nil) (,mB nil)) ;; excluding input layer (do ((,idx-sym 1 (1+ ,idx-sym))) ((>= ,idx-sym (layer-nums ,mlp))) (multiple-value-setq (,mW ,mB) (layer-weights ,mlp ,idx-sym)) ,@body)))) ;;; Network construction (defmethod build-network ((mlp multilayer-perceptron) X y) "fill in input and output layer" (error "not implemented in base class")) ;;; Cache initialization (defmethod %init-forward-cache ((mlp multilayer-perceptron) X) (with-slots (mZcache mAcache) mlp (setf mZcache (list X)) (setf mAcache (list X)) (do-layer-weights (mW mB mlp) (push (make-matrix (nrow X) (ncol mW)) mZcache) (push (make-matrix (nrow X) (ncol mW)) mAcache)) (setf mZcache (nreverse mZcache)) (setf mAcache (nreverse mAcache)))) ;;; Forward Propagation (defun linear-combination (mX mW vB &optional (op #'+)) "mX * mW + vB: broadcasting `vB' accross rows of (mX * mW)" (let ((mXW (m* mX mW))) (do-matrix-row (i mXW) (do-matrix-col (j mXW) (setf (mref mXW i j) (funcall op (mref mXW i j) (vref vb j))))) mXW)) (defmethod forward-linear ((mlp multilayer-perceptron) i mA) "Z = AW + b" (multiple-value-bind (mW mB) (layer-weights mlp i) (linear-combination mA mW mB))) (defmethod forward-layer ((mlp multilayer-perceptron) i X &optional zCache) "feed forward X through layer i: (values A Z), where A = act(Z) = act(XW + b) if the output layer, A = Z without activation: softmax might be out there! if `zCache', cache Z" (with-slots (activation layer-nums) mlp (let ((mZ (forward-linear mlp i X))) (when zCache (fill-matrix zCache mZ)) (if (= i (output-layer mlp)) mZ (activate-matrix activation mZ))))) (defmethod forward-output ((mlp multilayer-perceptron) mZ) "do activation on the output" (error "not implemented in base class")) (defmethod forward-propagation ((mlp multilayer-perceptron) X) "feed forward and cache Z's of each layer" (with-slots (mZcache mAcache) mlp (let ((pred X)) (do-layers (l mlp) (setf pred (forward-layer mlp l pred (nth l mZcache))) (fill-matrix (nth l mAcache) pred)) (forward-output mlp pred)))) ;;; Backward Propagation (defmethod backward-output ((mlp multilayer-perceptron) mA y) "do loss gradient on the outupt and label: returns dA for the output layer, dZ = dA" (error "not implemented in base class")) (defun %element-wise-op (mA mZ &optional (op #'*)) "NOTICE: will modify `mA'" (do-matrix (i j mA) (setf (mref mA i j) (funcall op (mref mA i j) (mref mZ i j)))) mA) ;;; TODO: replace dA with dZ, for the last layer, dZ = dA (defmethod backward-layer ((mlp multilayer-perceptron) i dZ) "Input: dZ[l]; Output: dZ[l-1], dW[l], db[l]" (with-slots (activation mZcache mAcache) mlp (let* ((Ap (nth (- i 1) mAcache)) (Zp (nth (- i 1) mZcache)) (m (nrow Zp)) (mW nil) dAp dZp dW db) (multiple-value-setq (mW) (layer-weights mlp i)) ;; dW = 1/m \dot Ap.T \dot dZ (setf dW (m* (/ 1 m) (mt Ap) dZ)) ;; db = 1/m \dot sum(dZ) (setf db (m* (/ 1 m) (msum dZ :axis 0))) ;; dAp = dZ \dot W.T (setf dAp (m* dZ (mt mW))) ;; g'(Z) (activate-gradient-matrix activation Zp) ;; dZ = dA * g'(Z) (setf dZp (%element-wise-op dAp Zp)) (values dZp dW db)))) (defun %update-weight (mW dW eta) (do-matrix (i j mW) (decf (mref mW i j) (* eta (mref dW i j)))) mW) (defmethod backward-propagation ((mlp multilayer-perceptron) dZ) "backward propagation" (with-slots (learn-rate) mlp (do-layers-reverse (i mlp) (multiple-value-bind (mW mB) (layer-weights mlp i) (multiple-value-bind (dZp dW dB) (backward-layer mlp i dZ) (%update-weight mW dW learn-rate) (%update-weight mB dB learn-rate) (setf dZ dZp)))))) (defmethod fit ((mlp multilayer-perceptron) X &optional y) (build-network mlp X y) (%init-forward-cache mlp X) (with-slots (epochs) mlp (let (mA dZ) (dotimes (i epochs) (setf mA (forward-propagation mlp X)) (setf dZ (backward-output mlp mA y)) (backward-propagation mlp dZ) (let ((pred (predict mlp X))) (format t "~A-th accuracy: ~A~%" i (accuracy-score y pred))))))) (defmethod predict ((mlp multilayer-perceptron) X) "feed forward and no cache: for prediction" (let ((pred X)) (do-layers (l mlp) (setf pred (forward-layer mlp l pred nil))) (forward-output mlp pred))) ;;; MLP classifier (defclass mlp-classifier (multilayer-perceptron) ((nclasses :initform nil))) (defmethod build-network ((mlpclf mlp-classifier) X y) (with-slots (hidden-units mWi mWo mBo nclasses) mlpclf (setf nclasses (length (mbincount y))) (setf mWi (make-rand-matrix (ncol X) (car hidden-units) 1.0)) (setf mWo (make-rand-matrix (car (last hidden-units)) nclasses 1.0)) (setf mBo (make-rand-row-vector nclasses 1.0)))) (defmethod forward-output ((mlpclf mlp-classifier) mZ) (softmax-on-matrix mZ)) (defmethod backward-output ((mlpclf mlp-classifier) mA y) (cross-entropy-gradient mA y) mA) (defmethod predict-proba ((mlpclf mlp-classifier) X) (let ((pred X)) (do-layers (l mlpclf) (setf pred (forward-layer mlpclf l pred nil))) (softmax-on-matrix pred))) (defmethod predict ((mlpclf mlp-classifier) X) (let ((pred (predict-proba mlpclf X))) (margmax pred :axis 1))) ;;; MLP regressor (defclass mlp-regressor (multilayer-perceptron) ()) (defmethod initialize-instance :after ((mlpreg mlp-regressor) &rest args) "skip input layer, as we do not know the input shape yet..." (declare (ignore args)) (with-slots (hidden-units mWo mBo) mlpreg (setf mWo (make-rand-matrix (car (last hidden-units)) 1 1.0)) (setf mBo (make-rand-row-vector 1 1.0)))) (defmethod build-network ((mlpreg mlp-regressor) X y) (declare (ignore y)) (with-slots (hidden-units mWi) mlpreg (setf mWi (make-rand-matrix (ncol X) (car hidden-units) 1.0)))) (defmethod forward-output ((mlpreg mlp-regressor) mZ) mZ) (defmethod backward-output ((mlpred mlp-regressor) mA y) )
9,605
Common Lisp
.lisp
224
38.183036
87
0.658036
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
79f94b9ddcb662f8aedfc42e478dfd61f2d6c54f30ba0cb0a956cb16e2a3e949
17,374
[ -1 ]
17,375
kmeans.lisp
jnjcc_cl-ml/cluster/kmeans.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Unsupervised Learning > clustering > k-Means clustering (in-package #:cl-ml) (deftype kmeans-init-type () '(member :kmeans++ :random)) (defclass kmeans-cluster (estimator) ((nclusters :initform 5 :initarg :nclusters) (clusters :initform nil :documentation "smatrix of centroids") (xlabels :initform nil :documentation "labels of each point") (init :initform :kmeans++ :initarg :init :type kmeans-init-type :documentation "method for cluster centers initialization") ;;; TODO: choose best (ninit :initform 1 :initarg :ninit :documentation "number of times the k-means algorithm will be run with different centroid") (epochs :initform 300 :initarg :epochs :documentation "max number of iterations of the k-means algorithm for a single run") ;;; TODO: tolerance (tolerance :initform 1.0e-3 :initarg :tolerance))) (defun %%min-distance (X i chosens) "min distance between `i'-th sample and `chosens' centroids" (let ((cur (mrv X i)) (tdis nil) ;; temp distance (mdis nil) (midx nil)) (do-ia-access (indx chosens) (setf tdis (euclidean-distance cur (mrv X indx))) (when (or (null mdis) (> mdis tdis)) (setf mdis tdis) (setf midx indx))) (values mdis midx))) (defun %%choose-next-index (X chosens lefts) (if (null chosens) (randint 0 (nrow X)) (let ((probs nil) (curdis nil)) (do-ia-access (l lefts) (setf curdis (%%min-distance X l chosens)) (setf curdis (* curdis curdis)) (push curdis probs)) (car (weighted-sampling lefts (nreverse probs) 1))))) (defun %kmeans++-centroids-indices (X k) (let (;; chosen indices, left indices (chosens nil) (lefts (make-indices (nrow X))) ;; current chosen index (cidx nil)) (dotimes (i k) (setf cidx (%%choose-next-index X chosens lefts)) (push cidx chosens) (setf lefts (nset-difference lefts (list cidx)))) chosens)) (defmethod init-centroids ((kmeans kmeans-cluster) X) (with-slots (init nclusters clusters) kmeans (let ((rindices nil)) (ecase init (:kmeans++ (setf rindices (%kmeans++-centroids-indices X nclusters))) (:random (setf rindices (simple-indices (nrow X) nclusters)))) (cond ((or (null clusters) (or (/= (nrow clusters) nclusters) (/= (ncol clusters) (ncol X)))) (setf clusters (copy-matrix (make-matrix-view X :row-view rindices)))) (t (do-indices (i indx rindices) (setf (mrv clusters i) (mrv X indx)))))))) (defmethod cluster-one-sample ((kmeans kmeans-cluster) X i) (with-slots (clusters) kmeans (let ((cur (mrv X i)) (mdist nil) ;; minimum distance (mclst nil) ;; minimum cluster (tdist nil)) (do-matrix-row (clst clusters) (setf tdist (euclidean-distance cur (mrv clusters clst))) (when (or (null mdist) (> mdist tdist)) (setf mdist tdist) (setf mclst clst))) (values mclst mdist)))) (defmethod cluster-samples ((kmeans kmeans-cluster) X) (let ((clst-bins nil)) (do-matrix-row (i X) (multiple-value-bind (mclst) (cluster-one-sample kmeans X i) (binpush clst-bins mclst i))) clst-bins)) (defmethod update-centroids ((kmeans kmeans-cluster) X bins) (with-slots (clusters nclusters) kmeans (do-bins (clst indices bins) (let ((avg (mmean (make-matrix-view X :row-view indices)))) (setf (mrv clusters clst) avg))))) (defmethod inertia-score ((kmeans kmeans-cluster) X bins) (let ((inertia 0.0)) (do-matrix-row (i X) (multiple-value-bind (clst dist) (cluster-one-sample kmeans X i) (declare (ignore clst)) (incf inertia (* dist dist)))) inertia)) (defmethod fit ((kmeans kmeans-cluster) X &optional y) (declare (ignore y)) (with-slots (nclusters clusters xlabels init ninit epochs tolerance) kmeans (when (< (nrow X) nclusters) (error "sample number less than clusters")) (setf xlabels (make-vector (nrow X) :initial-element nil)) (dotimes (ini ninit) (init-centroids kmeans X) (dotimes (ep epochs) (let ((clst-bins (cluster-samples kmeans X))) (update-centroids kmeans X clst-bins)))))) (defmethod predict-one ((kmeans kmeans-cluster) X i) (cluster-one-sample kmeans X i)) (defmethod predict ((kmeans kmeans-cluster) X) (let ((pred (make-vector (nrow X) :initial-element nil))) (do-matrix-row (i X) (setf (vref pred i) (cluster-one-sample kmeans X i))) pred)) (defmethod %fill-one-reduction ((kmeans kmeans-cluster) X i R j) "fill i-th dimension reduction vector into j-th row of R" (with-slots (clusters) kmeans (let ((cur (mrv X i))) (do-matrix-row (clst clusters) (setf (mref R j clst) (euclidean-distance cur (mrv clusters clst))))))) (defmethod transform-one ((kmeans kmeans-cluster) X i) (with-slots (nclusters) kmeans (let ((reduced (make-row-vector nclusters :initial-element nil))) (%fill-one-reduction kmeans X i reduced 0) reduced))) (defmethod transform ((kmeans kmeans-cluster) X) "NOTICE: unlike `transformer' class, this method does not modify `X'" (with-slots (nclusters) kmeans (let ((reduced (make-matrix (nrow X) nclusters :initial-element nil))) (do-matrix-row (i reduced) (%fill-one-reduction kmeans X i reduced i)) reduced))) (defmethod fit-transform ((kmeans kmeans-cluster) X) )
5,564
Common Lisp
.lisp
132
36.333333
82
0.653122
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
8a36c89fda746c6537f532c7b32eca2307e1a88914acde6c4f49572e3a3e4894
17,375
[ -1 ]
17,376
dbscan.lisp
jnjcc_cl-ml/cluster/dbscan.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Unsupervised Learning > clustering > DBSCAN (in-package #:cl-ml)
143
Common Lisp
.lisp
4
34.5
66
0.695652
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
51dd179abb96c489aba355579c69c992b2bbc73aedc8370e8f6b51ee471c7c16
17,376
[ -1 ]
17,377
sim-access.lisp
jnjcc_cl-ml/linalg/sim-access.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Simple matrix: access opertaions for smatrix and smatrix-view through (MREF) ;;;; NOTICE: unless stated, all access opertaions share memory, too (in-package #:cl-ml/linalg) ;; loop with matrix indices: ;; with indices of `mref' properly translated, we can now safely start loop from indices (0, 0) (defmacro do-matrix-row ((i ma) &body body) `(dotimes (,i (nrow ,ma)) ,@body)) (defmacro do-matrix-col ((j ma) &body body) `(dotimes (,j (ncol ,ma)) ,@body)) ;; NOTICE: with the form ;; (do-matrix-row (,i ,ma) ;; (do-matrix-col (,j ,ma) ;; ,@body)) ;; we cannot do (RETURN) right in `body' ;; NOTICE: with the form ;; (multiple-value-bind (,i ,j) (floor ,idx-sym (ncol ,ma)) ;; ,@body) ;; we cannot do (GO end-of-loop) right in `body' (defmacro do-matrix ((i j ma) &body body) (let ((idx-sym (gensym "IDX-"))) `(do ((,idx-sym 0 (1+ ,idx-sym)) (,i nil) (,j nil)) ((>= ,idx-sym (* (nrow ,ma) (ncol ,ma)))) ;; let's do row major! (multiple-value-setq (,i ,j) (floor ,idx-sym (ncol ,ma))) ,@body))) (defmacro do-vector ((i va) &body body) (let ((len-sym (gensym "LEN-"))) ;; one of nrow / ncol should be 1 `(let ((,len-sym (* (nrow ,va) (ncol ,va)))) (dotimes (,i ,len-sym) ,@body)))) (defun copy-matrix (ma) (let ((copy (make-matrix (nrow ma) (ncol ma)))) (do-matrix (i j copy) (setf (mref copy i j) (mref ma i j))) copy)) (defun fill-matrix (ma mb) (do-matrix (i j ma) (setf (mref ma i j) (mref mb i j)))) (defun fill-vector (va vb) (do-vector (i va) (setf (vref va i) (vref vb i)))) (defmethod vref ((va smatrix) i) (case (svector-type va) (:column (mref va i 0)) (:row (mref va 0 i)) (otherwise (error "malformed vector dimension (~A, ~A)" (nrow va) (ncol va))))) (defmethod (setf vref) (val (va smatrix) i) (case (svector-type va) (:column (setf (mref va i 0) val)) (:row (setf (mref va 0 i) val)) (otherwise (error "malformed vector dimension (~A, ~A)" (nrow va) (ncol va))))) (defmethod mrv ((ma smatrix) i) "row vector of matrix" (make-matrix-view ma :row-view (list i))) (defmethod (setf mrv) ((val smatrix) (ma smatrix) i) "set row vector of matrix" (unless (and (= (ncol ma) (ncol val)) (= (nrow val) 1)) (error "row vector dimension not match: (~A, ~A) (~A, ~A)" (nrow ma) (ncol ma) (nrow val) (ncol val))) (do-matrix-col (j ma) (setf (mref ma i j) (vref val j)))) (defmethod (setf mrv) ((val number) (ma smatrix) i) (do-matrix-col (j ma) (setf (mref ma i j) val))) (defmethod mcv ((ma smatrix) j) "column vector of matrix" (make-matrix-view ma :col-view (list j))) (defmethod (setf mcv) ((val smatrix) (ma smatrix) j) "set column vector of matrix" (unless (and (= (nrow ma) (nrow val)) (= (ncol val) 1)) (error "column vector dimension not match: (~A, ~A) (~A, ~A)" (nrow ma) (ncol ma) (nrow val) (ncol val))) (do-matrix-row (i ma) (setf (mref ma i j) (vref val i)))) (defmethod (setf mcv) ((val number) (ma smatrix) j) (do-matrix-row (i ma) (setf (mref ma i j) val))) (defmethod print-object ((ma smatrix) stream) (fresh-line stream) (format stream "~A x ~A (~A):~%" (nrow ma) (ncol ma) (type-of (mref ma 0 0))) (do-matrix-row (i ma) (do-matrix-col (j ma) (format stream "~A~A" (mref ma i j) #\Tab)) (format stream "~%")))
3,509
Common Lisp
.lisp
92
34.108696
95
0.591471
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
4e7c177f99b029a1f6a47b2203d3c68967b75ee8166f72890915951f8eff5f60
17,377
[ -1 ]
17,378
sim-smatrix.lisp
jnjcc_cl-ml/linalg/sim-smatrix.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Simple matrix: smatrix class ;;;; ;;;; smatrix-dense ;;;; / ;;;; smatrix (- smatrix-sparse[*] smatrix-view ;;;; \ / \ ;;;; smatrix-view-window[*] (- smatrix-transpose -) view of the underlying smatrix ;;;; \ / ;;;; smatrix-diagview (in-package #:cl-ml/linalg) (defclass smatrix () ()) ;;; 1) rows and columns (defgeneric nrow (ma) (:documentation "rows of `ma'")) (defgeneric ncol (ma) (:documentation "cols of `ma'")) (defgeneric mshape (ma)) (defmethod mshape ((ma smatrix)) (list (nrow ma) (ncol ma))) ;;; 2) vector (defun svector-type (vx) (cond ((= (ncol vx) 1) :column) ((= (nrow vx) 1) :row) (t nil))) ;;; 3) element access (defgeneric mref (ma i j) (:documentation "access (i, j)-th element")) (defgeneric (setf mref) (val ma i j) (:documentation "set (i, j)-th element")) (defgeneric vref (vx i) (:documentation "access i-th element of vector")) (defgeneric (setf vref) (val vx i) (:documentation "set i-th element of vector")) ;;; 4) make-* functions ;;; - make-matrix ;;; - make-square-matrix ;;; - make-identity-matrix ;;; - make-rand-matrix ;;; - make-vector ;;; - make-row-vector ;;; - make-rand-vector ;;; - make-rand-row-vector (declaim (ftype (function (integer integer &key (:initial-element t) (:initial-contents t)) smatrix) make-matrix)) (declaim (ftype (function (integer &key (:initial-element t) (:initial-contents t)) smatrix) make-square-matrix)) (declaim (ftype (function (integer) smatrix) make-identity-matrix)) (declaim (ftype (function (integer integer &optional t t) smatrix) make-rand-matrix)) (deftype make-vector-ftype () '(function (integer &key (:initial-element t) (:initial-contents t)) smatrix)) (declaim (ftype make-vector-ftype make-vector)) (declaim (ftype make-vector-ftype make-row-vector)) (deftype make-rand-vector-ftype () '(function (integer &optional t t) smatrix)) (declaim (ftype make-rand-vector-ftype make-rand-vector)) (declaim (ftype make-rand-vector-ftype make-rand-row-vector)) ;;; 5) matrix properties and operations ;;; NOTICE: M-operations access element through (MREF), which handles polymorphism ;;; - (M+) (M-) (M*) (M/) (MINV) (MPINV) return a fresh object of smatrix ;;; - (MT) shares memory with the original smatrix ;;; - (M+=) (M-=) (M*=) (M/=) (MMAP) (MREDUCE) do operations in-place (defgeneric mdet (ma) (:documentation "determinant of squared matrix")) (defgeneric m+ (ma mb &rest mrest) (:documentation "matrix addition")) (defgeneric m+= (ma mb)) (defgeneric m- (ma mb &rest mrest) (:documentation "matrix substraction")) (defgeneric m-= (ma mb)) (defgeneric m* (ma mb &rest mrest) (:documentation "matrix multiplication")) (defgeneric m*= (ma mb) (:documentation "NOTICE: m*= does its best to do operation in-place: `mb' is number, or (ncol `mb') = (nrow `mb'), or even (ncol `mb') < (nrow `mb')")) (defgeneric m/ (ma mb) (:documentation "m/ only works on smatrix and number")) (defgeneric m/= (ma mb) (:documentation "m/= only works on smatrix and number")) (defgeneric mt (ma) (:documentation "matrix transpose")) (defgeneric minv (ma) (:documentation "matrix inverse")) (defgeneric mpinv (ma) (:documentation "Moore-Penrose pseudoinverse")) (defgeneric mmap (ma op) (:documentation "do `op' on each matrix element")) (defgeneric mreduce (ma op &key axis key initial-value) (:documentation "`axis' = nil: do `op' on all elements of `ma'; `axis' = 0: on elements of same column; `axis' = 1: on elements of same row")) (defgeneric v+ (vx vy) (:documentation "vector element-wise addition")) (defgeneric v+= (vx vy)) (defgeneric v- (vx vy) (:documentation "vector element-wise substraction")) (defgeneric v-= (vx vy)) (defgeneric v* (vx vy) (:documentation "vector element-wise product")) (defgeneric v*= (vx vy)) (defgeneric v/ (vx vy) (:documentation "v/ only works on smatrix and number")) (defgeneric v/= (vx vy)) (defgeneric vdot (vx vy) (:documentation "vector dot product. NOTICE: accept different shapes")) (defgeneric vouter (vx vy) (:documentation "outer product")) (defgeneric vsum (vx) (:documentation "vector sum")) (defgeneric vmap (vx op) (:documentation "do `op' on each vector element")) (defgeneric vreduce (vx op &key initial-value) (:documentation "reduce `op' on vector")) ;;; 6) matrix statistics (defgeneric mhead (ma &optional n)) (defgeneric msum (ma &key axis key initial-value) (:documentation "on same column by default")) (defgeneric mmean (ma &key axis key)) (defgeneric mquantile (ma quad &key axis)) (defgeneric mmax (ma &key axis key)) (defgeneric mmin (ma &key axis key)) (defgeneric margmax (ma &key axis key)) (defgeneric margmin (ma &key axis key) (:documentation "on same column by default")) (defgeneric mbincount (ma) (:documentation "bin classes and count"))
5,169
Common Lisp
.lisp
132
36.590909
93
0.655131
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
29a8918d1868cb7fb3b34d6c8935a0c67e844455aa1ea70dfe9bdb999da2a3d9
17,378
[ -1 ]
17,379
sim-operation.lisp
jnjcc_cl-ml/linalg/sim-operation.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Simple matrix: matrix properties and operations (in-package #:cl-ml/linalg) (defmethod mdet ((ma smatrix)) (let ((copy (copy-matrix ma)) (det 1)) (gaussian-on-matrix copy) (do-matrix-row (i copy) (setf det (* det (mref copy i i)))) det)) (defun %ensure-dimension-match (ma mb) (when (or (/= (nrow ma) (nrow mb)) (/= (ncol ma) (ncol mb))) (error "dimension not match: (~A, ~A), (~A, ~A)" (nrow ma) (ncol ma) (nrow mb) (ncol mb)))) (defun %ensure-dimension-mult (ma mb) (when (/= (ncol ma) (nrow mb)) (error "dimension not match for mult: (~A, ~A), (~A, ~A)" (nrow ma) (ncol ma) (nrow mb) (ncol mb)))) (defmethod m+= ((ma smatrix) (mb smatrix)) (%ensure-dimension-match ma mb) (do-matrix (i j ma) (incf (mref ma i j) (mref mb i j)))) (defmethod m+= ((ma smatrix) (mb number)) (do-matrix (i j ma) (incf (mref ma i j) mb))) (defmethod m+ ((ma smatrix) mb &rest mrest) "smatrix + smatrix / smatrix + number" (let ((add (copy-matrix ma))) (m+= add mb) (dolist (mr mrest) (m+= add mr)) add)) (defmethod m+ ((ma number) (mb smatrix) &rest mrest) (let ((add (copy-matrix mb))) (m+= add ma) (dolist (mr mrest) (m+= add mr)) add)) (defmethod m+ ((ma number) (mb number) &rest mrest) (let ((sum (+ ma mb))) (if mrest (apply #'m+ (cons sum mrest)) sum))) (defmethod m-= ((ma smatrix) (mb smatrix)) (%ensure-dimension-match ma mb) (do-matrix (i j ma) (decf (mref ma i j) (mref mb i j)))) (defmethod m-= ((ma smatrix) (mb number)) (do-matrix (i j ma) (decf (mref ma i j) mb))) (defmethod m- ((ma smatrix) mb &rest mrest) "smatrix - smatrix / smatrix - number" (let ((sub (copy-matrix ma))) (m-= sub mb) (dolist (mr mrest) (m-= sub mr)) sub)) (defmethod m- ((ma number) (mb smatrix) &rest mrest) (let ((sub (copy-matrix mb))) (do-matrix (i j sub) (setf (mref sub i j) (- ma (mref mb i j)))) (dolist (mr mrest) (m-= sub mr)) sub)) (defmethod m*= ((ma smatrix) (mb smatrix)) (%ensure-dimension-mult ma mb) (unless (= (ncol mb) (nrow mb)) (error "m*= not applicable: (~A, ~A) (~A, ~A)" (nrow ma) (ncol ma) (nrow mb) (ncol mb))) (let ((vrow (make-row-vector (ncol ma)))) (do-matrix-row (i ma) (fill-matrix vrow (mrv ma i)) (do-matrix-col (j ma) (setf (mref ma i j) 0) (dotimes (k (ncol ma)) (incf (mref ma i j) (* (vref vrow k) (mref mb k j)))))))) (defmethod m*= ((ma smatrix) (mb number)) (do-matrix (i j ma) (setf (mref ma i j) (* (mref ma i j) mb)))) (defun %prod-out-place (ma mb) (let ((prod (make-matrix (nrow ma) (ncol mb) :initial-element 0))) (do-matrix (i j prod) (dotimes (k (ncol ma)) (incf (mref prod i j) (* (mref ma i k) (mref mb k j))))) prod)) (defmethod %prod-try-in-place ((ma smatrix) (mb smatrix)) "do matrix production in-place as much as possible" (let ((prod ma)) (if (= (nrow mb) (ncol mb)) (m*= ma mb) (setf prod (%prod-out-place ma mb))) prod)) (defmethod %prod-try-in-place ((ma smatrix) (mb number)) (m*= ma mb)) (defmethod m* ((ma smatrix) (mb smatrix) &rest mrest) "do matrix production in-place as much as possible" (let ((prod (%prod-out-place ma mb))) (dolist (mr mrest) (setf prod (%prod-try-in-place prod mr))) prod)) (defmethod m* ((ma smatrix) (mb number) &rest mrest) (let ((prod (make-matrix (nrow ma) (ncol ma)))) (do-matrix (i j prod) (setf (mref prod i j) (* (mref ma i j) mb))) (dolist (mr mrest) (setf prod (%prod-try-in-place prod mr))) prod)) (defmethod m* ((ma number) (mb smatrix) &rest mrest) (let ((prod (make-matrix (nrow mb) (ncol mb)))) (do-matrix (i j prod) (setf (mref prod i j) (* (mref mb i j) ma))) (dolist (mr mrest) (setf prod (%prod-try-in-place prod mr))) prod)) (defmethod m* ((ma number) (mb number) &rest mrest) (let ((mult (* ma mb))) (if mrest (apply #'m* (cons mult mrest)) mult))) (defmethod m/ ((ma smatrix) (mb smatrix)) (%ensure-dimension-match ma mb) (let ((div (make-matrix (nrow ma) (ncol ma)))) (do-matrix (i j div) (setf (mref div i j) (/ (mref ma i j) (mref mb i j)))) div)) (defmethod m/= ((ma smatrix) (mb smatrix)) (%ensure-dimension-match ma mb) (do-matrix (i j ma) (setf (mref ma i j) (/ (mref ma i j) (mref mb i j))))) (defmethod m/ ((ma smatrix) (mb number)) (let ((div (make-matrix (nrow ma) (ncol ma)))) (do-matrix (i j div) (setf (mref div i j) (/ (mref ma i j) mb))) div)) (defmethod m/= ((ma smatrix) (mb number)) (do-matrix (i j ma) (setf (mref ma i j) (/ (mref ma i j) mb)))) (defmethod mt ((ma smatrix)) (%make-transpose-matrix ma)) (defmethod minv ((ma smatrix)) (%gauss-jordan ma)) (defmethod mmap ((ma smatrix) op) (do-matrix (i j ma) (setf (mref ma i j) (funcall op (mref ma i j)))) ma) (defmethod mreduce ((ma smatrix) op &key (axis 0) (key #'identity) (initial-value 0)) (let ((reduced initial-value)) (cond ((null axis) (do-matrix (i j ma) (setf reduced (funcall op reduced (funcall key (mref ma i j)))))) ;; on all elements of the same column ((= axis 0) (if (= (ncol ma) 1) (do-matrix (i j ma) (setf reduced (funcall op reduced (funcall key (mref ma i j))))) (progn (setf reduced (make-row-vector (ncol ma) :initial-element initial-value)) (do-matrix (i j ma) (setf (vref reduced j) (funcall op (vref reduced j) (funcall key (mref ma i j)))))))) ;; on all elements of the same row ((= axis 1) (if (= (nrow ma) 1) (do-matrix (i j ma) (setf reduced (funcall op reduced (funcall key (mref ma i j))))) (progn (setf reduced (make-vector (nrow ma) :initial-element initial-value)) (do-matrix (i j ma) (setf (vref reduced i) (funcall op (vref reduced i) (funcall key (mref ma i j))))))))) reduced)) (defun %ensure-two-vectors (vx vy) (unless (and (svector-type vx) (svector-type vy)) (error "vectors expected: (~A, ~A), (~A, ~A)" (nrow vx) (ncol vx) (nrow vy) (ncol vy)))) (defun %ensure-one-vector (vx) (unless (svector-type vx) (error "vector expected: (~A, ~A)" (nrow vx) (ncol vx)))) (defun %ensure-size-match (vx vy) (unless (= (* (nrow vx) (ncol vx)) (* (nrow vy) (ncol vy))) (error "vector size dimatch: (~A, ~A), (~A, ~A)" (nrow vx) (ncol vx) (nrow vy) (ncol vy)))) (defmethod v+ ((vx smatrix) (vy smatrix)) (%ensure-two-vectors vx vy) (m+ vx vy)) (defmethod v+= ((vx smatrix) (vy smatrix)) (%ensure-two-vectors vx vy) (m+= vx vy)) (defmethod v+ ((vx smatrix) (vy number)) (%ensure-one-vector vx) (m+ vx vy)) (defmethod v+= ((vx smatrix) (vy number)) (%ensure-one-vector vx) (m+= vx vy)) (defmethod v+ ((vx number) (vy smatrix)) (%ensure-one-vector vy) (m+ vx vy)) (defmethod v- ((vx smatrix) (vy smatrix)) (%ensure-two-vectors vx vy) (m- vx vy)) (defmethod v-= ((vx smatrix) (vy smatrix)) (%ensure-two-vectors vx vy) (m-= vx vy)) (defmethod v- ((vx smatrix) (vy number)) (%ensure-one-vector vx) (m- vx vy)) (defmethod v-= ((vx smatrix) (vy number)) (%ensure-one-vector vx) (m-= vx vy)) (defmethod v- ((vx number) (vy smatrix)) (%ensure-one-vector vy) (m- vx vy)) (defmethod v* ((vx smatrix) (vy smatrix)) (%ensure-two-vectors vx vy) (%ensure-dimension-match vx vy) (let ((prod (make-matrix (nrow vx) (ncol vx)))) (do-matrix (i j prod) (setf (mref prod i j) (* (mref vx i j) (mref vy i j)))) prod)) (defmethod v*= ((vx smatrix) (vy smatrix)) (%ensure-two-vectors vx vy) (%ensure-dimension-match vx vy) (do-matrix (i j vx) (setf (mref vx i j) (* (mref vx i j) (mref vy i j))))) (defmethod v* ((vx smatrix) (vy number)) "scalar multiplication of matrices" (%ensure-one-vector vx) (m* vx vy)) (defmethod v*= ((vx smatrix) (vy number)) (%ensure-one-vector vx) (m*= vx vy)) (defmethod v* ((vx number) (vy smatrix)) (%ensure-one-vector vy) (m* vx vy)) (defmethod v/ ((vx smatrix) (vy smatrix)) (%ensure-two-vectors vx vy) (m/ vx vy)) (defmethod v/= ((vx smatrix) (vy smatrix)) (%ensure-two-vectors vx vy) (m/= vx vy)) (defmethod v/ ((vx smatrix) (vy number)) (%ensure-one-vector vx) (m/ vx vy)) (defmethod v/= ((vx smatrix) (vy number)) (%ensure-one-vector vx) (m/= vx vy)) (defmethod vdot ((vx smatrix) (vy smatrix)) (%ensure-two-vectors vx vy) (%ensure-size-match vx vy) (let ((dot 0)) (do-vector (i vx) (incf dot (* (vref vx i) (vref vy i)))) dot)) (defmethod vouter ((vx smatrix) (vy smatrix)) (%ensure-two-vectors vx vy) (let ((xtype (svector-type vx)) (ytype (svector-type vy))) (cond ((and (eq xtype :column) (eq ytype :row)) (m* vx vy)) ((and (eq xtype :column) (eq ytype :column)) (m* vx (mt vy))) ((and (eq xtype :row) (eq ytype :row)) (m* (mt vx) vy)) ((and (eq xtype :row) (eq ytype :column) (m* (mt vx) (mt vy))))))) (defmethod vmap ((vx smatrix) op) (%ensure-one-vector vx) (do-matrix (i j vx) (setf (mref vx i j) (funcall op (mref vx i j)))) vx) (defmethod vreduce ((vx smatrix) op &key (initial-value 0)) (%ensure-one-vector vx) (let ((result initial-value)) (do-matrix (i j vx) (setf result (funcall op result (mref vx i j)))) result))
9,747
Common Lisp
.lisp
276
30.192029
86
0.574934
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
48fa6a86fc59f0731fe527b60c716581a5e8809962b003b48aacd4ff282b3b44
17,379
[ -1 ]
17,380
sim-bidiagonal.lisp
jnjcc_cl-ml/linalg/sim-bidiagonal.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Simple matrix: bidiagonalization using Householder transformation (in-package #:cl-ml/linalg) (defun %make-full-view (mA) (make-matrix-view mA :row-view '(0 . :end) :col-view '(0 . :end))) ;;; narrow from top-left corner to bottom-right corner (defun %narrow-matrix-column (mAv) "A[k] = (v[k] A[k+1]) extract A[k+1] to calculate householder-of-row-vector" (let ((kplus (+ (car (col-view mAv)) 1))) (update-matrix-view mAv :col-view `(,kplus . :end)))) (defun %narrow-matrix-row (mAv) "A[k] = (v^{T} A[k+1])^{T}, extract A[k+1]" (let ((kplus (+ (car (row-view mAv)) 1))) (update-matrix-view mAv :row-view `(,kplus . :end)))) (defun %make-square-view (mH s) "bottom right corner of square matrix mH, with size S x S" (let* ((n (nrow mH)) (start (- n s))) (make-matrix-view mH :row-view `(,start . :end) :col-view `(,start . :end)))) ;;; widen from bottom-right corner to top-left corner (defun %widen-square-view (mHv) (let ((kminus (- (car (row-view mHv)) 1))) (update-matrix-view mHv :row-view `(,kminus . :end) :col-view `(,kminus . :end)))) ;;; Assume m > n (defun %householder-on-matrix (mAv beta vvec delta &optional (force nil)) (householder-on-matrix mAv beta vvec) (when force ;; force first column zero to avoid precision problem (householder-on-vector (mcv mAv 0) beta vvec delta))) (defun %householder-on-row-matrix (mAv beta vvec gamma &optional (force nil)) (householder-on-row-matrix mAv beta vvec) (when force (householder-on-row-vector (mrv mAv 0) beta vvec gamma))) (defun bidiagonalize (mA) "Requires: nrow > ncol; Returns: (U, V, B) such that U^{T}AV = B; NOTICE: will modify A in-place, copy-matrix if necessary The backward version, which avoids (M*=) & (%narrow-householder-view) using householder-on-matrix: U = P1 * (P2 * (P3 * ... * (Pn * I))) Outside the view of P[k] and P[k+1], all other elements are 1's and 0's of identity matrix, we can safely do (P[k] * P[k+1]) before P[k-1] with elements outside of P[k]'s view untouched (imagine partitioned matrix!)" (let* ((m (nrow mA)) (n (ncol mA)) (mU (make-identity-matrix m)) (mV (make-identity-matrix n)) ;; \tilde{P}[n] starts from (m-n+1)x(m-n+1) (mUv (%make-square-view mU (- m n -1))) ;; \tilde{H}[n-2] starts from 2x2 (mVv (%make-square-view mV 2)) (mPlist nil) ;; list of (beta v) for Householder matrix P's (mHlist nil) (mAv (%make-full-view mA))) (do ((k 1 (+ k 1))) ((>= k (- n 1))) ;; A_{k-1} = (v_{k} A_{k}) (multiple-value-bind (beta vvec delta) (householder (mcv mAv 0)) ;; A_{k-1} = P * A_{k-1} (%householder-on-matrix mAv beta vvec delta) (push (list beta vvec) mPlist)) ;; extract A_{k} (%narrow-matrix-column mAv) ;; A_{k} = (u^{T} \tilde{A}_{k})^{T} (multiple-value-bind (beta vvec gamma) (householder-of-row-vector (mrv mAv 0)) ;; A * H = (H * A^{T})^{T} (%householder-on-row-matrix mAv beta vvec gamma) (push (list beta vvec) mHlist)) ;; extract as A_{k} for the next loop (%narrow-matrix-row mAv)) ;; k = n-1: collect P[n-1, n] (multiple-value-bind (beta vvec delta) (householder (mcv mAv 0)) (%householder-on-matrix mAv beta vvec delta) (push (list beta vvec) mPlist)) ;; extract A_{n-1} = (\gamma_{n} v_{n})^{T} (%narrow-matrix-column mAv) ;; extract v_{n} (%narrow-matrix-row mAv) (multiple-value-bind (beta vvec delta) (householder (mcv mAv 0)) (%householder-on-matrix mAv beta vvec delta) (push (list beta vvec) mPlist)) (dolist (Pvals mPlist) ;; U = P * U (householder-on-matrix mUv (car Pvals) (cadr Pvals)) (%widen-square-view mUv)) (dolist (Hvals mHlist) ;; V = H * V (householder-on-matrix mVv (car Hvals) (cadr Hvals)) (%widen-square-view mVv)) (values mU mV mA))) (defun %narrow-householder-view (mHv) "make `mHv' identity matrix, and narrow view, so as to hold the next Householder matrix \((k . :end) (k . :end)) => ((k+1 . :end) (k+1 . :end))" (do-matrix (i j mHv) (if (= i j) (setf (mref mHv i j) 1) (setf (mref mHv i j) 0))) (let ((kplus (+ (car (row-view mHv)) 1))) (update-matrix-view mHv :row-view `(,kplus . :end) :col-view `(,kplus . :end)))) (defun bidiagonalize-forward (mA) "Requires: nrow > ncol; Returns: (U, V, D) such that U^{T}AV = D NOTICE: will modify A in-place, copy-matrix if necessary This is the forward version: U = ((P1 * P2) * P3) * ... Pn" (let* ((m (nrow mA)) (n (ncol mA)) (mU (make-identity-matrix m)) (mV (make-identity-matrix n)) (mP (make-identity-matrix m)) (mH (make-identity-matrix n)) (mPv (%make-square-view mP m)) (mHv (%make-square-view mH (- n 1))) (mAv (%make-full-view mA))) (do ((k 1 (+ k 1))) ((>= k (- n 1))) ;; A_{k-1} = (v_{k} A_{k}) (multiple-value-bind (beta vvec delta) (householder (mcv mAv 0)) ;; A_{k-1} = P * A_{k-1} (%householder-on-matrix mAv beta vvec delta) ;; k-th Householder matrix: do Householder tranformation on identity matrix (householder-on-matrix mPv beta vvec) (m*= mU mP) ;; make identity matrix (%narrow-householder-view mPv)) ;; extract A_{k} (%narrow-matrix-column mAv) ;; A_{k} = (u^{T} \tilde{A}_{k})^{T} (multiple-value-bind (beta vvec gamma) (householder-of-row-vector (mrv mAv 0)) ;; A * H = (H * A^{T})^{T} (%householder-on-row-matrix mAv beta vvec gamma) (householder-on-row-matrix mHv beta vvec) (m*= mV mH) (%narrow-householder-view mHv)) ;; extract as A_{k} for the next loop (%narrow-matrix-row mAv)) ;; k = n-1: collect P[n-1, n] (multiple-value-bind (beta vvec delta) (householder (mcv mAv 0)) (%householder-on-matrix mAv beta vvec delta) (householder-on-matrix mPv beta vvec) (m*= mU mP) (%narrow-householder-view mPv)) ;; extract A_{n-1} = (\gamma_{n} v_{n})^{T} (%narrow-matrix-column mAv) ;; extract v_{n} (%narrow-matrix-row mAv) (multiple-value-bind (beta vvec delta) (householder (mcv mAv 0)) (%householder-on-matrix mAv beta vvec delta) (householder-on-matrix mPv beta vvec) (m*= mU mP) (%narrow-householder-view mPv)) (values mU mV mA)))
6,607
Common Lisp
.lisp
153
37.045752
89
0.590563
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
e73e0ff4fac21ae033c9aea80f953dc9f789e36ffad268ef18eff00563065f1b
17,380
[ -1 ]
17,381
sim-hessenberg.lisp
jnjcc_cl-ml/linalg/sim-hessenberg.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Simple matrix: Hessenberg using Householder transformation (in-package #:cl-ml/linalg) (defun %bottom-left-vector (mAv) "mAv = ((A11, \pmb{a}_{2}) (\pmb{a}_{1}, A_{2})), we want to extract \pmb{a}_{1}: first column vector without A11" (make-matrix-view mAv :row-view '(1 . :end) :col-view '(0))) (defun %widen-to-right-block (mAv) "mAv = ((A1, A3) (A4, A2)), we want to extract ((A3) (A2)) right block of the whole matrix A" (update-matrix-view mAv :row-view '(0 . :end))) (defun %householder-and-narrow-view (mAv beta vvec) "HAH, while `beta' and `vvec' are parameters of \tilde{H}: H = ((I, 0) (0, \tilde{H})); A = ((A1, A3) (A4, A2)); mAv is A2 plus last row of A3 & last column of A4 H * mAv * H = ((a[1][1], a_{2}^{T} * \tilde{H}) (\tilde{H} * a_{1}, \tilde{H} * mAv * \tilde{H})) HAH = ((A1, A3 * \tilde{H}) (\tilde{H} * A4, \tilde{H} * A2 * \tilde{H})) The whole (A3 * \tilde{H}) part must be re-calculated each time" ;; bottom left vector a_{1} (householder-on-vector (%bottom-left-vector mAv) beta vvec) ;; right block B of the original matrix A, multiply \tilde{H} on the right: ;; B = B * \tilde{H} (%narrow-matrix-column mAv) (with-restored-view (mAv) (%widen-to-right-block mAv) (householder-on-row-matrix mAv beta vvec)) ;; A2 = \tilde{H} * A2 (%narrow-matrix-row mAv) (householder-on-matrix mAv beta vvec)) (defun hessenberg (mA) "Requires: nrow = ncol; Returns: (Q, H) such that Q^{T}AQ = H; NOTICE: will modify A in-place, copy-matrix if necessary The backward version: Q = H1 * (H2 * (H3 * ... * (H[n-2] * I))), where \tilde{H}[n-2] is 2x2" (let* ((n (nrow mA)) (mQ (make-identity-matrix n)) ;; \tilde{H}[n-2] starts from 2x2 (mQv (%make-square-view mQ 2)) (mHlist nil) (mAv (%make-full-view mA))) (do ((k 1 (+ k 1))) ((>= k (- n 1))) (multiple-value-bind (beta vvec aval) (householder (%bottom-left-vector mAv)) (declare (ignore aval)) ;; A = H * A * H (%householder-and-narrow-view mAv beta vvec) (push (list beta vvec) mHlist))) (dolist (Hvals mHlist) ;; Q = H * Q (householder-on-matrix mQv (car Hvals) (cadr Hvals)) (%widen-square-view mQv)) (values mQ mA))) (defun hessenberg-forward (mA) "Requires: nrow = ncol; Returns: (Q, H) such that Q^{T}AQ = H; NOTICE: will modify A in-place, copy-matrix if necessary The forward version: Q = ((H1 * H2) * H3) * ... * H[n-2]" (let* ((n (nrow mA)) (mQ (make-identity-matrix n)) (mH (make-identity-matrix n)) ;; \tilde{H}[n-2] starts from (n-1)x(n-1) (mHv (%make-square-view mH (- n 1))) (mAv (%make-full-view mA))) (do ((k 1 (+ k 1))) ((>= k (- n 1))) (multiple-value-bind (beta vvec aval) (householder (%bottom-left-vector mAv)) (declare (ignore aval)) ;; A = H * A * H (%householder-and-narrow-view mAv beta vvec) (householder-on-matrix mHv beta vvec) (m*= mQ mH) (%narrow-householder-view mHv))) (values mQ mA)))
3,143
Common Lisp
.lisp
72
38.680556
103
0.58956
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
cebc679d6318041cbb5f0972c872fd53f33456443f6d77d1e2caff831e04f5e2
17,381
[ -1 ]
17,382
sim-diagview.lisp
jnjcc_cl-ml/linalg/sim-diagview.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Simple matrix: matrix diagonal view (in-package #:cl-ml/linalg) (deftype diagonal-type () '(member :main :upper :lower :both)) (defclass smatrix-diagview (smatrix) ((displaced-to :initform nil :initarg :displaced-to :reader displaced-to) (diag-type :initform :main :initarg :diag-type :type diagonal-type) ;; assume index starts from `pseudo-start' (pseudo-start :initform 0 :initarg :pseudo-start :reader pseudo-start))) ;;; rows and colums (defmethod nrow ((ma smatrix-diagview)) (with-slots (displaced-to) ma (if displaced-to (nrow displaced-to) 0))) (defmethod ncol ((ma smatrix-diagview)) (with-slots (displaced-to) ma (if displaced-to (ncol displaced-to) 0))) (defmethod ndiag ((ma smatrix-diagview)) (let ((n (min (nrow ma) (ncol ma)))) (with-slots (diag-type) ma (ecase diag-type (:main n) (:upper (if (>= (nrow ma) (ncol ma)) (- n 1) n)) (:lower (if (<= (nrow ma) (ncol ma)) (- n 1) n)) (:both (if (= (nrow ma) (ncol ma)) (- n 1) (error "square matrix expected: (~A, ~A)" (nrow ma) (ncol ma)))))))) ;;; element access (defmethod %indices-valid-p ((ma smatrix-diagview) i j) (with-slots (diag-type) ma (ecase diag-type (:main (= i j)) (:upper (= (+ i 1) j)) (:lower (= i (+ j 1))) (:both (or (= (+ i 1) j) (= i (+ j 1))))))) (defmethod mref ((ma smatrix-diagview) i j) (with-slots (displaced-to) ma (if (%indices-valid-p ma i j) (mref displaced-to i j) 0))) (defmethod (setf mref) (val (ma smatrix-diagview) i j) (with-slots (displaced-to) ma (when (%indices-valid-p ma i j) (setf (mref displaced-to i j) val)))) ;; diagonal element access (defmethod dref ((ma smatrix-diagview) i) (with-slots (diag-type pseudo-start) ma (decf i pseudo-start) (ecase diag-type (:main (mref ma i i)) (:upper (mref ma i (+ i 1))) (:lower (mref ma (+ i 1) i)) (:both (mref ma i (+ i 1)))))) (defmethod (setf dref) (val (ma smatrix-diagview) i) (with-slots (diag-type pseudo-start) ma (decf i pseudo-start) (ecase diag-type (:main (setf (mref ma i i) val)) (:upper (setf (mref ma i (+ i 1)) val)) (:lower (setf (mref ma (+ i 1) i) val)) (:both (setf (mref ma i (+ i 1)) val (mref ma (+ i 1) i) val))))) (defmacro do-diagonal ((i ma) &body body) (let ((ndiag-sym (gensym "NDIAG-")) (start-sym (gensym "START-"))) `(let ((,ndiag-sym (ndiag ,ma)) (,start-sym (pseudo-start ,ma))) (do ((,i ,start-sym (+ ,i 1))) ((>= ,i (+ ,start-sym ,ndiag-sym))) ,@body)))) (defmacro do-diagonal-reverse ((i ma) &body body) (let ((ndiag-sym (gensym "NDIAG-")) (start-sym (gensym "START-"))) `(let ((,ndiag-sym (ndiag ,ma)) (,start-sym (pseudo-start ,ma))) (do ((,i (+ ,start-sym ,ndiag-sym -1) (- ,i 1))) ((< ,i ,start-sym)) ,@body)))) ;;; make-* functions (defun make-diagonal-view (ma &key (diag-type :main) (pseudo-start 0)) (make-instance 'smatrix-diagview :displaced-to ma :diag-type diag-type :pseudo-start pseudo-start))
3,381
Common Lisp
.lisp
91
30.582418
87
0.560134
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
485830b0a5d85cde833e2448aa34762e7329d0d610acb86ee81e94786123c2d9
17,382
[ -1 ]
17,383
sim-stats.lisp
jnjcc_cl-ml/linalg/sim-stats.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Statistics stuff for smatrix (in-package #:cl-ml/linalg) (defmethod mhead ((ma smatrix) &optional (n 6)) (if (< n 0) (make-matrix-view ma :row-view (cons (+ (nrow ma) n) :end)) (make-matrix-view ma :row-view (cons 0 n)))) (defmethod msum ((ma smatrix) &key (axis 0) (key #'identity) (initial-value 0)) (mreduce ma #'+ :initial-value initial-value :key key :axis axis)) (defmethod mmean ((ma smatrix) &key (axis 0) (key #'identity)) (let ((sum (msum ma :axis axis :key key :initial-value 0))) (cond ((null axis) (setf sum (/ sum (* (nrow ma) (ncol ma))))) ((= axis 1) (m/= sum (ncol ma))) ((= axis 0) (m/= sum (nrow ma)))) sum)) (defun %get-quant-value (va indices quat) "get quantile of a single vector, and a single quantile" (setf indices (sort-indices indices va)) (multiple-value-bind (i ir j jr) (quantile-positions (length indices) quat) (+ (* ir (iavref va indices i)) (* jr (iavref va indices j))))) (defun %fill-quant-vector (va indices quatlst quatvec) "fill quantile for vectors of a matrix" (setf indices (sort-indices indices va)) (let ((idx 0) (len (length indices))) (dolist (quat quatlst) (multiple-value-bind (i ir j jr) (quantile-positions len quat) (setf (vref quatvec idx) (+ (* ir (iavref va indices i)) (* jr (iavref va indices j))))) (incf idx)))) (defmethod mquantile ((ma smatrix) quat &key (axis 0)) (let ((qumat nil)) (cond ((null axis) (progn (do-matrix (i j ma) (push (mref ma i j) qumat)) (setf qumat (sort qumat #'<)) (setf qumat (quantile qumat quat)) (when (consp qumat) (setf qumat (make-vector (length qumat) :initial-contents qumat))) qumat)) ;; on all elements of the same column ((= axis 0) (let ((indices (make-indices (nrow ma)))) (cond ((consp quat) (setf qumat (make-matrix (length quat) (ncol ma)))) ((> (ncol ma) 1) (setf qumat (make-matrix 1 (ncol ma)) quat (list quat)))) (do-matrix-col (j ma) (if qumat (%fill-quant-vector (mcv ma j) indices quat (mcv qumat j)) (setf qumat (%get-quant-value (mcv ma j) indices quat)))) qumat)) ;; on all elements of the sam row ((= axis 1) (let ((indices (make-indices (ncol ma)))) (cond ((consp quat) (setf qumat (make-matrix (nrow ma) (length quat)))) ((> (nrow ma) 1) (setf qumat (make-matrix (nrow ma) 1) quat (list quat)))) (do-matrix-row (i ma) (if qumat (%fill-quant-vector (mrv ma i) indices quat (mrv qumat i)) (setf qumat (%get-quant-value (mrv ma i) indices quat))))))) qumat)) (defmethod mmax ((ma smatrix) &key (axis 0) (key #'identity)) (labels ((nilmax (a b) (if (null a) b (max a b)))) (mreduce ma #'nilmax :axis axis :key key :initial-value nil))) (defmethod mmin ((ma smatrix) &key (axis 0) (key #'identity)) (labels ((nilmin (a b) (if (null a) b (min a b)))) (mreduce ma #'nilmin :axis axis :key key :initial-value nil))) (defmethod margfun ((ma smatrix) cmp &optional (axis 0) (key #'identity)) (let ((argvals nil)) (cond ((null axis) (let ((mval nil)) (do-matrix (i j ma) (when (or (null mval) (funcall cmp (funcall key (mref ma i j)) mval)) (setf mval (funcall (mref ma i j))) (setf argvals (cons i j)))))) ;; on all elements of the same column ((= axis 0) (let ((mvals (make-row-vector (ncol ma) :initial-element nil))) (setf argvals (make-row-vector (ncol ma) :initial-element nil)) (do-matrix (i j ma) (when (or (null (vref mvals j)) (funcall cmp (funcall key (mref ma i j)) (vref mvals j))) (setf (vref mvals j) (funcall key (mref ma i j))) (setf (vref argvals j) i))))) ;; on all elements of the same row ((= axis 1) (let ((mvals (make-vector (nrow ma) :initial-element nil))) (setf argvals (make-vector (nrow ma) :initial-element nil)) (do-matrix (i j ma) (when (or (null (vref mvals i)) (funcall cmp (funcall key (mref ma i j)) (vref mvals i))) (setf (vref mvals i) (funcall key (mref ma i j))) (setf (vref argvals i) j)))))) argvals)) (defmethod margmax ((ma smatrix) &key (axis 0) (key #'identity)) (margfun ma #'> axis key)) (defmethod margmin ((ma smatrix) &key (axis 0) (key #'identity)) (margfun ma #'< axis key)) (defmethod mbincount ((ma smatrix)) (let ((binlist nil)) (do-matrix (i j ma) (binincf binlist (mref ma i j))) binlist))
5,242
Common Lisp
.lisp
114
35.201754
94
0.530309
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
7e9c00ca4f30795ecb15d1253c78332aa0c6ad28420eb018404048f48e93693e
17,383
[ -1 ]
17,384
sim-qr.lisp
jnjcc_cl-ml/linalg/sim-qr.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Simple matrix: The QR algorithm (in-package #:cl-ml/linalg) (defun %make-tridiagonal (alphas betas) (if (/= (length alphas) (+ (length betas) 1)) (error "main diagonal and sub diagonal length not match") (let* ((n (length alphas)) (ma (make-matrix n n))) (dotimes (i (- n 1)) (setf (mref ma i i) (nth i alphas)) (setf (mref ma i (+ i 1)) (nth i betas)) (setf (mref ma (+ i 1) i) (nth i betas))) (setf (mref ma (- n 1) (- n 1)) (nth (- n 1) alphas)) ma))) (defun %sign (delta) (if (>= delta 0) 1 -1)) (defun %sqdref (diag i) "squared dref" (* (dref diag i) (dref diag i))) (defun wilkinson-tridiagonal (mT) "Symmetric tridiagonal QR algorithm with implicit Wilkinson shift, with main diagonal being (alpha[1], alpha[2], ..., alpha[n]), first diagonal above main diagonal being (beta[1], ..., beta[n-1]) NOTICE: will modify mT in-place, copy-matrix if necessary" (let* ((n (nrow mT)) (alpha (make-diagonal-view mT :diag-type :main :pseudo-start 1)) (beta (make-diagonal-view mT :diag-type :both :pseudo-start 1)) (delta (/ (- (dref alpha (- n 1)) (dref alpha n)) 2)) (mu (- (dref alpha n) (/ (%sqdref beta (- n 1)) (+ delta (* (%sign delta) (sqrt (+ (* delta delta) (%sqdref beta (- n 1))))))))) (x (- (dref alpha 1) mu)) (y (dref beta 1))) (do-diagonal (k beta) ;; solving [[c s] [-s c]] (multiple-value-bind (c s sigma) (givens-from-value x y) (multiple-value-bind (atmp btmp etmp ftmp) (givens-on-square (dref alpha k) (dref beta k) (dref beta k) (dref alpha (+ k 1)) c s) (multiple-value-bind (atmp btmp etmp ftmp) (givens-on-row-square atmp btmp etmp ftmp c (- s)) (assert (= btmp etmp)) (setf (dref alpha k) atmp) (setf (dref beta k) btmp) (setf (dref alpha (+ k 1)) ftmp))) (setf (dref beta (+ k 1)) (* c (dref beta (+ k 1)))) (when (> k 1) (setf (dref beta (- k 1)) sigma)) (setf x (dref beta k)) (setf y (* s (dref beta (+ k 1)))))))) (defun %make-bidiagonal (deltas gammas) (if (/= (length deltas) (+ (length gammas) 1)) (error "main diagonal and sub diagonal length not match") (let* ((n (length deltas)) (ma (make-matrix n n))) (dotimes (i (- n 1)) (setf (mref ma i i) (nth i deltas)) (setf (mref ma i (+ i 1)) (nth i gammas))) (setf (mref ma (- n 1) (- n 1)) (nth (- n 1) deltas)) ma))) (defun wilkinson-bidiagonal (mB) "Returns: (P, Q, B) such that B := P^{T}BQ NOTICE: will modify B in-place, copy-matrix if necessary main diagonal being (delta[0], delta[1], ..., delta[n-1]), first diagonal above main diagonal being (gamma[1], ..., gamma[n-1])" (let* ((n (nrow mB)) (delta (make-diagonal-view mB :diag-type :main)) (gamma (make-diagonal-view mB :diag-type :upper :pseudo-start 1)) ;; if mB is a 2x2 matrix, let gamma[0] be 0 (sqgamma (if (= n 2) 0 (%sqdref gamma (- n 2)))) (d (/ (- (+ (%sqdref delta (- n 2)) sqgamma) (+ (%sqdref gamma (- n 1)) (%sqdref delta (- n 1)))) 2)) (mu (/ (- (+ (%sqdref gamma (- n 1)) (%sqdref delta (- n 1))) (* (%sqdref delta (- n 2)) (%sqdref gamma (- n 1)))) (+ d (* (%sign d) (sqrt (+ (* d d) (* (%sqdref delta (- n 2)) (%sqdref gamma (- n 1))))))))) (x (- (%sqdref delta 0) mu)) (y (* (dref delta 0) (dref gamma 1))) (mP (make-identity-matrix n)) (mQ (make-identity-matrix n))) (dotimes (k (- n 1)) (multiple-value-bind (c s sigma) (givens-from-row-value x y) (let (btmp ftmp) (multiple-value-setq (x btmp y ftmp) (givens-on-row-square (dref delta k) (dref gamma (+ k 1)) 0 (dref delta (+ k 1)) c s)) (setf (dref gamma (+ k 1)) btmp) (setf (dref delta (+ k 1)) ftmp)) (givens-on-row-matrix mQ k (+ k 1) c s) (when (> k 0) (setf (dref gamma k) sigma))) (multiple-value-bind (c s sigma) (givens-from-value x y) (setf (dref delta k) sigma) ;; by using -s, we are doing transpose of G (givens-on-row-matrix mP k (+ k 1) c (- s)) (if (< k (- n 2)) (let (etmp ftmp) (multiple-value-setq (x y etmp ftmp) (givens-on-square (dref gamma (+ k 1)) 0 (dref delta (+ k 1)) (dref delta (+ k 2)) c s)) (setf (dref delta (+ k 1)) etmp) (setf (dref gamma (+ k 2)) ftmp)) (multiple-value-bind (atmp btmp) (givens-on-value (dref gamma (- n 1)) (dref delta (- n 1)) c s) (setf (dref gamma (- n 1)) atmp) (setf (dref delta (- n 1)) btmp))))) (values mP mQ mB)))
5,212
Common Lisp
.lisp
112
36.196429
98
0.499509
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
0e63cd5767c196fbadd5b679288eda85891a068056d180f7187d75009f6365a0
17,384
[ -1 ]
17,385
sim-transpose.lisp
jnjcc_cl-ml/linalg/sim-transpose.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Simple matrix: transposed matrix (in-package #:cl-ml/linalg) (defclass smatrix-transpose (smatrix) ((displaced-to :initform nil :initarg :displaced-to :reader displaced-to))) ;;; rows and columns (defmethod nrow ((ma smatrix-transpose)) (if (displaced-to ma) (ncol (displaced-to ma)) 0)) (defmethod ncol ((ma smatrix-transpose)) (if (displaced-to ma) (nrow (displaced-to ma)) 0)) ;;; element access (defmethod %translated-indices ((ma smatrix-transpose) i j) (declare (ignore ma)) (values j i)) (defmethod mref ((ma smatrix-transpose) i j) (with-slots (displaced-to) ma (multiple-value-bind (ridx cidx) (%translated-indices ma i j) (if displaced-to (mref displaced-to ridx cidx) (error "out of bounds: (~A, ~A)" i j))))) (defmethod (setf mref) (val (ma smatrix-transpose) i j) (with-slots (displaced-to) ma (multiple-value-bind (ridx cidx) (%translated-indices ma i j) (setf (mref displaced-to ridx cidx) val)))) ;;; make-* functions (defun %make-transpose-matrix (ma) (declare (type smatrix ma)) (if (typep ma 'smatrix-transpose) (displaced-to ma) (make-instance 'smatrix-transpose :displaced-to ma)))
1,282
Common Lisp
.lisp
35
32.714286
77
0.677159
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
66d7135473ec6351fcecf61e512b5fd4c1e7ec6f2f1f454474a1626a7c91bfbb
17,385
[ -1 ]
17,386
sim-transform.lisp
jnjcc_cl-ml/linalg/sim-transform.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Simple matrix: Matrix transformations (in-package #:cl-ml/linalg) ;;; 1) Gaussian elimination: three types of elementary row operations (defun %swap-rows (ma i j) "swapping two rows" (declare (type smatrix ma)) (do-matrix-col (k ma) (let ((tmp (mref ma i k))) (setf (mref ma i k) (mref ma j k)) (setf (mref ma j k) tmp)))) (defun %row*= (ma i mul) "multiplying a row by a nonzero number" (declare (type smatrix ma)) (do-matrix-col (j ma) (setf (mref ma i j) (* (mref ma i j) mul)))) (defun %row+= (ma to from &optional (mul 1)) "adding a multiple of one row to another row" (declare (type smatrix ma)) (do-matrix-col (j ma) (incf (mref ma to j) (* (mref ma from j) mul)))) (defun gaussian-on-matrix (mA) "Gaussian elimination on matrix; Requires: ncol >= nrow NOTICE: will modify `mA' in-place; copy-matrix if necessary" (let ((n (nrow mA))) (do-matrix-row (i mA) (when (= (mref mA i i) 0) (do ((j (+ i 1) (1+ j))) ((>= j n) (return-from gaussian-on-matrix)) (when (/= (mref mA j i) 0) (%swap-rows mA i j) (return)))) (let ((base (/ 1 (mref mA i i))) (ratio nil)) (do ((j (+ i 1) (1+ j))) ((>= j n)) (setf ratio (* base (mref mA j i))) (%row+= mA j i (- ratio))))))) (defun %gauss-jordan (ma) (declare (type smatrix ma)) (if (/= (nrow ma) (ncol ma)) (error "square matrix expected: (~A, ~A)" (nrow ma) (ncol ma)) (let* ((n (nrow ma)) ;; block matrix (bma (make-matrix n (* 2 n) :initial-element 0)) (inv (make-matrix n n))) (do-matrix (i j ma) (setf (mref bma i j) (mref ma i j))) (do-matrix-row (i bma) (setf (mref bma i (+ n i)) 1)) (do-matrix-row (i bma) (when (= (mref bma i i) 0) (do ((j (+ i 1) (1+ j))) ((>= j n) (error "matrix not invertible")) (when (/= (mref bma j i) 0) (%swap-rows bma i j) (return)))) (let ((ratio (/ 1 (mref bma i i)))) (%row*= bma i ratio) (do ((j 0 (1+ j))) ((>= j n)) (unless (= i j) (%row+= bma j i (- (mref bma j i))))))) (do-matrix (i j inv) (setf (mref inv i j) (mref bma i (+ j n)))) inv))) ;;; 2) Householder transformation (defun householder (vx) "Householder matrix from vector `vx', H * vx = a * e: H = I - 2ww^{T} = I - beta * v * v^{T} v = x + a * e, where a = ||x||; beta = 1 / a * v[1] Returns: (beta, v, a)" (let (beta v aval eta) (do-vector (i vx) (if (= i 0) (setf eta (abs (vref vx i))) (setf eta (max eta (abs (vref vx i)))))) (if (= eta 0) (values 0 (copy-matrix vx) 0) (progn (setf v (v/ vx eta)) ;; a = norm = ||v|| (setf aval (sqrt (vdot v v))) (when (< (vref v 0) 0) (setf aval (- aval))) ;; v1 = v1 + a (incf (vref v 0) aval) (setf beta (/ 1 (* aval (vref v 0)))) ;; a = eta * a (setf aval (* eta aval)) (values beta v aval))))) (defun householder-on-vector (vx beta v &optional a) "Hx = (I - \beta * v * vT) * x = x - \beta * (vT * x) * v NOTICE: will modify `vx' in-place; copy if necessary" (if a (do-vector (i vx) (setf (vref vx i) 0) (when (= i 0) (setf (vref vx i) (- a)))) (let ((dot (vdot v vx))) (do-vector (i vx) (decf (vref vx i) (* beta dot (vref v i)))))) vx) (defun householder-on-vector-copy (vx beta v &optional a) "Hx = (I - \beta * v * vT) * x = x - \beta * (vT * x) * v" (declare (ignore a)) (v- vx (v* (* beta (vdot v vx)) v))) (defun householder-on-matrix (mA beta v) "HA = A - \beta * v * (A^{T} * v)^{T} By making A = I, we can get the actual Householder matrix NOTICE: will modify A in-place; copy-matrix if necessary" (let ((sigma 0)) (do-matrix-col (j mA) (setf sigma 0) (do-matrix-row (i mA) (incf sigma (* (vref v i) (mref mA i j)))) (setf sigma (* beta sigma)) (do-matrix-row (i mA) (decf (mref mA i j) (* sigma (vref v i))))) mA)) (defun householder-of-row-vector (vx) (householder (mt vx))) (defun householder-on-row-vector (vx beta v &optional a) "xH: (MT VX) shares memory with VX" (householder-on-vector (mt vx) beta v a)) (defun householder-on-row-matrix (mA beta v) "AH = ((AH)^{T})^{T} = (H^{T} * A^{T})^{T} = (H * A^{T})^{T} \(MT A) shares memory with A" (householder-on-matrix (mt mA) beta v)) (defun householder-matrix (beta v) "H = I - \beta * v * vT" (let ((H (make-identity-matrix (nrow v)))) (householder-on-matrix H beta v))) ;;; 3) Givens rotation (defun givens-from-value (x y) "[[c s] [-s c]] * [[x] [y]] = [[val] [0]]: -s * x + c * y = 0" (let (c s) (if (= y 0) (setf c 1 s 0) (if (>= (abs y) (abs x)) (let ((tmp (/ x y))) (setf s (/ 1 (sqrt (+ 1 (* tmp tmp))))) (setf c (* s tmp))) (let ((tmp (/ y x))) (setf c (/ 1 (sqrt (+ 1 (* tmp tmp))))) (setf s (* c tmp))))) (values c s (+ (* c x) (* s y))))) (defun givens-from-row-value (x y) "[x y] * [[c s] [-s c]] = [val 0] <=> [[c -s] [s c]] * [[x] [y]] = [[val] [[0]]: s * x + c * y = 0" (multiple-value-bind (c s sigma) (givens-from-value x y) (values c (- s) sigma))) (defun givens (vx i j) "Givens matrix from vector `vx': vy = G(i, j, theta) * vx: vy[i] = c * vx[i] + s * vx[j]; vy[j] = 0" (multiple-value-bind (c s sigma) (givens-from-value (vref vx i) (vref vx j)) (values i j c s sigma))) (defun givens-on-value (x y c s) "[[c s] [-s c]] * [[x] [y]]" (values (+ (* c x) (* s y)) (+ (* (- s) x) (* c y)))) (defun givens-on-row-value (x y c s) "[x y] * [[c s] [-s c]]" (values (+ (* c x) (* (- s) y)) (+ (* s x) (* c y)))) (defun givens-on-square (a b e f c s) "G * SQ2 = [[c s] [-s c]] * [[a b] [e f]" (multiple-value-bind (newa newe) (givens-on-value a e c s) (multiple-value-bind (newb newf) (givens-on-value b f c s) (values newa newb newe newf)))) (defun givens-on-row-square (a b e f c s) "SQ2 * G = [[a b] [e f]] * [[c s] [-s c]]" (multiple-value-bind (newa newb) (givens-on-row-value a b c s) (multiple-value-bind (newe newf) (givens-on-row-value e f c s) (values newa newb newe newf)))) (defun givens-on-vector (vx i j c s) "vy = G * vx: vy[i] = c * vx[i] + s * vx[j]; vy[j] = -s * vx[i] + c * vx[j] NOTICE: will modify `vx' in-place; copy if necessary" (multiple-value-bind (newx newy) (givens-on-value (vref vx i) (vref vx j) c s) (setf (vref vx i) newx) (setf (vref vx j) newy)) vx) (defun givens-on-row-vector (vx i j c s) "vx * G NOTICE: will modify `vx' in-place; copy if necessary" (multiple-value-bind (newx newy) (givens-on-value (vref vx i) (vref vx j) c s) (setf (vref vx i) newx) (setf (vref vx j) newy)) vx) (defun givens-on-matrix (mA i j c s) "GA: only change row I and J of A; G is the form of [[c s] [-s c]] NOTICE: will modify A in-place; copy-matrix if necessary" (let (alpha beta) (do-matrix-col (k mA) (setf alpha (mref mA i k)) (setf beta (mref mA j k)) (setf (mref mA i k) (+ (* c alpha) (* s beta))) (setf (mref mA j k) (+ (* (- s) alpha) (* c beta))))) mA) (defun givens-on-row-matrix (mA i j c s) "AG: will only change column I and J of A; G is the form of [[c s] [-s c]] NOTICE: will modify A in-place; copy-matrix if necessary" (let (alpha beta) (do-matrix-row (k mA) (setf alpha (mref mA k i)) (setf beta (mref mA k j)) (setf (mref mA k i) (+ (* c alpha) (* (- s) beta))) (setf (mref mA k j) (+ (* s alpha) (* c beta))))) mA) (defun givens-matrix (n i j c s) "NOTICE: by using -s, we can get transpose matrix of G" (let ((idm (make-identity-matrix n))) (setf (mref idm i j) s) (setf (mref idm j i) (- s)) (setf (mref idm i i) c) (setf (mref idm j j) c) idm))
8,245
Common Lisp
.lisp
221
31.276018
94
0.515629
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
896169fefbd0d2d870b6866786480398b3daa746a5cfe5cd8c1253890d8f5d19
17,386
[ -1 ]
17,387
sim-view.lisp
jnjcc_cl-ml/linalg/sim-view.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Simple matrix: matrix view window (in-package #:cl-ml/linalg) ;;; three types of view window: ;;; - (start . end) association pair, meaning [start, end) ;;; + `start' must be integer ;;; + `end' can be integer or :end ;;; - (i1 i2 i3 ...) proper list ;;; - nil (defclass smatrix-view (smatrix) ((displaced-to :initform nil :initarg :displaced-to :reader displaced-to) (row-view :initform nil :initarg :row-view :accessor row-view :documentation "row indices of matrix") (col-view :initform nil :initarg :col-view :accessor col-view :documentation "col indices of matrix"))) ;;; rows and colums (defun %assoc-pair-p (view) "(a . b): a must be integer; b can be integer or :end" (and (consp view) (integerp (car view)) (or (integerp (cdr view)) (eq (cdr view) :end)))) (defmethod nrow ((ma smatrix-view)) (with-slots (row-view) ma (cond ((%assoc-pair-p row-view) (- (cdr row-view) (car row-view))) ((consp row-view) (length row-view)) ((displaced-to ma) (nrow (displaced-to ma))) (t 0)))) (defmethod ncol ((ma smatrix-view)) (with-slots (col-view) ma (cond ((%assoc-pair-p col-view) (- (cdr col-view) (car col-view))) ((consp col-view) (length col-view)) ((displaced-to ma) (ncol (displaced-to ma))) (t 0)))) ;;; element access (defun %translate-to-matrix-index (idx view) "translate from view index to matrix index" (cond ((%assoc-pair-p view) (let ((midx (+ idx (car view)))) (if (< midx (cdr view)) midx (error "out of bounds: ~A" idx)))) ((consp view) (if (< idx (length view)) (nth idx view) (error "out of bounds: ~A" idx))) (t idx))) (defmethod %translated-row-index ((ma smatrix-view) i) (%translate-to-matrix-index i (row-view ma))) (defmethod %translated-col-index ((ma smatrix-view) j) (%translate-to-matrix-index j (col-view ma))) (defmethod %translated-indices ((ma smatrix-view) i j) (values (%translate-to-matrix-index i (row-view ma)) (%translate-to-matrix-index j (col-view ma)))) (defmethod mref ((ma smatrix-view) i j) (with-slots (displaced-to) ma (multiple-value-bind (ridx cidx) (%translated-indices ma i j) (if displaced-to (mref displaced-to ridx cidx) (error "out of bounds: (~A, ~A)" i j))))) (defmethod (setf mref) (val (ma smatrix-view) i j) (with-slots (displaced-to) ma (multiple-value-bind (ridx cidx) (%translated-indices ma i j) (setf (mref displaced-to ridx cidx) val)))) ;;; make-* functions (defun %canonize-index (idx len) (or (integerp idx) (error "malformed index ~A: integer expected" idx)) (cond ((< -1 idx len) idx) ((<= (- len) idx -1) (+ idx len)) (t (error "malformed index ~A: range [~A, ~A) expected" idx (- len) len)))) (defun %canonize-pair-view (view len) (let ((car-idx (%canonize-index (car view) len)) (cdr-idx (cdr view))) (setf cdr-idx (cond ((eq cdr-idx :end) len) ((>= cdr-idx len) len) (t (%canonize-index cdr-idx len)))) (if (<= car-idx cdr-idx) (cons car-idx cdr-idx) (error "malformed view ~A: lower bound bigger than upper bound" view)))) (defun %canonize-view (view len) (labels ((canonize-index-with-len (idx) (%canonize-index idx len))) (cond ((%assoc-pair-p view) (%canonize-pair-view view len)) ((consp view) (mapcar #'canonize-index-with-len view)) ((null view) view) ((integerp view) (list (canonize-index-with-len view))) (t (error "malformed view ~A: not supported" view))))) (defun make-matrix-view (ma &key (row-view nil) (col-view nil)) (declare (type smatrix ma)) (let ((rview (%canonize-view row-view (nrow ma))) (cview (%canonize-view col-view (ncol ma)))) (make-instance 'smatrix-view :displaced-to ma :row-view rview :col-view cview))) ;;; NOTICE: we are changing view of the (displaced-to) matrix (defun update-matrix-view (maview &key (row-view nil row-supplied-p) (col-view nil col-supplied-p)) (when row-supplied-p (setf (row-view maview) (%canonize-view row-view (nrow (displaced-to maview))))) (when col-supplied-p (setf (col-view maview) (%canonize-view col-view (ncol (displaced-to maview)))))) (defmacro with-matrix-view ((maview &key row-view col-view) ma &body body) "matrix view for smatrix MA" `(let ((,maview (make-matrix-view ,ma :row-view ,row-view :col-view ,col-view))) ,@body)) (defmacro with-restored-view ((maview &key (row-view nil row-supplied-p) (col-view nil col-supplied-p)) &body body) (let ((row-sym (gensym "ROW-")) (col-sym (gensym "COL-")) (rview-sym (gensym "RVIEW-")) (cview-sym (gensym "CVIEW-"))) `(let ((,row-sym (row-view ,maview)) (,col-sym (col-view ,maview)) (,rview-sym (%canonize-view ,row-view (nrow (displaced-to ,maview)))) (,cview-sym (%canonize-view ,col-view (ncol (displaced-to ,maview))))) (unwind-protect (progn (when ,row-supplied-p (setf (row-view ,maview) ,rview-sym)) (when ,col-supplied-p (setf (col-view ,maview) ,cview-sym)) ,@body) (setf (row-view ,maview) ,row-sym (col-view ,maview) ,col-sym)))))
5,543
Common Lisp
.lisp
128
36.703125
85
0.602928
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
e00c44aea424b683dbfaa05a00b59b0311735982ae71252e8cb886d9662eb42c
17,387
[ -1 ]
17,388
sim-indirect.lisp
jnjcc_cl-ml/linalg/sim-indirect.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Simple matrix: Indirect Addressing through INDICES (in-package #:cl-ml/linalg) (defun iaref (data indices i &optional (ref #'vref)) "reference through Indirect Addressing" (let ((indx (nth i indices))) (funcall ref data indx))) (defun iavref (va indices i) "vector reference through Indirect Addressing" (iaref va indices i #'vref)) (defun (setf iavref) (val va indices i) (let ((indx (nth i indices))) (setf (vref va indx) val))) (defun swap-indices (indices i j) (let ((tmp (nth i indices))) (setf (nth i indices) (nth j indices)) (setf (nth j indices) tmp))) (defun sort-indices (indices datas &key (start 0) end (predicate #'<) (ref #'vref)) "sort `indices' according to `datas' NOTICE: destructive function, remember to do (setf indices (sort-indices indices)) as for destructive function, the original sequence is implementation-dependent, see HyperSpec of `nreverse'" (labels ((compare (i j) ;; here I and J (elemts of INDICES) are indices of DATAS, direct addressing (funcall predicate (funcall ref datas i) (funcall ref datas j)))) (setf (subseq indices start end) (sort (subseq indices start end) #'compare)) indices)) (defmacro do-indices ((i indx indices &key (start 0) end) &body body) "I is the index of `indices'; `indx' is the index of indirect addressing" (let ((end-sym (gensym "END-"))) `(let ((,end-sym ,end) (,indx nil)) (unless ,end-sym (setf ,end-sym (length ,indices))) (do ((,i ,start (1+ ,i))) ((>= ,i ,end-sym)) (setf ,indx (nth ,i ,indices)) ,@body)))) (defmacro do-ia-access ((indx indices &key (start 0) end) &body body) (let ((idx-sym (gensym "IDX-")) (end-sym (gensym "END-"))) `(let ((,end-sym ,end) (,indx nil)) (unless ,end-sym (setf ,end-sym (length ,indices))) (do ((,idx-sym ,start (1+ ,idx-sym))) ((>= ,idx-sym ,end-sym)) (setf ,indx (nth ,idx-sym ,indices)) ,@body)))) (defmacro do-mutable-indices ((i indx indices nactive) &body body) "I is the index of `indices'; `indx' is the index of indirect addressing NOTICE: the `nactive' might change during loop" `(do ((,i 0 (1+ ,i)) (,indx nil)) ((>= ,i ,nactive)) (setf ,indx (nth ,i ,indices)) ,@body)) (defmacro do-mutable-iacess ((indx indices nactive) &body body) "`indx' is the index of indirect addressing NOTICE: the `nactive' might change during loop" (let ((idx-sym (gensym "IDX-"))) `(do ((,idx-sym 0 (+ ,idx-sym 1)) (,indx nil)) ((>= ,idx-sym ,nactive)) (setf ,indx (nth ,idx-sym ,indices)) ,@body)))
2,769
Common Lisp
.lisp
67
35.940299
88
0.619614
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
ad508a09670238ea4ce1947ae931efb1f527359c008a35d77feac37385fa5c9e
17,388
[ -1 ]
17,389
packages.lisp
jnjcc_cl-ml/linalg/packages.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Linear Algebra (in-package #:cl-user) (defpackage #:cl-ml/linalg (:nicknames #:ml/linalg) (:use #:cl #:cl-ml/probs) (:export #:smatrix #:nrow #:ncol #:mshape ;; smatrix creation #:make-matrix #:copy-matrix #:fill-matrix #:make-square-matrix #:make-identity-matrix #:make-rand-matrix #:make-vector #:make-rand-vector #:fill-vector #:make-row-vector #:make-rand-row-vector ;; smatrix-view creation #:make-matrix-view #:update-matrix-view #:with-matrix-view #:with-restored-view ;; smatrix element access #:do-matrix #:do-vector #:do-matrix-row #:do-matrix-col #:mref #:vref #:mrv #:mcv ;; smatrix properties #:mdet #:svector-type ;; smatrix operations #:m+ #:m- #:m* #:m/ #:m+= #:m-= #:m*= #:m/= #:mt #:minv #:msvd #:mpinv #:mmap #:mreduce #:v+ #:v- #:v* #:v/ #:v+= #:v-= #:v*= #:v/= #:vdot #:vouter #:vmap #:vreduce ;; smatrix indirect addressing #:swap-indices #:sort-indices #:do-indices #:do-ia-access #:do-mutable-indices #:do-mutable-iacess #:iavref ;; smatrix statistics #:mhead #:msum #:mmean #:mquantile #:mmax #:mmin #:margmax #:margmin #:mbincount ))
1,460
Common Lisp
.lisp
36
30.583333
79
0.527915
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
13ea78df516eceb7690e63a11685398c43a6392ce4b47be2a1c7098bac95d09a
17,389
[ -1 ]
17,390
sim-dense.lisp
jnjcc_cl-ml/linalg/sim-dense.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Simple matrix: smatrix-dense (in-package #:cl-ml/linalg) (defclass smatrix-dense (smatrix) ((data :initform nil :type 'array))) ;;; rows and columns (defmethod nrow ((ma smatrix-dense)) (with-slots (data) ma (if data (array-dimension data 0) 0))) (defmethod ncol ((ma smatrix-dense)) (with-slots (data) ma (if data (array-dimension data 1) 0))) ;;; element access (defmethod mref ((ma smatrix-dense) i j) (with-slots (data) ma (aref data i j))) (defmethod (setf mref) (val (ma smatrix-dense) i j) (with-slots (data) ma (setf (aref data i j) val))) ;;; make-* functions (defun make-matrix (nrow ncol &key (initial-element 0) initial-contents) (let ((ma (make-instance 'smatrix-dense))) (with-slots (data) ma (if initial-contents (setf data (make-array `(,nrow ,ncol) :initial-contents initial-contents)) (setf data (make-array `(,nrow ,ncol) :initial-element initial-element)))) ma)) (defun make-square-matrix (n &key (initial-element 0) initial-contents) (make-matrix n n :initial-element initial-element :initial-contents initial-contents)) (defun make-identity-matrix (n) (let ((idma (make-square-matrix n :initial-element 0))) (with-slots (data) idma (dotimes (i n idma) (setf (aref data i i) 1))))) (defun make-rand-matrix (nrow ncol &optional (limit 1.0) (state *random-state*)) (let ((ma (make-instance 'smatrix-dense))) (with-slots (data) ma (setf data (make-array (list nrow ncol) :initial-contents (randuni limit (list nrow ncol) state)))) ma)) ;; accept a list of values (defun make-vector (nrow &key (initial-element 0) initial-contents) "column vector as default" (when initial-contents ;; list of list (setf initial-contents (mapcar #'list initial-contents))) (make-matrix nrow 1 :initial-element initial-element :initial-contents initial-contents)) (defun make-row-vector (ncol &key (initial-element 0) initial-contents) (when initial-contents (setf initial-contents (list initial-contents))) (make-matrix 1 ncol :initial-element initial-element :initial-contents initial-contents)) (defun make-rand-vector (nrow &optional (limit 1.0) (state *random-state*)) "column vector as default" (make-vector nrow :initial-contents (randuni limit nrow state))) (defun make-rand-row-vector (ncol &optional (limit 1.0) (state *random-state*)) (make-row-vector ncol :initial-contents (randuni limit ncol state)))
2,639
Common Lisp
.lisp
64
36.359375
88
0.677079
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
47a84679d669d1d2b0716954f4084f884367a0f4467f11787a6b586127ca5953
17,390
[ -1 ]
17,391
sim-svd.lisp
jnjcc_cl-ml/linalg/sim-svd.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Simple matrix: Singular Value Decomposition and Moore-Penrose Pseudoinverse (in-package #:cl-ml/linalg) ;;; Singular Value Decomposition (defun %make-square-view-bound (mB p q) (let ((end (+ q 1))) (make-matrix-view mB :row-view `(,p . ,end) :col-view `(,p . ,end)))) (defun %update-square-view-bound (mBv p q) (let ((end (+ q 1))) (update-matrix-view mBv :row-view `(,p . ,end) :col-view `(,p . ,end)))) (defun %update-colview-bound (mUv p q) (let ((end (+ q 1))) (update-matrix-view mUv :col-view `(,p . ,end)))) (defun msvd (mA &optional (eps 1e-5)) "Requires: nrow > ncol; Returns: (U, B, V) such that A = UBV^{T} NOTICE: will modify A in-place, copy-matrix if necessary" (multiple-value-bind (mU mV mB) (bidiagonalize mA) (let ((delta (make-diagonal-view mB :diag-type :main)) (gamma (make-diagonal-view mB :diag-type :upper :pseudo-start 1)) (mUv (%make-full-view mU)) (mVv (%make-full-view mV))) ;; forever-loop (do ((mBsqv (%make-full-view mB))) (nil) (multiple-value-bind (converge-p p q) (%converge-test delta gamma mU eps) (when converge-p (return-from msvd (values mU mB mV))) (%update-square-view-bound mBsqv p q) (multiple-value-bind (mP mQ) (wilkinson-bidiagonal mBsqv) (%update-colview-bound mUv p q) (m*= mUv mP) (%update-colview-bound mVv p q) (m*= mVv mQ))))))) (defun %converge-test (delta gamma mU eps) "(delta[0], delta[1], ..., delta[n-1]) vs (gamma[1], gamma[2], ..., gamma[n-1])" (let* ((n (ndiag delta)) (converge-p t) (p 1) (q n)) ;; forever-loop (do () (nil) ;;; (i) clear gamma's (do-diagonal (j gamma) (when (<= (abs (dref gamma j)) (* eps (+ (abs (dref delta j)) (abs (dref delta (- j 1)))))) (setf (dref gamma j) 0))) ;;; (ii) find interval p, q (setf converge-p t) (do-diagonal (j gamma) (when (/= (dref gamma j) 0) (setf converge-p nil) (return))) (when converge-p (return-from %converge-test (values t nil nil))) (let ((found-q nil) (found-p nil)) (do-diagonal-reverse (j gamma) (if (not found-q) (when (/= (dref gamma j) 0) (setf found-q t) (setf q j)) (when (= (dref gamma j) 0) (setf found-p t) (setf p j) (return)))) ;; assume a pseudo gamma[0] := 0, or {gamma[pseudo_start - 1] := 0} (unless found-p (setf p 0))) ;;; (iii) initialize x, y (let ((infnorm (%infinity-norm delta gamma)) i x y) (do ((idx p (+ idx 1))) ((>= idx q) (return-from %converge-test (values nil p q))) (when (<= (abs (dref delta idx)) (* eps infnorm)) (setf i idx) (setf (dref delta i) 0) (setf x (dref gamma (+ i 1))) (setf y (dref delta (+ i 1))) (setf (dref gamma (+ i 1)) 0) (return))) ;;; (iv) [[c s] [-s c]] * [[x] [y]] = [[0] [sigma]] (do ((l 1 (+ l 1))) ((>= l (- q i))) ;; what we want: c * x + s * y = 0 (multiple-value-bind (s c) (givens-from-value x y) ;; what we get: -c * x + s * y = 0 (setf c (- c)) ;; -s * x + c * y (setf (dref delta (+ i l)) (+ (* (- s) x) (* c y))) (givens-on-row-matrix mU i (+ i l) c (- s)) (setf x (* s (dref gamma (+ i l 1)))) (setf (dref gamma (+ i l 1)) (* c (dref gamma (+ i l 1)))) (setf y (dref delta (+ i l 1))))))))) (defun %infinity-norm (delta gamma) "(delta[0], delta[1], ..., delta[n-1]) vs (gamma[1], gamma[2], ..., gamma[n-1])" (let ((norm (abs (dref delta (- (ndiag delta) 1)))) (crow 0)) (do-diagonal (i gamma) (setf crow (+ (abs (dref delta (- i 1))) (abs (dref gamma i)))) (when (> crow norm) (setf norm crow))) norm)) ;;; Moore-Penrose Pseudoinverse (defmethod mpinv ((ma smatrix)) (let ((mD (copy-matrix ma)) (dim (min (nrow ma) (ncol ma)))) (multiple-value-bind (mU mD mV) (msvd mD) (dotimes (i dim) (when (/= (mref mD i i) 0) (setf (mref mD i i) (/ 1.0 (mref mD i i))))) (m* mV mD (mt mU)))))
4,508
Common Lisp
.lisp
112
31.526786
82
0.497037
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
e6e961c62bd208a624b0967fd7cc3a211c9a27e9ceb7cb2dc3cb0efff9774f6e
17,391
[ -1 ]
17,392
transformer.lisp
jnjcc_cl-ml/base/transformer.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Transformer (in-package #:cl-ml) (defclass transformer (estimator) ()) (defgeneric transform (trans X) (:documentation "transform dataset X")) (defgeneric fit-transform (trans X) (:documentation "fit and transform dataset X")) (defgeneric inv-transform (trans X) (:documentation "inverse transform dataset X")) (defmethod transform ((trans transformer) X) X) (defmethod fit-transform ((trans transformer) X) X) (defmethod inv-transform ((trans transformer) X) X) ;;; we expand bias as the first term (defun %expand-bias (X) (declare (type smatrix X)) (let ((nrow (nrow X)) (ncol (ncol X))) (let ((x-bias (make-matrix nrow (+ ncol 1) :initial-element 1))) (do-matrix-row (i X) (do-matrix-col (j X) (setf (mref x-bias i (+ j 1)) (mref X i j)))) x-bias)))
895
Common Lisp
.lisp
28
28.642857
68
0.667053
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
6ebe44774571f1f0b31c31a495e46cf5cb9aab16a8491b3a538c70ab838b2552
17,392
[ -1 ]
17,393
numeric.lisp
jnjcc_cl-ml/base/numeric.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; numeric stuff such as infinity, overflow / underflow (in-package #:cl-ml) ;;; infinity comparison, we will not do infinity arithmetic (deftype infty-type () "positive infinity, negative infinity" '(member :infty :ninfty)) (defun inf< (a b) (cond ((eq a :infty) nil) ((eq a :ninfty) (not (eq b :ninfty))) (t (cond ((eq b :infty) t) ((eq b :ninfty) nil) (t (< a b)))))) (defun inf= (a b) (cond ((eq a :infty) (eq b :infty)) ((eq a :ninfty) (eq b :ninfty)) (t (= a b)))) (defun inf<= (a b) (cond ((eq a :infty) (eq b :infty)) ((eq a :ninfty) t) (t (cond ((eq b :infty) t) ((eq b :ninfty) nil) (t (<= a b)))))) (defun inf> (a b) (inf< b a)) (defun inf>= (a b) (inf<= b a)) (defun infmax (a b) (if (inf< a b) b a)) (defun infmin (a b) (if (inf< a b) a b)) ;;; overflow, underflow (defun logsumexp (y) "\log(\sum(\exp(x)))" (let ((b (mmax y :axis nil)) (sumexp 0.0)) (do-vector (i y) (incf sumexp (exp (- (vref y i) b)))) (+ b (log sumexp)))) (defun softmax-on-vector (y) "exp(yi) / \sum{exp(yi)} = exp(yi - b) / \sum{exp(yi - b)} NOTICE: will modify y in-place, copy-matrix if necessary" (let ((b (mmax y :axis nil)) (sumexp 0.0)) (do-vector (i y) ;; exp(y[i] - b) (setf (vref y i) (exp (- (vref y i) b))) (incf sumexp (vref y i))) (do-vector (i y) (setf (vref y i) (/ (vref y i) sumexp))) y)) (defun logsoftmax (y) "(log (softmax y))" (let ((b (mmax y :axis nil)) (sumexp 0.0)) (do-vector (i y) (setf (vref y i) (- (vref y i) b)) (incf sumexp (exp (vref y i)))) (setf sumexp (log sumexp)) (do-vector (i y) (setf (vref y i) (- (vref y i) sumexp))) y))
1,888
Common Lisp
.lisp
72
21.555556
66
0.522173
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
667b3b4b820521793aa2103b23e4d163d1d8b776a6f1820aaf54fcedfe444dda
17,393
[ -1 ]
17,394
estimator.lisp
jnjcc_cl-ml/base/estimator.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Estimator (in-package #:cl-ml) (defclass estimator () ()) (defgeneric fit (est X &optional y) (:documentation "train estimator from training set X")) (defgeneric predict (est X) (:documentation "predict for dataset X")) (defmethod fit ((est estimator) X &optional y) (declare (ignore y))) (defmethod predict ((est estimator) X))
418
Common Lisp
.lisp
13
30.230769
66
0.708229
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
8aec5a2e411c5d4102ff155fe99322708faa56440ffd639de4adf942e75c6c6d
17,394
[ -1 ]
17,395
dframe.lisp
jnjcc_cl-ml/base/dframe.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; "Data Frame" for training (in-package #:cl-ml) ;;; NOTICE: reorder training data through indirect addressing ;;; it is necessary we reorder the y label at the same time ;;; smatrix-view is not able to do that (defclass data-frame () ((xmatrix :initform nil :initarg :xmatrix) (ylabels :initform nil :initarg :ylabels) ;; feature name (optional) (feaname :initform nil :initarg :feaname) ;; indirect access of samples and features (sindice :initform nil :initarg :sindice) (findice :initform nil :initarg :findice))) (defun make-data-frame (X y &optional feaname) (let ((frame (make-instance 'data-frame :xmatrix X :ylabels y :feaname feaname))) (with-slots (sindice findice) frame (setf sindice (make-indices (nrow X))) (setf findice (make-indices (ncol X)))) frame)) (defmethod get-shape ((frame data-frame)) (with-slots (sindice findice) frame (values (length sindice) (length findice)))) (defmethod get-label ((frame data-frame) i) (with-slots (ylabels sindice) frame (iavref ylabels sindice i))) (defmethod get-sample ((frame data-frame) i) (with-slots (xmatrix ylabels sindice findice) frame (values (make-matrix-view xmatrix :row-view (nth i sindice) :col-view findice) (get-label frame i)))) (defmethod get-feature ((frame data-frame) j) (with-slots (xmatrix sindice findice) frame (make-matrix-view xmatrix :row-view sindice :col-view (nth j findice)))) (defmethod get-feature-value ((frame data-frame) i j) "J-th feature value of I-th sample" (with-slots (xmatrix sindice findice) frame (mref xmatrix (nth i sindice) (nth j findice)))) (defmethod get-feature-name ((frame data-frame) j) "get the original feature before reordering" (with-slots (feaname findice) frame (let ((jndx (nth j findice))) (if feaname (values jndx (nth jndx feaname)) (values jndx nil))))) ;;; for classification tasks ;;; TODO: what if label is string? (assoc #'string=) (defmethod count-label ((frame data-frame) &optional (start 0) end) (unless end (setf end (get-shape frame))) (let ((alist nil)) (do ((i start (1+ i))) ((>= i end)) (binincf alist (get-label frame i))) (values alist (- end start)))) (defmethod label-density ((frame data-frame) &optional (start 0) end) (multiple-value-bind (alist cnt) (count-label frame start end) (labels ((conv2prob (elem) (/ (cdr elem) cnt))) (mapcar #'conv2prob alist)))) ;;; for regression tasks (defmethod sum-label ((frame data-frame) &optional (start 0) end) (unless end (setf end (get-shape frame))) (let ((sum 0)) (do ((i start (1+ i))) ((>= i end)) (incf sum (get-label frame i))) (values sum (- end start)))) (defmethod mse-label ((frame data-frame) &optional (start 0) end) (unless end (setf end (get-shape frame))) (let ((avg 0) (mse 0) (diff 0) (cnt (- end start))) (do ((i start (1+ i))) ((>= i end)) (incf avg (get-label frame i))) (setf avg (/ avg cnt)) (do ((i start (1+ i))) ((>= i end)) (setf diff (- (get-label frame i) avg)) (incf mse (* diff diff))) (values mse cnt))) (defmethod swap-frame ((frame data-frame) i j) (with-slots (sindice) frame (swap-indices sindice i j))) (defmethod shuffle-frame ((frame data-frame) &optional (start 0) end) (with-slots (sindice) frame (shuffle sindice start end))) (defmethod sort-frame ((frame data-frame) j &optional (start 0) end) "sort data frame [start, end) by feature J" (with-slots (xmatrix sindice findice) frame (let ((jndx (nth j findice))) (setf sindice (sort-indices sindice (mcv xmatrix jndx) :start start :end end))))) (defmethod swap-feature ((frame data-frame) i j) (with-slots (findice) frame (swap-indices findice i j))) (defmethod shuffle-feature ((frame data-frame) &optional (start 0) end) (with-slots (findice) frame (shuffle findice start end)))
4,064
Common Lisp
.lisp
100
36.35
87
0.66371
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
9c5c338e0c0633203bc34c6de3d71e5e52b5cfdccf41c873d531cd0cb8e72c37
17,395
[ -1 ]
17,396
cl-ml.asd
jnjcc_cl-ml/cl-ml.asd
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (asdf:defsystem #:cl-ml :description "Machine Learning in Common Lisp" :version "0.1.0" :author "jnjcc at live.com" :licence "GPL" :serial t :components ((:module "probs" :components ((:file "packages") (:file "precision") (:file "bins") (:file "stats") ;; parametric probability distributions (:file "paramdist") (:file "randoms") (:file "indices") (:file "combination") (:file "shuffle") (:file "sampling"))) (:module "linalg" :components ((:file "packages") (:file "sim-smatrix") (:file "sim-dense") (:file "sim-transpose") (:file "sim-view") (:file "sim-diagview") (:file "sim-access") (:file "sim-transform") (:file "sim-operation") (:file "sim-indirect") (:file "sim-stats") (:file "sim-bidiagonal") (:file "sim-hessenberg") (:file "sim-qr") (:file "sim-svd"))) (:module "algo" :components ((:file "packages") (:file "string") (:file "kmp") (:file "binary-tree") (:file "stack") (:file "queue") (:file "huffman") )) (:module "graph" :components ((:file "packages") (:file "sim-base") (:file "sim-graph"))) (:module "io" :components ((:file "packages") (:file "sim-char") (:file "sim-lex") (:file "sim-synt") (:file "sim-file") (:file "sim-example") (:file "sim-matrix") (:file "sim-graph"))) (:file "packages") (:module "base" :components ((:file "estimator") (:file "transformer") (:file "dframe") (:file "numeric"))) (:module "preprocess" :components ((:file "scaler") (:file "polynomial") (:file "onehot") (:file "label"))) (:module "metrics" :components ((:file "cost") (:file "classifier") (:file "regressor") (:file "cluster"))) (:module "linear" :components ((:file "regression") (:file "sgd") (:file "logistic") (:file "svm") (:file "linsvc") (:file "linsvr") (:file "ksvc") (:file "ksvr"))) (:module "trees" :components ((:file "dtcrite") (:file "xgframe") (:file "xgcrite") (:file "dtree") (:file "cart") (:file "xgcart") (:file "forest") (:file "gbloss") (:file "xgloss") (:file "gbtree") (:file "xgboost"))) (:module "neural" :components ((:file "activations") (:file "losses") (:file "mlp"))) ;;; Unsupervised Learning (:module "cluster" :components ((:file "kmeans") (:file "dbscan") )) (:module "pgm" :components ((:file "gaussian") (:file "gmm"))))) (asdf:defsystem #:cl-ml-test :description "cl-ml test suite" :version "0.1.0" :author "jnjcc at live.com" :licence "GPL" :depends-on (#:cl-ml #:lisp-unit) :serial t :components ((:module "test" :components ((:file "packages") (:file "common") (:file "dataset") (:file "linalg-test") (:file "algo-test") (:file "graph-test") (:file "prepro-test") (:file "metrics-test") (:file "linear-test") (:file "dtree-test") (:file "forest-test") (:file "gbtree-test") (:file "xgboost-test") (:file "kmeans-test") (:file "mixture-test") (:file "neural-test") (:file "tests")))))
6,603
Common Lisp
.asd
132
20.287879
76
0.276086
jnjcc/cl-ml
3
0
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
f79d1d1eb1fb8a758e7792565d86a41e782955920b70badf887645fa33c0097c
17,396
[ -1 ]
17,511
pseudo-print.lisp
eschulte_pseudo-print/pseudo-print.lisp
;;; pseudo-print.lisp --- print lisp as pseudo-code ;; Copyright (C) Eric Schulte 2013 ;; Licensed under the Gnu Public License Version 3 or later ;;; Commentary ;; Use `with-pseudo-printer' to print lisp code as pseudo code using ;; the normal printing facilities. E.g., ;; ;; PSEUDO-PRINT> (with-pseudo-pprinter ;; (pprint '(if (> a b) (+ a b c) 3/4))) ;; ;; If (A > B) Then ;; (A + B + C) ;; Else ;; 3/4 ;; EndIf ;; ;; PSEUDO-PRINT> (with-pseudo-pprinter ;; (pprint '(DEFUN EUCLIDS-GCD (A B) ;; (IF (= A 0) ;; B ;; (DO () ;; ((= B 0) A) ;; (IF (> A B) ;; (SETF A (- A B)) ;; (SETF B (- B A)))))))) ;; ;; Function: EUCLIDS-GCD (A, B) ;; If (A ≡ 0) Then ;; B ;; Else ;; Do ;; If (A > B) Then ;; A <- (A - B) ;; Else ;; B <- (B - A) ;; EndIf ;; Until (B ≡ 0) ;; A ;; EndIf ;; EndFunction ;; ;; Customize using the `pseudo-pprinters' variable. ;; ;; see http://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node253.html ;;; Code: (in-package :pseudo-print) (eval-when (:compile-toplevel :load-toplevel :execute) (enable-curry-compose-reader-macros)) (defun if-print (s r colon? atsign?) (declare (ignorable colon? atsign?)) (if (fourth r) (format s "~:<If~; ~W Then~:@_~2I~W~-2I~ ~:@_Else~0I~:@_~W~-2I~:@_~;EndIf~:>" (cdr r)) (format s "~:<If~; ~W Then~:@_~2I~W~-2I~:@_~;EndIf~:>" (cdr r)))) (defun when-print (s r colon? atsign?) (declare (ignorable colon? atsign?)) (format s "~:<Wh~;en ~W Do~:@_~2I~W~-2I~:@_~;EndWhen~:>" (cdr r))) (defvar infix-translations '((equalp . "≡") (equal . "≡") (eql . "≡") (eq . "≡") (= . "≡") (append . "++")) "Alist used to hold different names for infix functions.") (defun infix-print (s r colon? atsign?) (declare (ignorable colon? atsign?)) (format s (format nil "~~{~~W~~^ ~a ~~}" (or (cdr (assoc (first r) infix-translations)) (first r))) (cdr r))) (defun defun-print (s r colon? atsign?) (declare (ignorable colon? atsign?)) (format s "~:<Fu~;nction: ~a (~{~a~^, ~})~:@_~2I~W~-2I~:@_~;EndFunction~:>" (cdr r))) (defun defmacro-print (s r colon? atsign?) (declare (ignorable colon? atsign?)) (format s "~:<Ma~;cro: ~a (~{~a~^, ~})~:@_~2I~W~-2I~:@_~;EndMacro~:>" (cdr r))) (defun set-print (s r colon? atsign?) (declare (ignorable colon? atsign?)) (format s "~{~{~W <- ~W~}~^~:@_~}" (loop :for i :from 0 :by 2 :below (length (cdr r)) :for j :from 1 :by 2 :below (length (cdr r)) :collect (list (nth i (cdr r)) (nth j (cdr r)))))) (defun do-print (s r colon? atsign?) (declare (ignorable colon? atsign?)) (let ((vars (second r)) (until (first (third r))) (to-return (second (third r))) (body (fourth r))) (if until (format s "~:<Do~;~a ~:@_~2I~W~-2I~:@_Until ~W~;~:>" (list (if vars " TODO: VARIABLE INITIALIZATION" "") body until)) (format s "~:<Do~;~a ~:@_~2I~W~-2I~:@_~;EndDo~:>" (list (if vars " TODO: VARIABLE INITIALIZATION" "") body))) (when to-return (format s "~:@_~W" to-return)))) (defun let-print (s r colon? atsign?) (declare (ignorable colon? atsign?)) (format s "~:<~;~W~^ ~:<~;~@{~:<~;~@{~W~^ <- ~_~}~;~:>~^, ~:_~}~; in~:>~ ~1I~@{~^ ~_~W~}~;~:>" r)) (defun flet-print (s r colon? atsign?) (declare (ignorable colon? atsign?)) (format s "~:<~;let~^ ~:<~;~@{~:<~;~@{~W~^ <- ~_~}~;~:>~^, ~:_~}~; in~:>~ ~1I~@{~^ ~_~W~}~;~:>" (cons (mapcar (lambda (f) (list (car f) (append (list 'defun (car f)) (cdr f))) ) (cadr r)) (cddr r)))) (defun map-print (s r colon? atsign?) (declare (ignorable colon? atsign?)) (let ((collection-word (case (car r) (mapc "Do") (mapcar "Collect") (mapcan "Append")))) (format s "~:<Fo~;r ~{~W~^, ~} in ~W ~a ~:_~ ~2I~{~W~^ ~_~} ~-2I~_~;EndFor~:>" (if (listp (second (second r))) (list (second (second r)) (third r) collection-word (cddr (second r))) (list (list 'element) (third r) collection-word (list (list (second (second r)) 'element))))))) (defun list-print (s r colon? atsign?) (declare (ignorable colon? atsign?)) (format s "[~{~W~^, ~_~}]~_" (cdr r))) (defun prog1-print (s r colon? atsign?) (declare (ignorable colon? atsign?)) (format s "~:<Re~;turn ~W After~:@_~2I~@{~W~^ ~_~}~-2I~@:_~;EndAfter~:>" (cdr r))) (defun loop-print (s r colon? atsign?) (declare (ignorable colon? atsign?)) (format s "~:<Lo~;op ~2I~@{~W~^ ~_~}~-2I~@:_~;EndLoop~:>" (cdr r))) (defun destructuring-bind-print (s r colon? atsign?) (declare (ignorable colon? atsign?)) (format s "~:<~;Let~^ ~W <- ~W in~1I~@{~^ ~_~W~}~;~:>" (cdr r))) (defun generic-function-print (s r colon? atsign?) (declare (ignorable colon? atsign?)) (format s "~:<~;~W(~{~W~^, ~})~;~:>" (list (car r) (cdr r)))) (defvar pseudo-pprinters '((:if-print (cons (and symbol (eql if)))) (:when-print (cons (and symbol (eql when)))) (:set-print (cons (and symbol (member set setq setf)))) (:defun-print (cons (and symbol (eql defun)))) (:defmacro-print (cons (and symbol (eql defmacro)))) (:infix-print (cons (and symbol (member > < >= <= = + - * / append equalp equal eql eq)))) (:do-print (cons (and symbol (eql do)))) (:let-print (cons (and symbol (eql let)))) (:flet-print (cons (and symbol (member flet labels)))) (:map-print (cons (and symbol (member mapc mapcar mapcan)))) (:list-print (cons (and symbol (eql list)))) (:prog1-print (cons (and symbol (eql prog1)))) (:loop-print (cons (and symbol (eql loop)))) (:destructuring-bind-print (cons (and symbol (eql destructuring-bind))))) "List of pseudo-printer functions.") (defmacro with-pseudo-pprinter (&rest body) (let ((orig-tab (gensym))) `(let ((,orig-tab (copy-pprint-dispatch *print-pprint-dispatch*))) (unwind-protect (progn (setq *print-pprint-dispatch* (copy-pprint-dispatch nil)) ,@(mapcar (lambda (pair) `(set-pprint-dispatch ',(second pair) (formatter ,(format nil "~~/pseudo-print::~a/" (symbol-name (first pair)))))) pseudo-pprinters) ,@body) ;; restore original value of pprinter (setq *print-pprint-dispatch* ,orig-tab)))))
7,464
Common Lisp
.lisp
182
32.989011
80
0.465415
eschulte/pseudo-print
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
8fd00abe631e2648721eb5cb65d9f3850577d82245824af85caf86a89c8349b0
17,511
[ -1 ]
17,512
pseudo-print.asd
eschulte_pseudo-print/pseudo-print.asd
(defsystem :pseudo-print :description "print lisp as pseudo-code" :version "0.0.0" :author ("Eric Schulte <[email protected]>") :licence "GPL V3" :depends-on (alexandria curry-compose-reader-macros) :components ((:file "package") (:file "pseudo-print" :depends-on ("package"))))
298
Common Lisp
.asd
8
34.5
69
0.706897
eschulte/pseudo-print
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
081e8029341d553cf5686b6df8f34906f5cdadf96ca5f1b31281b782d0f74a94
17,512
[ -1 ]
17,529
chordinator.lisp
rheaplex_rheart/chordinator/chordinator.lisp
;; chordinator.lisp - Colour chord generation ;; Copyright Rhea Myers 2007 ;; ;; 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/>. ;; Types and default values for keywords??? ;; Min & max bounds for saturation & brightness?value ;; Gamut for inkjet? ;; Tween colours, esp. complements? ;; For colour: plane (fore/mid/back/etc), ;; object (ground/table/tree), ;; group (edges/top/legs/trunk/branches), ;; element (branch1..20/leg1..4/leaf1..200) ;; So a red pot in the blue distance will need to compose the plane, ;; object and element colour generators (defvar acceptible-value-deviation 0.1) (defclass colour () ((hue :accessor hue :initform 1.0 :initarg :hue :documentation "The colour-wheel hue of the colour.") (saturation :accessor saturation :initform 1.0 :initarg :saturation :documentation "The saturation of the colour.") (brightness :accessor brightness :initform 1.0 :initarg :brightness :documentation "The brightness (HSV) of the colour.")) (:documentation "A colour")) (defmethod combined-value ((col colour)) "Get the value 0.0..1.0 by combining brightness and saturation." (/ (+ (brightness col) (- 1.0 (saturation col))) 2.0)) ;; Change to (write) methods (defmethod dump ((col colour)) (format t "Colour hue: ~a saturation: ~a brightness ~a" (hue col) (saturation col) (brightness col))) (defmethod dump (cols) (dolist (col cols) (dump col) (format t "~%"))) (defmethod fixed-generator (val) "Make a function to always return the same value." (lambda () val)) (defmethod random-generator ((from float) (to float)) "make a function to generate random numbers between from and to." (let ((base (min from to)) (range (abs (- to from)))) (lambda () (+ base (random range))))) (defmethod step-generator ((from float) (to float) (steps integer)) "Make a function to return a value that steps from from to to in steps steps." (let ((step (/ (abs (- to from)) steps)) (i 0)) (lambda () (let ((current-value (+ (* i step) from))) (incf i) current-value)))) (defmethod colour-generator (hue-fun saturation-fun brightness-fun) "Make a function to make a new instance of colour." (lambda () (make-instance 'colour :hue (funcall hue-fun) :saturation (funcall saturation-fun) :brightness (funcall brightness-fun)))) (defmethod random-colour-generator (&key (min-hue 0.0) (max-hue 1.0) (min-saturation 0.0) (max-saturation 1.0) (min-brightness 0.0) (max-brightness 1.0)) "Make a function to make a random colour." (colour-generator (random-generator min-hue max-hue) (random-generator min-saturation max-saturation) (random-generator min-brightness max-brightness))) (defmethod n-random-colours ((n integer) &key (min-hue 0.0) (max-hue 1.0) (min-saturation 0.0) (max-saturation 1.0) (min-brightness 0.0) (max-brightness 1.0)) "Make a list of n random colours." (let ((generate (random-colour-generator :min-hue min-hue :max-hue max-hue :min-saturation min-saturation :max-saturation max-saturation :min-brightness min-brightness :max-brightness max-brightness))) (loop repeat n collect (funcall generate)))) (defmethod hue-step-colour-generator ((n integer) &key (min-hue 0.0) (max-hue 1.0) (min-saturation 0.0) (max-saturation 1.0) (min-brightness 0.0) (max-brightness 1.0)) "Make a function to make colours with stepped hue, random sat / brightness." (colour-generator (step-generator min-hue max-hue n) (random-generator min-saturation max-saturation) (random-generator min-brightness max-brightness))) (defmethod n-hue-step-colours ((n integer) &key (min-hue 0.0) (max-hue 1.0) (min-saturation 0.0) (max-saturation 1.0) (min-brightness 0.0) (max-brightness 1.0)) "Make a list of n colours equally space around hue, random sat / brightness." (let ((generate (hue-step-colour-generator n :min-hue min-hue :max-hue max-hue :min-saturation min-saturation :max-saturation max-saturation :min-brightness min-brightness :max-brightness max-brightness)) (i 0)) (loop repeat n collect (funcall generate) do (incf i)))) (defmethod n-hue-step-colours-start-offset ((n integer) &key (min-hue 0.0) (max-hue 1.0) (min-saturation 0.0) (max-saturation 1.0) (min-brightness 0.0) (max-brightness 1.0)) "Make a list of n colours equally space around hue, random sat / brightness." (let ((offset (random (- 1.0 (min (- 1.0 ;; Smaller distance from range to limit max-hue) min-hue))))) (n-hue-step-colours n :min-hue (+ min-hue offset) :max-hue (+ max-hue offset) :min-saturation min-saturation :max-saturation max-saturation :min-brightness min-brightness :max-brightness max-brightness))) ;; Random in bounds ;; Like step, but with each colour offset randomly from step with min gap ;; Additive series, use complements etc. but avoid already used colours (defmethod list-property-range (items key) (let ((lowest (funcall key (car items))) (highest (funcall key (car items))) (count 0)) (dolist (item items) (let ((val (funcall key item))) (if (> val highest) (setf highest val)) (if (< val lowest) (setf lowest val))) (incf count)) (values lowest highest (- highest lowest) count))) (defmethod colours-brightness-range (colours) "Get the range of brightness for the colours in the list." (list-property-range colours #'brightness)) (defmethod colours-value-range (colours) "Get the range of value for the colours in the list." (list-property-range colours #'combined-value)) (defmethod converge-value ((col colour) (value-target real)) "Get the colour as close as possible to the target value." nil) #| (let ((delta (- value-target (combined-value col)))) (when (> delta acceptible-value-deviation) ;; Try to change the brightness, but not too much ;; Avoid a change of > .2 if possible ;; If we'd have to change it too much, ;;change the saturation as well ;; If both > 0.2, change brightness most ;; Or something (when (> (delta (brightness col)) (setf (brightness col ) ) |# (defmethod dolist-index (items fun) "Iterate through items calling (fun item index-of-item) ." (let ((count 0)) (dolist (item items) (funcall fun item count) (incf count)))) (defmethod make-linearise-property (colours key) "Make a function which when called with a colour and index will set the colour's brightness to its linear position in the range from darkest to lightest." (multiple-value-bind (from to range steps) (list-property-range colours key) (declare (ignore to)) (let ((step (/ range steps))) (lambda (col i) (setf (slot-value col key) (+ from (* i step))))))) (defmethod linearise-brightness (colours) "Set each colour's brightness to its linear position in the range from darkest to lightest." (dolist-index colours (make-linearise-property colours 'brightness))) (defmethod linearise-saturation (colours) "Set each colour's saturation to its linear position in the range." (dolist-index colours (make-linearise-property colours 'saturation))) (defmethod make-linearise-value (colours) "Make a function which when called with a colour and index will set the colour's brightness to its linear position in the range from least to most saturated-and-bright." (multiple-value-bind (from to range count) (colours-value-range colours) (declare (ignore range)) (let ((step (/ (- to from) ;; Get the range in value-range? Yes. count))) (lambda (col i) (converge-value col (* i step)))))) (defmethod linearise-value (colours) "Make a function which when called with a colour and index will set the colour's brightness to its linear position in the range from least to most saturated-and-bright." (dolist-index colours (make-linearise-value colours))) (defmethod sort-by-brightness (colours) "Sort the colours from darkest to lightest." (stable-sort colours #'< :key #'brightness)) (defmethod sort-by-value (colours) "Sort the colours into ascending value (brightness + saturation)." (stable-sort colours #'< :key #'combined-value)) (defmethod hsb-to-rgb ((col colour)) "Convert the hue/saturation/brightness colour to RGB." (cond ((= (saturation col) 0.0) (values (brightness col) (brightness col) (brightness col))) ((= (brightness col) 0.0) (values (saturation col) (saturation col) (saturation col))) (t (let* ((s (saturation col)) (v (brightness col)) (j (* (hue col) 6.0)) (i (floor j)) (f (- j i)) (p (* v (- 1 s))) (q (* v (- 1 (* s f )))) (u (* v (- 1 (* s (- 1 f)))))) (case i ((0) (values v u p)) ((1) (values q v p)) ((2) (values p v u)) ((3) (values p q v)) ((4) (values u p v)) ((5) (values v p q))))))) (defmethod hue-weight ((col colour)) "Get the perceptual brightness weight for the hue." (case (floor (* (hue col) 5.0)) ((0) 0) ;; Red ((1) 0.2) ;; Yellow ((2) 0) ;; Green ((3) 0.1) ;; Cyan ((4) -0.1) ;; Blue ((5) -0.1))) ;; Magenta (defmethod difference ((a colour) (b colour)) "Decide how different two colours are. 0 .. approx 2.1" (+ (* (abs (- (hue a) (hue b))) 0.00028) (abs (- (saturation a) (saturation b))) (abs (- (brightness a) (brightness b))))) (defmethod value-difference ((a colour) (b colour)) "The difference in value between the two colours." (/ (+ (saturation a) (saturation b) (brightness a) (brightness b)) 4.0)) (defmethod different-value ((target float) (separation float) (wrap float)) "Make a value 0 .. wrap where value is < or > target +/- separation." (cond ;; Range is from 0 .. target - separation ((> (+ target separation) wrap) (random (- target separation))) ;; Range is from target + separation .. wrap ((< (- target separation) 0.0) (+ target separation (random (- wrap target separation)))) ;; Range is either of the above (t (mod (+ (+ target separation) (random (- wrap (* 2.0 separation)))) wrap)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Postscript ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defvar *ps-stream* t) (defmethod write-eps-header (width height &key (to *ps-stream*)) "Write the standard raw PostScript header." (format to "%!PS-Adobe-3.0 EPSF-3.0~%") (format to "%%BoundingBox: 0 0 ~a ~a~%" width height) (format to "/L {lineto} bind def~%/M {moveto} bind def~%")) (defmethod write-eps-footer (&key (to *ps-stream*)) "Write the standard (but optional PostScript footer" (format to "%%EOF~%")) (defmethod write-rgb (r g b &key (to *ps-stream*)) "Set the PostScript RGB colour value." (format to "~F ~F ~F setrgbcolor~%" r g b)) (defmethod write-rectfill (x y width height &key (to *ps-stream*)) "Draw a rectangle with the given co-ordinates and dimensions." (format to "~F ~F ~F ~F rectfill~%" x y width height)) (defmethod write-rectstroke (x y width height &key (to *ps-stream*)) "Draw a rectangle with the given co-ordinates and dimensions." (format to "~F ~F ~F ~F rectstroke~%" x y width height)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Colour chord (palette) generation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod write-colours ((name string) colours width height) "Write the drawing" (with-open-file (ps name :direction :output :if-exists :supersede) (write-eps-header width height :to ps) (let* ((count (length colours)) (step (/ width count)) (i 0)) (dolist (col colours) (multiple-value-bind (r g b) (hsb-to-rgb col) (write-rgb r g b :to ps)) (write-rectfill (* i step) 0 step height :to ps) (incf i))) (write-eps-footer :to ps))) (defmethod create-colours () "Sort by value, but adjust only brightness." (let* ((n (+ (random 8) 4)) (colours (sort-by-value (n-random-colours n)))) (linearise-brightness colours) (dump colours) (write-colours "./test.ps" colours 1000 200) #+openmcl (ccl::os-command (format nil "open ~a" "./test.ps")))) ;; random (num colours * min separation -> 1.0) = range, make & step ;; Light on dark ground, or dark on light ground? ;; Ensure separation of HSV axes independently ;; Choose the components of the chord equally spaced around the colour wheel ;; (change the spacing/start to have components in just part of the spectrum) ;; Or by additive sequences (so 4 colours random, separated, with 3 split comps) ;; (n cols random, w/ 1 or 2 or 4 adjacents) ;; Sort the chord by brightness ;; Divide the range from lightest to darkest into equal steps ;; Adjust each component to the brightness required by its sequence position ;; Or increase the saturation to get to the darkness/value ;; Get number of colours required. ;; Get the list of colours, chosen from equally around the colour wheel ;; with random brightness and saturation. ;; (Or: n times ;; generate starting point ;; choose colours around it additively) ;; Order by brightness. ;; Divide the range from lightest to darkness into equal steps. ;; Adjust each to the brightness required by its position in the sequence. ;; If too bright, darken and desaturate. ;; AARON used inks with set maximum darknesses and brightnesses (not sats) ;; So if
14,416
Common Lisp
.lisp
357
36.173669
171
0.662436
rheaplex/rheart
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
993bafac660097bdca8d98832dfcd2cd1b5db9d7eee0e9de4accbe8df79e008e
17,529
[ -1 ]
17,530
arc.lisp
rheaplex_rheart/draw-something/arc.lisp
;; arc.lisp - A 2D circle segment. ;; Copyright (C) 2006 Rhea Myers [email protected] ;; ;; This file is part of draw-something. ;; ;; draw-something 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. ;; ;; draw-something 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/>. ;;(in-package "DRAW-SOMETHING") (defclass arc () ((x :accessor x :type float :initform 0.0 :initarg :x :documentation "The x co-ordinate of the arc's circle's centre.") (y :accessor y :type float :initform 0.0 :initarg :y :documentation "The y co-ordinate of the arc's circle's centre.") (radius :accessor radius :type float :initform 0.0 :initarg :radius :documentation "The radius of the arc's circle.") (start-angle :accessor start-angle :initarg :from) (finish-angle :accessor finish-angle :initarg :to) (start-point :accessor start-point) (finish-point :accessor finish-point)) (:documentation "A simple circle.")) (defmethod arc-point-at-angle ((obj arc) theta) "Get the point on the circumference of the arc at theta. Doesn't check limits of arc." (multiple-value-bind (ax ay) (co-ordinates-at-angle obj theta) (make-instance 'point :x ax :y ay))) (defmethod initialize-instance :after ((instance arc) &rest args) "Make the from- and to- points from their angles." (declare (ignore args)) (setf (start-point instance) (arc-point-at-angle instance (start-angle instance))) (setf (finish-point instance) (arc-point-at-angle instance (finish-angle instance))) instance) (defmethod highest-leftmost-point ((a arc)) "The highest point of the arc." ;;FIXME (if (or (> (start-angle a) (* pi 1.5)) (< (finish-angle a) (* pi 1.5))) (highest-leftmost-of (start-point a) (finish-point a)) (make-instance 'point :x (x a) :y (+ (y a) (radius a))))) (defmethod distance ((p point) (a arc)) "Only calculates distance to outside of arc, more a slice distance." (let ((theta (angle-between-two-points-co-ordinates (x p) (y p) (x a) (y a)))) (if (and (> theta (start-angle a)) (< theta (finish-angle a))) (abs (- (distance-point-co-ordinates p (x a) (y a)) (radius a))) (distance-point-line p (start-point a) (finish-point a))))) (defmethod bounds ((a arc)) "The bounds of the arc." (make-instance 'rectangle :x 0.0 :y 0.0 :width 100.0 :height 100.0)) ;; Do point-to-angle && fit-curve-to-3-points
2,948
Common Lisp
.lisp
71
38.070423
80
0.687805
rheaplex/rheart
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
dcef581655838e4873ec534f65dc19270e3c9566fb4ae1206a07bc60c58976a1
17,530
[ -1 ]
17,531
package.lisp
rheaplex_rheart/draw-something/package.lisp
;; package.lisp - The main package for draw-something ;; Copyright (C) 2006 Rhea Myers [email protected] ;; ;; This file is part of draw-something. ;; ;; draw-something 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. ;; ;; draw-something 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/>. (in-package "CL-USER") (eval-when (:COMPILE-TOPLEVEL :LOAD-TOPLEVEL :EXECUTE) (defpackage DRAW-SOMETHING (:documentation "The draw-something package.") (:use common-lisp) (:export run generate-skeleton draw-something x y)))
1,038
Common Lisp
.lisp
24
41.791667
73
0.757157
rheaplex/rheart
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
d15929cc4328d24a4dd6a8fa4a061332939cf5a70f19b80f388d2f9ea5836c0d
17,531
[ -1 ]
17,532
figure.lisp
rheaplex_rheart/draw-something/figure.lisp
;; figure.lisp - A drawn figure. ;; Copyright (C) 2006 Rhea Myers [email protected] ;; ;; This file is part of draw-something. ;; ;; draw-something 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. ;; ;; draw-something 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/>. ;;(in-package "DRAW-SOMETHING") (defconstant min-forms 5) (defconstant max-forms 10) (defclass figure () ((forms :accessor forms :type vector :initform (make-vector 5) :initarg :forms :documentation "The forms of the figure.") (bounds :accessor bounds :type rectangle :initarg :bounds :documentation "The bounds of the figure.")) (:documentation "A figure drawn in the drawing.")) (defmethod make-figure-from-points ((points vector)) "Make a figure with a single polyline from the provided points." (advisory-message "Making figure.~%") (let ((fig (make-instance 'figure))) (vector-push-extend (make-form-from-points points) (forms fig)) fig)) (defmethod draw-figure ((fig figure)) "Draw the forms of a figure." (loop for form across (forms fig) do (advisory-message "Drawing figure.~%") do (draw-form form)))
1,664
Common Lisp
.lisp
43
36.046512
73
0.727554
rheaplex/rheart
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
9aaa7ea43ca8aa1925e0cadb3dd8ada7776d7f525b91cc64c0dfd481b627d27c
17,532
[ -1 ]
17,533
composition.lisp
rheaplex_rheart/draw-something/composition.lisp
;; composition.lisp - Generating an image with some kind of intent. ;; Copyright (C) 2006 Rhea Myers [email protected] ;; ;; This file is part of draw-something. ;; ;; draw-something 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. ;; ;; draw-something 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/>. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Generating the point population for the composition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod make-composition-points ((d drawing) count) "Generate the points on the image plane that the composition will use." (advisory-message (format nil "Making ~d composition points.~%" count)) (let* ((b (bounds d)) (corner-count (random 4)) (interior-count (random (- count corner-count))) (edge-count (- count interior-count corner-count))) (setf (composition-points d) (concatenate 'vector (random-points-at-rectangle-corners b corner-count) (random-points-on-rectangle b edge-count) (random-points-in-rectangle b interior-count))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Convex Hull ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod make-hull-figures (the-points count low-count high-count) "Make count hull figures. They may overlap or touch. Todo: prevent this." (advisory-message (format nil "Making ~d hull figure(s) for plane.~%" count)) (map-into (make-vector count) (lambda () (make-figure-from-points (points (convex-hull (choose-n-of (random-range low-count (min high-count (length the-points))) the-points))))))) (defconstant min-hulls-per-plane 1) (defconstant max-hulls-per-plane 4) (defconstant min-hull-points 3) (defconstant max-hull-points 12) (defmethod make-hull-figures-for-plane (points) "The plane population policy using hulls. " (make-hull-figures points (random-range min-hulls-per-plane max-hulls-per-plane) min-hull-points (min (length points) max-hull-points))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Polygons ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod make-polygon-figures (points count low-count high-count) "Make count polygon figures. They may overlap or touch. Todo: prevent this." (advisory-message (format nil "Making ~d polygon figure(s) for plane.~%" count)) (let ((polygons (make-vector count))) (map-into polygons (lambda () (make-figure-from-points (choose-n-of (random-range low-count high-count) points)))))) (defconstant min-polygons-per-plane 1) (defconstant max-polygons-per-plane 5) (defconstant min-polygon-points 3) (defconstant max-polygon-points 12) (defmethod make-polygon-figures-for-plane (points) "The plane population policy using polygons. " (make-polygon-figures points (random-range min-polygons-per-plane max-polygons-per-plane) min-polygon-points (min (length points) max-polygon-points))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Lines ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod make-line-figure (points) "Make a line figure using two of the points." (let ((p1p2 (choose-n-of 2 points))) (make-instance 'figure :forms (make-instance 'form :contents (make-instance 'line :from (first p1p2) :to (second p1p2)))))) (defmethod make-line-figures (points count) "Make count line figures. They may overlap or touch. Todo: ensure they don't." (advisory-message (format nil "Making ~d line figure(s) for plane.~%" count)) (let ((lines (make-vector count))) (map-into lines (lambda () (make-figure-from-points (choose-n-of 2 points)))))) (defconstant min-lines-per-plane 1) (defconstant max-lines-per-plane 8) (defmethod make-line-figures-for-plane (points) "The plane population policy using liness. " (make-line-figures points (random-range min-lines-per-plane (min (floor (/ (length points) 2.0)) max-lines-per-plane)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Points ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod make-point-figure (point) "Make a point figure." (make-instance 'figure :forms (make-instance 'form :contents point))) (defmethod make-point-figures (points count) "Make count point figures." (advisory-message (format nil "Making ~d point figure(s) for plane.~%" count)) (let ((source-points (choose-n-of count points)) (point-figures (make-vector count))) (loop for p across source-points do (vector-push-extend (make-figure-from-points (vector p)) point-figures)) point-figures)) (defconstant min-points-per-plane 1) (defconstant max-points-per-plane 12) (defmethod make-point-figures-for-plane (points) "The plane population policy using points. " (make-point-figures points (random-range min-points-per-plane (min (length points) max-points-per-plane)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Figure generation method selection ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defparameter figure-generation-method-list '(make-hull-figures-for-plane make-polygon-figures-for-plane make-line-figures-for-plane make-point-figures-for-plane)) (defmethod figure-generation-methods (count) (choose-n-of-ordered count figure-generation-method-list))
7,035
Common Lisp
.lisp
147
39.068027
80
0.541029
rheaplex/rheart
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
f79720cbdea84ca84c593044ee9deb693d854da4662e7f3615a4b3c89f058a70
17,533
[ -1 ]
17,534
line.lisp
rheaplex_rheart/draw-something/line.lisp
;; line.lisp - A 2D line Segment, and utilities on points and lines. ;; Copyright (C) 2006 Rhea Myers [email protected] ;; ;; This file is part of draw-something. ;; ;; draw-something 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. ;; ;; draw-something 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/>. ;;(in-package "DRAW-SOMETHING") (defclass line () ((from :accessor from :type point :initform (make-instance 'point) :initarg :from :documentation "The start of the line.") (to :accessor to :type point :initform (make-instance 'point) :initarg :to :documentation "The end of the line.")) (:documentation "A simple line (segment) between two points.")) ;; nearest_point_on_line ;; From "Crashing Into the New Year", ;; Jeff Lander, GD Magazine, Jan 1999. ;; From point t to line A = p1->p2, B is t -> p1, C is t ->p2, ;; n is nearest point on A to t ;; (p2 - p1) * (B o A) ;; n = p1 + ------------------- ;; (B o A) + (C o A) ;; [o is the dot product sign] ;; Note: Cull out-of-range points on the bounding circle of the ;; line for testing groups of lines to find closest. ;; This needs decomposing into smaller, more manageable and meaningful units (defmethod nearest-point-on-line ((p point) (l line)) ;;la lb) (nearest-point-on-line-points p (from l) (to l))) (defmethod nearest-point-on-line-points ((p point) (la point) (lb point)) (nearest-point-on-line-coordinates (x p) (y p) (x la) (y la) (x lb) (y lb))) (defmethod nearest-point-on-line-coordinates (xp yp xla yla xlb ylb) "Get the nearest point on a line" ;; Optimised to avoid point accessors (let ((dot-ta (+ (* (- xp xla) (- xlb xla)) (* (- yp yla) (- ylb yla))))) ;;(format t "~F%~%" dot-ta) (if (<= dot-ta 0.0) (make-instance 'point :x xla :y yla) ;; else (let ((dot-tb (+ (* (- xp xlb) (- xla xlb)) (* (- yp ylb) (- yla ylb))))) ;;(format t "~F%~%" dot-tb) (if (<= dot-tb 0.0) (make-instance 'point :x xlb :y ylb) ;; else (make-instance 'point :x (+ xla (/ (* (- xlb xla) dot-ta) (+ dot-ta dot-tb))) :y (+ yla (/ (* (- ylb yla) dot-ta) (+ dot-ta dot-tb))))))))) (defmethod distance ((p point) (l line)) "The distance between a point and a line." (distance p (nearest-point-on-line p l))) (defmethod distance-point-line ((p point) (from point) (to point)) "The distance between a point and a line." (distance p (nearest-point-on-line-points p from to))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Line-line intersection ;; http://astronomy.swin.edu.au/~pbourke/geometry/lineline2d/ ;; Returns the time where the second line intersects the first line ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod lines-intersect-co-ordinates (p1x p1y p2x p2y ;; First line p3x p3y p4x p4y);; Second line "Find whether the two lines, expressed as 8 co-ordinates, intersect." (let ((denominator (- (* (- p4y p3y) (- p2x p1x)) (* (- p4x p3x) (- p2y p1y))))) (if (= denominator 0.0) nil ;; Parallel lines (let ((ua (/ (- (* (- p4x p3x) (- p1y p3y)) (* (- p4y p3y) (- p1x p3x))) denominator)) (ub (/ (- (* (- p2x p1x) (- p1y p3y)) (* (- p2y p1y) (- p1x p3x))) denominator))) (if (and (>= ua 0.0) (<= ua 1.0) (>= ub 0.0) (<= ub 1.0)) ;; Intersection (or not) ua nil))))) (defmethod lines-intersect-points ((l1p1 point) (l1p2 point) (l2p1 point) (l2p2 point)) "Find whether the two lines, expressed as 4 points intersect." (lines-intersect-co-ordinates (x l1p1) (y l1p1) (x l1p2) (y l1p2) (x l2p1) (y l2p1) (x l2p2) (y l2p2))) (defmethod line-intersect-line-points ((l1 line) (l2p1 point) (l2p2 point)) "Find whether the two lines, the second expressed as 2 points intersect." (lines-intersect-points (from l1) (to l1) l2p1 l2p2)) (defmethod intersect ((l1 line) (l2 line)) "Find whether the two lines intersect." (lines-intersect-points (from l1) (to l1) (from l2) (to l2))) (defmethod line-at-t ((l line) (time real)) "Evaluate the line at t where 0<=t<=1 ." (make-instance 'point :x (* time (- (x (to l)) (x (from l)))) :y (* time (- (y (to l)) (y (from l)))))) (defmethod random-point-on-line ((l line)) "Generate a random point on a line" (line-at-t l (random 1.0))) (defmethod random-points-on-line ((l line) (count integer)) "Generate count points on line. These will not be in order." (loop for i below count collect (random-point-on-line l)))
5,269
Common Lisp
.lisp
130
36.646154
79
0.600429
rheaplex/rheart
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
d4d393b2def685c1654add6524e71e77e6a183cc3056f2d6f7d92a99d913b468
17,534
[ -1 ]
17,535
colouring-new.lisp
rheaplex_rheart/draw-something/colouring-new.lisp
;; colour-scheme.lisp - Colour scheme generation and application. ;; Copyright (C) 2006 Rhea Myers [email protected] ;; ;; This file is part of draw-something. ;; ;; draw-something 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. ;; ;; draw-something 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/>. ;; Acronyms: ;; lmh = low, medium, high ;; sv = saturation, value ;;(in-package "COLOUR-CELLS") (defconstant minimum-spec-probability 3) (defconstant maximum-spec-probability 9) (defconstant minimum-spec-count 2) (defconstant maximum-spec-count 3) (defparameter sv-spec-options '('ll 'lm 'lh 'ml 'mm 'mh 'hl 'hm 'hh)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; LMH - Low medium and high value ranges from 0.0..1.0 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defclass lmh-values () ((lows :type vector :initform (make-vector 7) :initarg :lows :accessor low-values) (mediums :type vector :initform (make-vector 7) :initarg :mediums :accessor medium-values) (highs :type vector :initform (make-vector 7) :initarg :highs :accessor high-values)) (:documentation "A range of values divided into low, medium and high values.")) (defun make-random-low-values (count medium-start) "Generate count random low values." (map-into (make-vector count) (lambda () (random-range 0.0 medium-start)))) (defun make-random-medium-values (count medium-start high-start) "Generate count random medium values." (map-into (make-vector count) (lambda () (random-range medium-start high-start)))) (defun make-random-high-values (count high-start) "Generate count random high values." (map-into (make-vector count) (lambda () (random-range high-start 1.0)))) (defmethod make-lmh (count medium-start high-start) "Make an lmh." (let* ((low-count (random-range 1 (- count 2))) (medium-count (random-range 1 (- count low-count 1))) (high-count (- count medium-count low-count))) (make-instance 'lmh-values :lows (make-random-low-values low-count medium-start) :mediums (make-random-medium-values medium-count medium-start high-start) :highs (make-random-high-values high-count high-start)))) (defmethod random-low-value ((lmh lmh-values)) "Randomly choose a value from the list of low values of the lmh." (choose-one-of (low-values lmh))) (defmethod random-medium-value ((lmh lmh-values)) "Randomly choose a value from the list of medium values of the lmh." (choose-one-of (medium-values lmh))) (defmethod random-high-value ((lmh lmh-values)) "Randomly choose a value from the list of medium values of the lmh." (choose-one-of (high-values lmh))) (defmethod random-lmh-value (lmh which) "Return a random low ('l), medium ('m) or high ('h) value based on which." (case which ('l (random-low-value lmh)) ('m (random-medium-value lmh)) ('h (random-high-value lmh)))) (defmethod print-lmh (lmh) (advisory-message "low: ") (loop for l across (low-values lmh) do (advisory-message (format nil "~a " l))) (advisory-message "~%medium: ") (loop for m across (medium-values lmh) do (advisory-message (format nil "~a " m))) (advisory-message "~%high: ") (loop for h across (high-values lmh) do (advisory-message (format nil "~a " h))) (advisory-message "~%")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Colour Scheme ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defclass colour-scheme () ((hues :type hash-table :initarg :hues :initform (make-hash-table) :accessor colour-scheme-hues) (saturations :type lmh-values :initarg :saturations :initform (make-instance 'lmh-values) :accessor colour-scheme-saturations) (values :type lmh-values :initarg :values :initform (make-instance 'lmh-values) :accessor colour-scheme-values)) (:documentation "The values describing a colour scheme.")) (defmethod print-colour-scheme (scheme) (advisory-message "Colour Scheme:~%") (advisory-message "hues:~%") (maphash (lambda (key value) (advisory-message (format nil "~a ~a " key value))) (colour-scheme-hues scheme)) (advisory-message "~%saturations:~%") (print-lmh (colour-scheme-saturations scheme)) (advisory-message "values:~%") (print-lmh (colour-scheme-values scheme))) (defmethod symbol-colour-scheme-hue (scheme hue-id) "Get the hue value from the scheme for a given id, eg :stem, :stalk." (gethash hue-id (colour-scheme-hues scheme))) (defmethod random-colour-scheme-saturation (scheme spec) "Choose a saturation from the range specified by spec." (random-lmh-value (colour-scheme-saturations scheme) spec)) (defmethod random-colour-scheme-value (scheme spec) "Choose a value from the range specified by spec." (random-lmh-value (colour-scheme-values scheme) spec)) (defmethod sv-spec-components (spec) "Return each half of the symbol specifying how to choose saturation & value." (case spec ('ll (values 'l 'l)) ('lm (values 'l 'm)) ('lh (values 'l 'h)) ('ml (values 'm 'l)) ('mm (values 'm 'm)) ('mh (values 'm 'h)) ('hl (values 'h 'l)) ('hm (values 'h 'm)) ('hh (values 'h 'h)))) (defmethod make-colour-by-sv-spec (scheme hue-id sv-spec) "Choose a colour for the hue id using the sv-spec eg 'lm, 'hh, 'ml." (multiple-value-bind (saturationspec valuespec) (sv-spec-components sv-spec) (make-instance 'colour :hue (symbol-colour-scheme-hue scheme hue-id) :saturation (random-colour-scheme-saturation scheme saturationspec) :brightness (random-colour-scheme-value scheme valuespec)))) ;; Generate additive colour range (defmethod make-hue-additive-series (hue-list) (let ((series (make-hash-table)) (hue-value (random 1.0))) (dolist (hue-symbol hue-list) (setf hue-value (mod (+ hue-value (random 0.3)) 1.0)) (setf (gethash hue-symbol series) hue-value)) series)) (defmethod make-colour-scheme (hue-list saturations values medium high) "Make a colour scheme for the saturation symbol list." (make-instance 'colour-scheme :hues (make-hue-additive-series hue-list) :saturations (make-lmh saturations medium high) :values (make-lmh values medium high))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Applying colour schemes ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defclass colour-scheme-applier () ((scheme :type colour-scheme :accessor applier-scheme :initarg :scheme) (count :type integer :initform 1 :accessor applier-count :documentation "How many objects this applier haas coloured.") (check :type integer :initform 5 :initarg :check :accessor applier-when-to-check :documentation "How often to check deviation.") ;; This one is more part of the scheme but is more convenient here (sv-chooser :initarg :sv-chooser :initform (lambda () 'll) :accessor applier-sv-chooser :documentation "The function to choose sv values.") (sv-probabilites :type hash-table :initform (make-hash-table) :initarg :sv-probabilities :accessor applier-probabilities :documentation "The probabilities of the chooser sv specs") (sv-occurrences :type hash-table :initform (make-hash-table) :accessor applier-occurences :documentation "How often each sv spec has been chosen.")) (:documentation "The data used in applying a colour scheme to an image.")) (defmethod set-applier-probabilities (applier spec-list) "Set the probabilites from a list of num/specs, and set occurences to zero" (let ((total-prob (float (prefs-range spec-list)))) (loop for prob in spec-list by #'cddr for spec in (cdr spec-list) by #'cddr do (setf (gethash (dequote spec) (applier-probabilities applier)) (/ prob total-prob)) do (setf (gethash (dequote spec) (applier-occurences applier)) 0)))) (defmethod set-applier-chooser (applier spec-list) "Make and set the chooser function for sv specs from the list." (setf (applier-sv-chooser applier) (prefs-list-lambda spec-list))) (defmethod set-applier-sv-spec (applier spec-list) "Configure the applier from the sv spec eg '(1 'hh 4 'ml 3 'lm)" (set-applier-chooser applier spec-list) (set-applier-probabilities applier spec-list)) ;; Change to being an :after initialize-instance method (defmethod make-colour-scheme-applier (scheme spec-list) "Make a colour scheme applier." (let ((applier (make-instance 'colour-scheme-applier :scheme scheme))) (set-applier-chooser applier spec-list) (set-applier-probabilities applier spec-list) applier)) (defmethod spec-probability-difference (applier spec) "Get the difference between the intended and actual occurence of a spec." (let* ((generation-count (float (applier-count applier))) (spec-count (gethash spec (applier-occurences applier))) (target (float (gethash spec (applier-probabilities applier)))) (current (/ spec-count generation-count)) (difference (- target current))) (advisory-message (format nil " ~a ~a ~,3F ~,3F ~,3F~%" spec spec-count target current difference) ) difference)) (defmethod most-deviant-spec (applier) "Find the spec that is being called the least compared to its probability." (let ((highest 0.0) (result nil)) (maphash #'(lambda (key val) (declare (ignore val)) (let ((difference (spec-probability-difference applier key))) (when (> difference highest) (setf highest difference) (setf result key)))) (applier-probabilities applier)) (advisory-message (format nil "~a~%" result)) result)) (defmethod increase-spec-count (applier spec) "Update the number of times a spec has been used." (incf (gethash spec (applier-occurences applier)))) (defmethod increase-applier-count (applier) "Increase the applier's count of objects it has been called for by 1." (incf (applier-count applier))) (defmethod update-applier-state (applier spec) "Call when you've applied colour to an object & are ready for the next one." (increase-spec-count applier spec) (increase-applier-count applier)) (defmethod applier-should-correct (applier) "Decide whether the applier should correct the spec probability error." (eq (mod (applier-count applier) (applier-when-to-check applier)) 0)) (defmethod applier-spec-choice (applier hue-id) "Choose the spec to be used." (if (applier-should-correct applier) (most-deviant-spec applier) (funcall (applier-sv-chooser applier)))) (defmethod choose-colour-for (applier hue-id) "Choose a colour from the scheme for the hue-id." (let* ((spec (applier-spec-choice applier hue-id)) (choice (make-colour-by-sv-spec (applier-scheme applier) hue-id spec))) (update-applier-state applier spec) choice)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; How to make and apply a colour scheme ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun chooser-spec () "Construct a list describing a random spec pref, eg (6 'll 3 'hm 2 'lh)." (loop for spec in (choose-n-of (random-range-inclusive minimum-spec-count maximum-spec-count) sv-spec-options) collect (random-range-inclusive minimum-spec-probability maximum-spec-probability) collect spec)) (defmethod colour-objects (drawing symbols) (let* ((scheme (make-colour-scheme symbols 7 7 .3 .6)) (sv-spec-list (chooser-spec)) (applier (make-colour-scheme-applier scheme sv-spec-list))) (advisory-message "Colouring forms.~%") (print-colour-scheme scheme) (advisory-message (format nil "sv-spec: ~a~%" sv-spec-list)) (setf (ground drawing) (choose-colour-for applier 'background)) (loop for plane across (planes drawing) do (loop for figure across (figures plane) do (loop for form across (forms figure) do (setf (fill-colour form) (choose-colour-for applier (object-symbol form))))))))
12,747
Common Lisp
.lisp
307
37.732899
79
0.675036
rheaplex/rheart
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
b8a50337f409118357f736ba4cd8c9226e7e0e3a75947bbcbdb0af374ff5e200
17,535
[ -1 ]
17,536
turtle.lisp
rheaplex_rheart/draw-something/turtle.lisp
;; turtle.lisp - A classic, L-system style computer graphics turtle. ;; Copyright (C) 2006 Rhea Myers [email protected] ;; ;; This file is part of draw-something. ;; ;; draw-something 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. ;; ;; draw-something 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/>. ;;(in-package "DRAW-SOMETHING") (defclass turtle-parameters () ((turn-step :accessor turn-step :initform 1.0 :initarg :turn-step :documentation "How many radians the turtle turns at a time.") (move-step :accessor move-step :initform 1.0 :initarg :move-step :documentation "How far the turtle moves each step.")) (:documentation "A set of parameters for turtle operations to use.")) (defclass turtle () ((location :accessor location :initform (make-instance 'point) :initarg :location :documentation "The turtle's current location.") (direction :accessor direction :initform 0.0 :initarg :direction :documentation "The heading, in radians anticlockwise.")) (:documentation "A classic computer graphics turtle plus randomness .")) (defmethod turn ((the-turtle turtle) amount) "Turn the turtle by the given amount in degrees," (setf (direction the-turtle) (+ (direction the-turtle) amount))) (defmethod left ((the-turtle turtle) amount) "Turn the turtle left by the given amount in degrees," (turn the-turtle (- amount))) (defmethod right ((the-turtle turtle) amount) "Turn the turtle left by the given amount in degrees," (turn the-turtle amount)) (defmethod next-point-x ((the-turtle turtle) amount) "The x co-ordinate of the next point the turtle would move forward to." (+ (x (location the-turtle)) (* amount (sin (direction the-turtle))))) (defmethod next-point-y ((the-turtle turtle) amount) "The y co-ordinate of the next point the turtle would move forward to." (+ (y (location the-turtle)) (* amount (cos (direction the-turtle))))) (defmethod next-point ((the-turtle turtle) amount) "The next point the turtle would move forward to." (make-instance 'point :x (next-point-x the-turtle amount) :y (next-point-y the-turtle amount))) (defmethod forward ((the-turtle turtle) amount) "Move the turtle forward the given distance at the turtle's current angle." (setf (location the-turtle) (next-point the-turtle amount))) (defmethod backward ((the-turtle turtle) amount) "Move the turtle backward the given distance at the turtle's current angle." (setf (location the-turtle) (next-point the-turtle (- amount))))
3,221
Common Lisp
.lisp
69
41.478261
78
0.696053
rheaplex/rheart
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
12b4ed53075bedb8b309eba5d73fa37df16a964d91b1239c3340b9d5f4617c8b
17,536
[ -1 ]
17,537
pen.lisp
rheaplex_rheart/draw-something/pen.lisp
;; pen.lisp - The pen to draw around skeletal forms with. ;; Copyright (C) 2007 Rhea Myers [email protected] ;; ;; This file is part of draw-something. ;; ;; draw-something 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. ;; ;; draw-something 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/>. (defclass pen-parameters (turtle-parameters) ((distance :accessor pen-distance :initarg :distance :documentation "How far fromt the skeleton to draw.") (distance-tolerance :accessor distance-tolerance :initarg :distance-tolerance :documentation "How far from the distance is tolerable.") (drift-probability :accessor drift-probability :initarg :drift-probability :documentation "How likely it is the pen will wobble.") (drift-range :accessor drift-range :initarg :drift-range :documentation "The +/- pen wobble range.")) (:documentation "A set of parameters for a pen to use.")) ;; Start with fixed values for tuning ;; Move to random ranges for production (defparameter plane-1-pen (make-instance 'pen-parameters :move-step 4.0 :distance 20.0 :distance-tolerance 5.0 :turn-step 0.1 :drift-probability 0.0 :drift-range 0.1)) (defparameter plane-2-pen (make-instance 'pen-parameters :move-step 2.0 :distance 10.0 :distance-tolerance 3.3 :turn-step 0.1 :drift-probability 0.0 :drift-range 0.1)) (defparameter plane-3-pen (make-instance 'pen-parameters :move-step 2.0 :distance 7.0 :distance-tolerance 2.0 :turn-step 0.1 :drift-probability 0.0 :drift-range 0.1)) (defparameter plane-4-pen (make-instance 'pen-parameters :move-step 2.0 :distance 5.0 :distance-tolerance 2.0 :turn-step 0.1 :drift-probability 0.0 :drift-range 0.1)) (defparameter plane-5-pen (make-instance 'pen-parameters :move-step 2.0 :distance 3.0 :distance-tolerance 1.0 :turn-step 0.1 :drift-probability 0.0 :drift-range 0.1)) (defparameter plane-6-pen (make-instance 'pen-parameters :move-step 2.0 :distance 2.0 :distance-tolerance 1.0 :turn-step 0.1 :drift-probability 0.0 :drift-range 0.1)) (defparameter plane-7-pen (make-instance 'pen-parameters :move-step 1.0 :distance 1.0 :distance-tolerance 0.2 :turn-step 0.1 :drift-probability 0.0 :drift-range 0.1)) (defparameter plane-pen-parameters (vector plane-1-pen plane-2-pen plane-3-pen plane-4-pen plane-5-pen plane-6-pen plane-7-pen)) (defmethod next-pen-distance ((skeleton-forms vector) (pen pen-parameters) (the-turtle turtle)) "How far the pen will be from the guide shape when it next moves forwards." (let ((dist most-positive-single-float) (p (next-point the-turtle (move-step pen) ))) (dovector (skel skeleton-forms) (let ((new-dist (distance p skel))) (when (< new-dist dist) (setf dist new-dist)))) dist)) (defmethod next-pen-too-close ((skeleton-forms vector) (pen pen-parameters) (the-turtle turtle)) "Will the pen move to be too close from the guide shape next time?" (< (random (distance-tolerance pen)) (- (next-pen-distance skeleton-forms pen the-turtle) (pen-distance pen)))) (defmethod next-pen-too-far ((skeleton-forms vector) (pen pen-parameters) (the-turtle turtle)) "Will the pen move to be too far from the guide shape next time?" (< (random (distance-tolerance pen)) (- (pen-distance pen) (next-pen-distance skeleton-forms pen the-turtle)))) (defmethod ensure-next-pen-far-enough ((skeleton-forms vector) (pen pen-parameters) (the-turtle turtle)) "If the pen would move too close next time, turn it left until it wouldn't." (loop while (next-pen-too-close skeleton-forms pen the-turtle) do (left the-turtle (random (turn-step pen))))) (defmethod ensure-next-pen-close-enough ((skeleton-forms vector) (pen pen-parameters) (the-turtle turtle)) "If the pen would move too far next time, turn it right until it wouldn't." (loop while (next-pen-too-far skeleton-forms pen the-turtle) do (right the-turtle (random (turn-step pen))))) (defmethod drift-pen-direction ((pen pen-parameters) (the-turtle turtle)) "Adjust the pen's direction to simulate human neurophysiological noise." (if (< (random 1.0) (drift-probability pen)) (turn the-turtle (random-range (- (drift-range pen)) (drift-range pen))))) (defmethod adjust-next-pen ((skeleton-forms vector) (pen pen-parameters) (the-turtle turtle)) "Drift or correct the pen's heading around the shape." (drift-pen-direction pen the-turtle) (ensure-next-pen-far-enough skeleton-forms pen the-turtle) (ensure-next-pen-close-enough skeleton-forms pen the-turtle))
6,359
Common Lisp
.lisp
139
35.870504
80
0.586907
rheaplex/rheart
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
1e6ed09f52ea6d91a41f9658b101ce7d05b4814d50c7b59be34b9dee0c4bf146
17,537
[ -1 ]
17,538
cell-matrix.lisp
rheaplex_rheart/draw-something/cell-matrix.lisp
;; cell-matrix.lisp - A picture cell matrix. ;; Copyright (C) 2006 Rhea Myers [email protected] ;; ;; This file is part of draw-something. ;; ;; draw-something 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. ;; ;; draw-something 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/>. ;;(in-package "DRAW-SOMETHING") ;; This version is much simpler than AARON: just a grid of figure references (defclass cell () ((figure :accessor figure :initform nil :documentation "The cell's figure.") (status :accessor status :initform 'unmarked :documentation "The cell's status.")) (:documentation "A cell in the matrix.")) (defconstant cell-size 1) (defmethod drawing-to-cell-x (x) "Convert a drawing x co-ordinate to a cell x co-ordinate." (floor (/ x cell-size))) (defmethod drawing-to-cell-y (y) "Convert a drawing y co-ordinate to a cell y co-ordinate." (floor (/ y cell-size))) (defmethod make-cell-matrix (the-drawing) "Make the picture cell matrix for the drawing" (let ((matrix-width (ceiling (/ (width (bounds the-drawing)) cell-size))) (matrix-height (ceiling (/ (height (bounds the-drawing)) cell-size)))) (setf (cell-matrix the-drawing) (make-array (list matrix-height matrix-width) :element-type 'cell)) (dotimes (i matrix-height) (dotimes (j matrix-width) (setf (aref (cell-matrix the-drawing) i j) (make-instance 'cell)))))) (defmethod apply-line (fun x0 y0 x1 y1) "Call fun along the bresenham line co-ordinates between the two points." ;;(declare (optimize speed 3)) (let ((steep (> (abs (- y1 y0)) (abs (- x1 x0))))) (when steep (rotatef x0 y0) (rotatef x1 y1)) (let* ((deltax (abs (- x1 - x0))) (deltay (abs (- y1 y0))) (error-value 0) (deltaerr deltay) (x x0) (y y0) (xstep (if (< x0 x1) 1 -1)) (ystep (if (< y0 y1) 1 -1)) (apply-fun (if steep (lambda (x y) (funcall fun y x)) (lambda (x y) (funcall fun x y))))) (declare (type integer deltax deltay error-value deltaerr x y xstep ystep)) (funcall apply-fun x y) (loop while (/= x x1) do (progn (setf x (+ x xstep)) (setf error-value (+ error-value deltaerr)) (when (> error-value deltax) (setf y (+ y ystep)) (setf error-value (- error-value deltax))) (funcall apply-fun x y)))))) (defmethod apply-rectangle-outline (fun x y width height &key ((:xstep xstep) 1) ((:ystep ystep) 1)) "Call fun at each co-ordinate pair along the outline of the rectangle." (let ((left x) (right (+ x width)) (bottom y) (top (+ y height))) (if (or (equal width 1) (equal height 1)) ;; If it's just a line, just draw a line (apply-line left bottom right top) (progn ;; Top line, (apply-line left top right top) ;; Right line, not overlapping top (apply-line right (- top 1) left bottom) ;; Bottom line, not overlapping right (apply-line (- right 1) bottom left bottom) ;; Left line, not overlapping bottom or top (apply-line left (+ 1 bottom) left (- 1 top)))))) (defmethod apply-rectangle-fill (fun x y width height &key ((:xstep xstep) 1) ((:ystep ystep) 1)) "Call fun at each co-ordinate pair in rectangle" (loop for v from y below (+ y height) by ystep do (loop for h from x below (+ x width) by xstep do (funcall fun h v)))) (defmethod apply-rectangle-fill-radial (fun x y width height &key ((:xstep xstep) 1) ((:ystep ystep) 1)) "Call fun at each co-ordinate pair radially in the square." (let ((xslop 0) (yslop 0)) ;; First pixel or line at centre ;; Lines go opposite way to rectangle outlines. Fix? (cond ((< height width) (progn (setf xslop (/ (- width height) 2)) (apply-line (- x xslop) y (+ x xslop 2) y))) ((> height width) (progn (setf yslop (/ (- height width) 2)) (apply-line x (- y yslop) x (+ y yslop)))) ((< height width) (progn (setf xslop (- width height)) (apply-line (- x (/ xslop 2) y (+ x (/ xslop 2)))))) ((equal height width) (funcall fun x y))) (loop for v from y below (+ y height) by ystep do (loop for h from x below (+ x width) by xstep do (apply-rectangle-outline fun (- x h xslop) (- y v yslop) (+ x h xslop) (+ y v yslop)))))) (defmethod cell-figure ((cells array) x y) "Get the cell's figure." (figure (aref cells x y))) (defmethod cell-figure ((d drawing) x y) "Get the cell's figure." (cell-figure (cell-matrix d) (drawing-to-cell-x x) (drawing-to-cell-y y))) (defmethod set-cell-figure ((cells array) x y fig role) "Set the cell to the figure. x and y are in cell co-ordinates." (let ((the-cell (aref cells x y))) (setf (figure the-cell) fig) (setf (role the-cell) role))) (defmethod set-cell-figure ((d drawing) x y fig role) "Set the cell to the figure. x and y are in cell co-ordinates." (set-cell-figure (cell-matrix d) x y fig role)) (defmethod mark-polyline-outline-cells (cells polyline fig role) "Mark the cells that the polyline passes through." (let* ((pts (points polyline)) (numpts (length pts))) (cond ((= numpts 0) nil) ((= numpts 1) (set-cell-figure cells (drawing-to-cell-x (x (first pts))) (drawing-to-cell-y (y (first pts))) fig role)) (t (let ((fun (lambda (x y) (set-cell-figure cells x y fig role)))) (dotimes (i (- numpts 1)) (let ((p1 (aref pts i)) (p2 (aref pts (mod (1+ i) numpts)))) (apply-line fun (drawing-to-cell-x (x p1)) (drawing-to-cell-y (y p1)) (drawing-to-cell-x (x p2)) (drawing-to-cell-y (y p2)))))))))) (defmethod scanline-intersections (cells fig x width y) "Find where the scanline intersects the outline." (let ((intersections (make-vector 4))) (do ((i x (1+ i))) ((> i (+ x width))) (when (equal (aref cells (+ x i) y) fig) (vector-push-extend i intersections))) intersections)) (defmethod fill-scanline-intersections (cells fig role intersections y) "If there is more than one intersection, fill between the pairs. This is OK as we are filling closed outlines, not open self-intersecters." (when (> (length intersections) 1) (loop for i from 0 by 2 below (length intersections) do (apply-line (lambda (x y) (set-cell-figure cells x y fig role)) (nth i intersections) y (nth (1+ i) intersections) y)))) (defmethod mark-polyline-fill-cells (cells poly fig role) "Flood fill inside the figure." (let ((poly-x (drawing-to-cell-x (x (bounds poly)))) (poly-y (drawing-to-cell-y (y (bounds poly)))) (poly-width (drawing-to-cell-x (width (bounds poly)))) (poly-height (drawing-to-cell-x (height (bounds poly))))) (do ((i poly-y (1+ i))) ((> i (+ poly-y poly-height))) (fill-scanline-intersections cells fig role (scanline-intersections cells fig poly-x poly-width i))))) (defmethod colour-for-cell (cells x y) "Get the colour for a cell." (fill-colour (cell-figure (cell cells x y)))) (defun write-cells-ppm (cells filename comment) "Write the drawing to a ppm file." (advisory-message (format nil "Writing drawing to file ~a .~%" filename)) (with-open-file (stream filename :direction :output :if-exists :supersede :element-type '(unsigned-byte 8)) (let ((x (array-dimension cells 1)) (y (array-dimension cells 0))) (format stream "P6~%#~A~%~D ~D~%~d~%" comment x y 255) (dotimes (i y) (dotimes (j x) (multiple-value-bind (r g b) (hsb-to-rgb (colour-for-cell cells i j)) (write-byte (normal-to-255 r) stream) (write-byte (normal-to-255 g) stream) (write-byte (normal-to-255 b) stream)))) (namestring stream))))
9,289
Common Lisp
.lisp
212
34.561321
78
0.573763
rheaplex/rheart
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
0e5605a0990c04e846b2c33cd6ecc44dd8a7d2b1e57788f838d49aa7930fcde9
17,538
[ -1 ]
17,539
utilities.lisp
rheaplex_rheart/draw-something/utilities.lisp
;; utilities.lisp - Various utilities. ;; Copyright (C) 2006 Rhea Myers [email protected] ;; ;; This file is part of draw-something. ;; ;; draw-something 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. ;; ;; draw-something 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/>. ;;(in-package "DRAW-SOMETHING") (defvar *print-advisories* t) (defvar *print-debugs* t) (defmethod debug-message (msg) "Write the message to the error stream, not to standard output." (when *print-debugs* (format *debug-io* "~A~%" msg) (finish-output *debug-io*))) (defmethod advisory-message (msg) "Write the message to the error stream, not to standard output. No newline." (when *print-advisories* (format *debug-io* msg) (finish-output *debug-io*))) (defmethod make-vector (initial-size) "Make a stretchy vector." (make-array initial-size :adjustable t :fill-pointer 0)) (defmacro while (test &rest body) `(do () ((not ,test)) ,@body)) (defmacro until (test &rest body) `(do () (,test) ,@body)) (defmacro dovector ((var vec) &rest body) `(loop for ,var across ,vec do (progn ,@body))) (defmethod dequote (item) "Remove the quote from a symbol, returning the symbol." (cadr item)) (defmethod random-number (a) "The built in random doesn't like 0.0 ." (if (= a 0) a (random a))) (defmethod random-range (a b) "Make a random number from a to below b." (let ((range (- b a))) (if (= range 0) a (+ (random range) a)))) (defmethod random-range-inclusive ((a integer) (b integer)) "Make a random number from a to below b." (let ((range (+ (- b a) 1))) (if (= range 0) a (+ (random range) a)))) (defmethod choose-one-of ((possibilities list)) "Choose one or none of the options." (nth (random (length possibilities)) possibilities)) (defmethod choose-one-of ((possibilities vector)) "Choose one or none of the options." (aref possibilities (random (length possibilities)))) (defmethod maybe-choose-one-of (possibilities) "Choose one or none of the options." (when (< (random 1.0) 0.5) (choose-one-of possibilities))) (defmethod maybe-choose-some-of (possibilities probability) "Choose none or more possibilities when random 1.0 < probability for it." (loop for item in possibilities when (< (random 1.0) probability) collect item)) (defmethod choose-n-of ((n integer) (choice-list list)) "Choose n different entries from choice-list." (assert (<= n (length choice-list))) (let ((choices choice-list) (chosen '())) (dotimes (i n) (let ((choice (choose-one-of choices))) (setf chosen (cons choice chosen)) (setf choices (remove choice choices)))) chosen)) (defmethod choose-n-of ((n integer) (choice-vector vector)) "Choose n different entries from choice-vector." (assert (<= n (length choice-vector))) (let ((choices choice-vector) (chosen (make-vector n))) (dotimes (i n) (let ((choice (choose-one-of choices))) (vector-push-extend choice chosen) (setf choices (remove choice choices)))) chosen)) (defun choose-n-of-ordered (n choice-list) "Choose n of the entries, and ensure they are in order." ;; Not very efficient at all (let ((choices (choose-n-of n choice-list))) (loop for i in choice-list when (member i choices) collect i))) (defun prefs-range (spec) "Get the total probability range of a prefs spec." (loop for prob in spec by #'cddr sum prob)) (defun prefs-cond (spec) "Make a cond to choose an option. eg (prefs 4 'a 4 'b 2 'c)" `(let ((i (random ,(prefs-range spec)))) (cond ,@(loop for prob in spec by #'cddr for val in (cdr spec) by #'cddr sum prob into prob-so-far collect `((< i ,prob-so-far) ,val))))) (defmacro prefs (&rest spec) "Make a prefs cond to choose an option. eg (prefs 4 'a 4 'b 2 'c)" (prefs-cond spec)) (defmacro prefs-list (spec) "Make a prefs cond to choose an option. eg (prefs-list '(4 'a 3 'b))" (prefs-cond spec)) (defun prefs-lambda (&rest spec) "Make a lambda to choose an option. eg (prefs-lambda 4 'a 4 'b 2 'c)" (eval `(lambda () ,(prefs-cond spec)))) (defun prefs-list-lambda (spec) "Make a lambda to choose an option. eg (prefs-list-lambda '(4 'a 3 'b))" (eval `(lambda () ,(prefs-cond spec)))) (defconstant normal-to-255-multiplier (/ 1.0 256)) (defmethod normal-to-255 (normal) "Convert a 0..1 value to a 0..255 value." (* normal normal-to-255-multiplier)) (defmacro make-hash (&rest key-values) (let ((hash (gensym)) (key-value-list (gensym)) (current-pair (gensym))) `(let ((,key-value-list ,key-values) (,hash (make-hash-table))) (dolist (,current-pair ,key-values) (setf (gethash (car ,current-pair)) (cdr ,current-pair))) ,hash))) (defmacro with-gensyms ((&rest names) &body body) "From Peter Siebel's Practical Common Lisp" `(let ,(loop for n in names collect `(,n (gensym))) ,@body))
5,623
Common Lisp
.lisp
152
32.717105
78
0.660849
rheaplex/rheart
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
bd59177b6b7937e550679ed24d05e4f453a8c536187985ba1112bf1acbc52104
17,539
[ -1 ]
17,540
load.lisp
rheaplex_rheart/draw-something/load.lisp
;; load.lisp - Load the asdf system. ;; Copyright (C) 2004 Rhea Myers [email protected] ;; ;; This file is part of draw-something. ;; ;; draw-something 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. ;; ;; draw-something 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/>. ;;(load "draw-something.asd") ;;(asdf:operate 'asdf:load-op :draw-something) (load "utilities.lisp") (load "geometry.lisp") (load "point.lisp") (load "line.lisp") (load "circle.lisp") (load "arc.lisp") (load "rectangle.lisp") (load "polyline.lisp") (load "colour.lisp") (load "colouring-new.lisp") (load "turtle.lisp") (load "pen.lisp") (load "form.lisp") (load "figure.lisp") (load "drawing.lisp") ;;(load "cell-matrix") ;;(load "find-space") (load "composition.lisp") (load "plane.lisp") (load "postscript.lisp") (load "svg.lisp") (load "draw-something.lisp")
1,354
Common Lisp
.lisp
41
31.902439
73
0.733028
rheaplex/rheart
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
80f00446f6a4b44e062140aacbfb774a672a9bd2cc452a47c82380e6922f2983
17,540
[ -1 ]
17,541
draw-something.lisp
rheaplex_rheart/draw-something/draw-something.lisp
;; draw-something.lisp - The main lifecycle code for draw-something. ;; Copyright (C) 2006 Rhea Myers [email protected] ;; ;; This file is part of draw-something. ;; ;; draw-something 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. ;; ;; draw-something 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/>. ;;(in-package "DRAW-SOMETHING") (defparameter object-symbol-choices '(leaf vein blade branch flower tendril)) (defparameter all-object-symbols (cons 'background object-symbol-choices)) (defmethod object-symbol (obj) (choose-one-of object-symbol-choices)) (defmethod draw-something () "Make the drawing data structures and create the image." (let ((the-drawing (make-drawing))) (make-composition-points the-drawing (random-range 8 42)) (make-planes the-drawing (number-of-planes)) (make-planes-skeletons the-drawing) (draw-planes-figures the-drawing) (colour-objects the-drawing all-object-symbols) the-drawing)) (defmethod run () "The main method that generates the drawing and writes it to file." (advisory-message "Starting draw-something.~%") (setf *random-state* (make-random-state t)) ;;(format t "Random state: ~a.~%" (write-to-string *random-state*)) (let ((the-drawing (draw-something))) (advisory-message "Finished drawing.~%") (let ((filepath (write-svg the-drawing))) (advisory-message "Finished draw-something.~%") filepath)))
1,929
Common Lisp
.lisp
43
42.232558
73
0.73883
rheaplex/rheart
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
31afb948a27a577b66de0c4d56506f97e22ca81fd1eea4089a84f8cc00cbc26a
17,541
[ -1 ]
17,542
drawing.lisp
rheaplex_rheart/draw-something/drawing.lisp
;; drawing.lisp - A drawing. ;; Copyright (C) 2006 Rhea Myers [email protected] ;; ;; This file is part of draw-something. ;; ;; draw-something 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. ;; ;; draw-something 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/>. ;;(in-package "DRAW-SOMETHING") (defconstant min-drawing-size 200.0) (defconstant max-drawing-size 600.0) (defclass drawing () ((bounds :accessor bounds :type rectangle :initarg :bounds :documentation "The dimensions of the drawing.") (planes :accessor planes :type vector :initarg :planes :initform (make-vector 10) :documentation "The planes of the drawing.") (ground :accessor ground :type colour :initarg :ground :initform (random-colour) :documentation "The flat background colour of the drawing.") (composition-points :accessor composition-points :type vector :initarg :composition-points :initform (make-vector 10) :documentation "The points for the composition")) (:documentation "A drawing in progress.")) ;; Change to width or height being max and other being random range (defmethod make-drawing-bounds () "Make a bounds rectangle for a drawing." (make-instance 'rectangle :x 0.0 :y 0.0 :width (random-range min-drawing-size max-drawing-size) :height (random-range min-drawing-size max-drawing-size))) (defmethod make-drawing () "Make a drawing, ready to be started." (let ((the-drawing (make-instance 'drawing :bounds (make-drawing-bounds)))) (advisory-message (format nil "Making drawing. Size: ~dx~d.~%" (floor (width (bounds the-drawing))) (floor (height (bounds the-drawing))))) the-drawing)) (defvar save-directory "../draw-something-drawings/") (defmethod generate-filename (&optional (suffix ".eps")) "Make a unique filename for the drawing, based on the current date & time." (multiple-value-bind (seconds minutes hours date month year) (decode-universal-time (get-universal-time)) (format nil "~a~a-~2,,,'0@A~2,,,'0@A~2,,,'0@A-~2,,,'0@A~2,,,'0@A~2,,,'0@A~a" save-directory "drawing" year month date hours minutes seconds suffix)))
2,762
Common Lisp
.lisp
66
37.348485
77
0.697657
rheaplex/rheart
3
1
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
b2f86197cead6a2b55a89a916fcb805d5d4d83d149386ccef933686b83c8308d
17,542
[ -1 ]