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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
11,979 | slime-repl-ansi-color.el | noloop_cacau/contrib/slime-repl-ansi-color/slime-repl-ansi-color.el | (require 'ansi-color)
(define-slime-contrib slime-presentations
"Turn on ANSI colors in REPL output"
(:authors "Max Mikhanosha")
(:license "GPL")
(:slime-dependencies slime-repl)
(:on-load
(add-hook 'slime-repl-mode-hook
(lambda ()
(slime-repl-ansi-on)))))
(defvar slime-repl-ansi-color t
"When Non-NIL will process ANSI colors in the lisp output")
(make-variable-buffer-local 'slime-repl-ansi-color)
(defun slime-repl-ansi-on ()
"Set `ansi-color-for-comint-mode' to t."
(interactive)
(setq slime-repl-ansi-color t))
(defun slime-repl-ansi-off ()
"Set `ansi-color-for-comint-mode' to t."
(interactive)
(setq slime-repl-ansi-color nil))
(defadvice slime-repl-emit (around slime-repl-ansi-colorize activate compile)
(with-current-buffer (slime-output-buffer)
(let ((start slime-output-start))
(setq ad-return-value ad-do-it)
(when slime-repl-ansi-color
(ansi-color-apply-on-region start slime-output-end)))))
(provide 'slime-repl-ansi-color)
| 1,029 | Common Lisp | .l | 28 | 32.571429 | 77 | 0.703927 | noloop/cacau | 8 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 5217f3ed9567eb1ce0cb234e902674468feab396ae524c5ff4d0da1cc3121479 | 11,979 | [
-1
] |
11,994 | package.lisp | fisxoj_map/package.lisp | ;; package.lisp
;;
;; Copyright (c) 2012 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(defpackage #:map
(:use #:cl)
(:export
;; Missing functions
#:multf
#:1/
;; Matrix type definitions
#:complex-matrix
#:real-matrix
#:matrix
;; Matrix math operation
#:.+
#:.-
#:.*
#:./
#:.^
;; Matrix predicates
#:same-size-p
#:hermitianp
#:squarep
#:singularp
;; Matrix operations
#:tensor-product
#:norm
#:eye
#:zeros
#:ones
#:complex-zeros
#:make-plane
#:random-matrix
#:complex-random-matrix
#:mtrace
#:mapply
#:mref
#:determinant
#:transpose
#:inverse
#:row-major-subscripts
#:subscripts-row-major
#:lu-decomposition
;; Matrix macros
#:do-matrix
#:as-vector
;; Vector operations
#:norm
#:dot
#:mean
#:standard-deviation
#:sum
;; Calculus
#:riemann
#:rkf45
;; Images
#:imread
;; Plotting
#:plot
#:plot3d
#:image
;; Printing utility functions
#:mute
;; Convenience functions/macros
#:with-result
;; Equality checking
#:eps=))
(in-package :map)
| 1,937 | Common Lisp | .lisp | 86 | 19.186047 | 76 | 0.676647 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | a1b5be43f31ca48e989c796a814f46c20a563910d4a88192395ea41b4aaa77f5 | 11,994 | [
-1
] |
11,995 | conditions.lisp | fisxoj_map/conditions.lisp | ;; conditions.lisp
;;
;; Copyright (c) 2012 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package #:map)
(define-condition dimension-mismatch ()
((A :reader dimension-mismatch-a :initarg :a)
(B :reader dimension-mismatch-b :initarg :b))
(:report (lambda (condition stream)
(format stream "Matrix A ~a must be the same size as B ~a"
(array-dimensions (dimension-mismatch-a condition))
(array-dimensions (dimension-mismatch-b condition))))))
| 1,276 | Common Lisp | .lisp | 29 | 42 | 76 | 0.743775 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | bceb3a36972a96d398c55191e40f8779050e2bf0d5cf79b61438b713054ca200 | 11,995 | [
-1
] |
11,996 | image.lisp | fisxoj_map/images/image.lisp | ;; image.lisp
;;
;; Copyright (c) 2012-2013 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package #:map)
(defun imread (pathname)
(multiple-value-bind (image width height color-channels) (jpeg:decode-image pathname)
(make-array (list width height color-channels)
:displaced-to image :displaced-index-offset 0)))
(defun discrete-cosine-transform (m)
"Implements the DCT-II algorithm."
(declare (optimize (speed 3) (safety 0) (debug 0))
(type matrix m))
(map:with-result (result (array-dimensions m) 'double-float)
(let* ((width (array-dimension m 0))
(height (array-dimension m 1))
(pi-over-2width (/ pi (* 2 width)))
(pi-over-2height (/ pi (* 2 height)))
(sum 0))
(dotimes (k width)
(dotimes (l height)
(setf (aref result k l)
(*
1/4
(if (zerop k)
(/ 1 (sqrt 2))
1)
(if (zerop l)
(/ 1 (sqrt 2))
1)
(loop
for j of-type fixnum from 0 below height
summing (loop
for i of-type fixnum from 0 below width
summing (* (aref m i j)
(cos (* (1+ (* 2 i)) k pi-over-2width))
(cos (* (1+ (* 2 j)) l pi-over-2height))))))))))))
(defun inverse-discrete-cosine-transform (m)
"Implements the DCT-II algorithm."
(declare (optimize (speed 3) (safety 0) (debug 0))
(type matrix m))
(map:with-result (result (array-dimensions m) 'double-float)
(let* ((width (array-dimension m 0))
(height (array-dimension m 1))
(pi-over-2width (/ pi (* 2 width)))
(pi-over-2height (/ pi (* 2 height))))
(map:do-matrix (result (k l))
(setf (aref result k l)
(/
(loop
for j from 1 below height
summing (loop
for i from 1 below width
summing (* (if (zerop k)
(/ 1 (sqrt 2))
1)
(if (zerop l)
(/ 1 (sqrt 2))
1)
(aref m i j)
(cos (* (1+ (* 2 i)) k pi-over-2width))
(cos (* (1+ (* 2 j)) l pi-over-2height)))))
4))))))
| 2,754 | Common Lisp | .lisp | 80 | 30.025 | 88 | 0.635581 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 7168a544d962ad78890ce026688dddc6ee1aec9b05edbc1793e2ded5e79dae68 | 11,996 | [
-1
] |
11,997 | missing-functions.lisp | fisxoj_map/utilities/missing-functions.lisp | ;; missing-functions.lisp
;;
;; Copyright (c) 2012 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package :map)
(defmacro multf (place &optional (delta 1))
(let ((del (gensym)))
`(let ((,del ,delta))
(setf ,place (.* ,place ,del)))))
(declaim (inline 1/))
(defun 1/ (number)
(/ 1 number))
(declaim (inline eps=))
(defun eps= (a b)
"Determines if a is within double-float precision of b"
(and (> a (- b double-float-epsilon))
(< a (+ b double-float-epsilon))))
| 1,296 | Common Lisp | .lisp | 34 | 36.235294 | 76 | 0.715421 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 71821ceb78f7881219da1c08706252137968b8b2023a88a533c16837a89a2b45 | 11,997 | [
-1
] |
11,998 | convenience.lisp | fisxoj_map/utilities/convenience.lisp | ;; convenience.lisp
;;
;; Copyright (c) 2012 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package :map)
(defmacro with-result ((result dimensions &optional element-type) &body body)
`(let ((,result (make-array ,dimensions :element-type ,(or `,element-type ''double-float))))
,@body
,result))
| 1,114 | Common Lisp | .lisp | 26 | 41.307692 | 94 | 0.746777 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | ae036d82caf10f96cf6498ee71d491ce6dd591c5cfe626e82557aa5a41c366f4 | 11,998 | [
-1
] |
11,999 | printing.lisp | fisxoj_map/utilities/printing.lisp | ;; printing.lisp
;;
;; Copyright (c) 2012 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package #:map)
(defmacro mute (&body body)
`(progn ,@body
nil))
| 966 | Common Lisp | .lisp | 25 | 37.36 | 76 | 0.751864 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | eec4804e57696b9ee10dff20cd05641da9a0f8d1ef11e1d2530d891286b45592 | 11,999 | [
-1
] |
12,000 | range.lisp | fisxoj_map/vectors/range.lisp | ;; range.lisp
;;
;; Copyright (c) 2012 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package #:map)
(defclass range ()
((start :accessor range-start :initarg :start)
(delta :accessor range-delta :initarg :delta)
(stop :accessor range-stop :initarg :stop)))
(defun rangep (object)
(typep object 'range))
(defun range-length (range)
(the integer (1+ (round (/ (- (range-stop range) (range-start range)) (range-delta range))))))
(defun range-macro (stream subchar arg)
(declare (ignore subchar arg))
(let* ((sexp (read stream t)))
(ecase (length sexp)
(3 `(make-instance 'range :start ,(first sexp) :delta ,(second sexp) :stop ,(third sexp)))
(2 `(make-instance 'range :start ,(first sexp) :delta (max (signum (- ,(second sexp) ,(first sexp))) 1) :stop ,(second sexp))))))
(set-dispatch-macro-character #\# #\r #'range-macro)
| 1,671 | Common Lisp | .lisp | 37 | 43.108108 | 135 | 0.714813 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 6882a17b8d269bcc7d3be2811db7bd7cb0ff6d3116ff84b3680f3a272dd04a8a | 12,000 | [
-1
] |
12,001 | vector.lisp | fisxoj_map/vectors/vector.lisp | ;; vector.lisp
;;
;; Copyright (c) 2012 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package #:map)
(defun vectorize-macro (stream subchar arg)
(declare (ignore subchar arg))
(let* ((sexp (read stream t))
(eval-last (eval (car (last sexp))))
(function (if (functionp eval-last) eval-last nil))
(xi (eval (first sexp)))
(xf (eval (cond
;; Function and 3 numbers
((and (= (length sexp) 4) function)
(third sexp))
;; No function and 3 numbers
((and (= (length sexp) 3) (not function))
(third sexp))
;; Function and 2 numbers
((and (= (length sexp) 3) function)
(second sexp))
;; No function, 2 numbers
((= (length sexp) 2)
(second sexp)))))
(dx (eval (second sexp)))
(vector (if (or (and (= (length sexp) 4) function)
(and (= (length sexp) 3) (not function)))
(vectorize xi dx xf)
(vectorize xi (signum (- xf xi)) xf))))
(if function
(map 'vector function vector)
vector)))
(defun vec-dbg (xi dx xf)
(format t "xi: ~g dx: ~g xf: ~g~%" xi dx xf))
(defun vectorize2 (stream subchar arg)
(declare (ignore subchar arg))
(let* ((sexp (read stream t))
(xi (car sexp))
(xf (or (caddr sexp)
(cadr sexp)))
(dx (cadr sexp)))
(if (caddr sexp)
(loop with size = (1+ (ceiling (/ (- xf xi) dx))) ;; [xi:dx:xf] equivalent
with vector = (make-array (1+ size) :element-type 'double-float)
for step from xi to xf by dx
for i from 0 by 1
do (setf (aref vector i) step)
finally (return vector))
(loop with size = (1+ (ceiling (- xf xi))) ;; [xi:xf] equivalent
with vector = (make-array size :element-type 'double-float)
for step from xi to xf by (signum (- xf xi))
for i from 0 by 1
do (setf (aref vector i) step)
finally (return vector)))))
(defgeneric vectorize (xi dx xf))
(defmethod vectorize ((xi integer) (dx integer) (xf integer))
(loop with size = (1+ (ceiling (/ (- xf xi) dx))) ;; [xi:xf] equivalent
with vector = (make-array size :element-type 'integer)
for step from xi to xf by dx
for i from 0 by 1
do (setf (aref vector i) step)
finally (return vector)))
(defmethod vectorize ((xi double-float) (dx double-float) (xf double-float))
(loop with size = (1+ (ceiling (/ (- xf xi) dx))) ;; [xi:xf] equivalent
with vector = (make-array size :element-type 'double-float)
for step from xi to xf by dx
for i from 0 by 1
do (setf (aref vector i) step)
finally (return vector)))
(defmethod vectorize (xi dx xf)
(let ((xii (coerce xi 'double-float))
(dxi (coerce dx 'double-float))
(xfi (coerce xf 'double-float)))
(loop with size = (1+ (ceiling (/ (- xfi xii) dxi))) ;; [xi:xf] equivalent
with vector = (make-array size :element-type 'double-float)
for step from xii to xfi by dxi
for i from 0 by 1
do (setf (aref vector i) step)
finally (return vector))))
(set-dispatch-macro-character #\# #\v #'vectorize-macro)
| 3,801 | Common Lisp | .lisp | 97 | 35.123711 | 78 | 0.650244 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | cff50a4ac17668ce910acbcd3cc1c96b0f6c069fa3791031a3946f09e9fd5295 | 12,001 | [
-1
] |
12,002 | vector-operations.lisp | fisxoj_map/vectors/vector-operations.lisp | ;; vector-operations.lisp
;;
;; Copyright (c) 2012 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package #:map)
(defmethod norm ((vec vector))
(sqrt (loop for i across vec sum (* i i))))
(defun dot (a b)
"Dot product of two vectors. Returns a scalar."
(assert (= (length a) (length b)))
(reduce #'+ (map 'vector '* a b)))
(defun mean (vector)
(/ (sum vector) (length vector)))
(defmethod sum ((vector vector))
(loop for i across vector sum i))
(defun range (vector min max)
(map 'vector (lambda (n) (+ (mod (- n min) (abs (- max min))) min)) vector))
(defun standard-deviation (vector)
(declare (optimize speed))
(loop
with x-bar = (mean vector)
for x across vector sum (expt (- x x-bar) 2) into sum
finally (return (/ sum (length vector)))))
| 1,592 | Common Lisp | .lisp | 40 | 37.775 | 78 | 0.708549 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 36b567839b31d61e4abc702f427af853f591ce764baa1de4e1d9fcfcdddf69ba | 12,002 | [
-1
] |
12,003 | plot.lisp | fisxoj_map/plotting/plot.lisp | ;; plot.lisp
;;
;; Copyright (c) 2012 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package #:map)
(defparameter *gnuplot-path* #p"/usr/bin/gnuplot")
(defparameter *gnuplot-args* '("-persist"))
(defparameter *gnuplot-process* nil)
;; Thanks http://yujianzhang.blogspot.com/2007/12/nicer-fonts-for-gnuplot.html
(defparameter *gnuplot-font* "/usr/share/fonts/bitstream-vera/Vera.ttf,12")
(defmacro with-plot ((stream &optional terminal pathspec) &body body)
(when (and (member terminal '(:eps :ps :png :jpg :svg))
(not pathspec))
(error "Attempting to plot to a file with no pathspec given"))
`(let ((gnuplot (ensure-gnuplot-connection)))
(with-open-stream (,stream (external-program:process-input-stream gnuplot))
;with-open-file (,stream #p"./test" :direction :output :if-exists :supersede)
(format ,stream "set term ~a enhanced font ~S~%" (string-downcase ,terminal) *gnuplot-font*)
(when ,pathspec (format ,stream "set output ~S~%" (namestring ,pathspec)))
,@body)))
(defun close-gnuplot-connection ()
(when *gnuplot-process*
(external-program:signal-process *gnuplot-process* :quit)))
(defun ensure-gnuplot-connection ()
(if (or (null *gnuplot-process*)
(not (eq (external-program:process-status *gnuplot-process*) :running)))
(setf *gnuplot-process* (external-program:start *gnuplot-path* *gnuplot-args*
:input :stream))
*gnuplot-process*))
(defun parse-style (stream style-number args)
;; Do we have a title? Print it first
(format stream "set style line ~d " style-number)
;; More style directives? They live together
(if args
(destructuring-bind (&key line-type line-color line-width point-type point-size &allow-other-keys) args
(when line-type (format stream "lt ~a " line-type))
(when line-color (format stream "lc ~a " line-color))
(when line-width (format stream "lw ~a " line-width))
(when point-type (format stream "pt ~a " point-type))
(when point-size (format stream "ps ~a " point-size))
(format stream "~%"))
(format stream "default~%")))
(defun print-vectors-to-stream (stream x y)
(loop for xi across x
for yi across y
do (format stream "~1,8f ~1,8f~%" xi yi))
(format stream "e~%"))
(defun plot (plot-sexps &key title (terminal :wxt) (pathspec "") x-label y-label)
;; Make sure args is always a list of plot specs
(let ((plot-sexps (if (consp (car plot-sexps))
plot-sexps
(list plot-sexps))))
(with-plot (stream terminal pathspec)
(when title (format stream "set title ~S~%" title))
(when x-label (format stream "set xlabel ~S~%" x-label))
(when y-label (format stream "set ylabel ~S~%" y-label))
;; Write line styles to stream
(loop
for plot in plot-sexps
for number from 1 by 1
do (parse-style stream number (subseq plot 2)))
;; Write plot commands to stream
(loop
for plot in plot-sexps
for number from 1 by 1
initially (princ "plot " stream)
do (format stream
"'-' using 1:2 ls ~d title ~S with ~a"
number
(or (getf plot :title) "")
(case (getf plot :line-style)
(:lines "lines")
(:points "points")
(:lines-points "linespoints")
(:impulses "impulses")
(:dots "dots")
(:steps "steps")
;; FIXME: Add others once we can parse more vectors (errorbars)
(t "lines")))
unless (= (length plot-sexps) number)
do (princ ", " stream)
finally (princ #\Newline stream))
(loop
for plot in plot-sexps
do (destructuring-bind (x y) (subseq plot 0 2)
;; hah! second-class functions to the rescue!
(print-vectors-to-stream stream x y))))))
(defun image (data &key title (terminal :wxt) (pathspec "") x-label y-label)
(with-plot (s terminal pathspec)
(when title (format s "set title ~S~%" title))
(when x-label (format s "set xlabel ~S~%" x-label))
(when y-label (format s "set ylabel ~S~%" y-label))
(format s "set pm3d map~%")
(format s "set size ratio 1~%")
(format s "splot '-' matrix~%")
(loop for i from (1- (array-dimension data 1)) downto 0
do (loop for j from 0 upto (1- (array-dimension data 0))
do (format s "~g " (aref data j i)))
do (format s "~%"))
(format s "e~%")))
(defun plot3d (data &key title (terminal :wxt) (pathspec "") x-label y-label z-label)
; (declare (type real-matrix data))
(with-plot (s terminal pathspec)
(when title (format s "set title ~S~%" title))
(when x-label (format s "set xlabel ~S~%" x-label))
(when y-label (format s "set ylabel ~S~%" y-label))
(when z-label (format s "set zlabel ~S~%" z-label))
; (format s "set pm3d~%")
(format s "set isosample 4~%")
(format s "splot '-' matrix~%")
(loop for i from 0 below (array-dimension data 0)
do (loop for j from 0 below (array-dimension data 1)
do (format s "~g " (aref data i j)))
do (format s "~%"))
(format s "e~%")))
| 5,771 | Common Lisp | .lisp | 132 | 39.356061 | 109 | 0.663876 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | e36089000599e1cd8ba401447e3c0730e9641a781ae3c175994d54607b37e9e5 | 12,003 | [
-1
] |
12,004 | matrix-multiply.lisp | fisxoj_map/matrix/matrix-multiply.lisp | ;; matrix-multiply.lisp
;;
;; Copyright (c) 2013 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package #:map)
(defun %*rr (aa bb)
"Real by real matrix multiplication"
(declare (optimize speed (safety 0) (debug 1)))
(let* ((rows (array-dimension aa 0))
(cols (array-dimension bb 1))
(inner (array-dimension aa 1))
(rr (map:zeros rows cols)))
(declare (type (simple-array double-float (* *)) aa bb rr)
(type fixnum rows cols inner))
(dotimes (i rows)
(let ((i-rows (the fixnum (* i rows))))
(declare (type fixnum i-rows))
(dotimes (k inner)
(let ((a-value (row-major-aref aa (the fixnum (+ i-rows k))))
(k-inner (the fixnum (* k inner))))
(declare (type double-float a-value)
(type fixnum k-inner))
(unless (zerop a-value)
(dotimes (j cols)
(incf (row-major-aref rr (+ i-rows j)) (* a-value (row-major-aref bb (+ k-inner j))))))))))
rr))
(defun %*cr (aa bb)
"Real by real matrix multiplication"
(declare (optimize speed (safety 0) (debug 1)))
(let* ((rows (array-dimension aa 0))
(cols (array-dimension bb 1))
(inner (array-dimension aa 1))
(rr (map:zeros rows cols)))
(declare (type (simple-array double-float (* *)) bb)
(type (simple-array (complex double-float) (* *)) aa rr)
(type fixnum rows cols inner))
(dotimes (i rows)
(let ((i-rows (the fixnum (* i rows))))
(declare (type fixnum i-rows))
(dotimes (k inner)
(let ((a-value (row-major-aref aa (the fixnum (+ i-rows k))))
(k-inner (the fixnum (* k inner))))
(declare (type (complex double-float) a-value)
(type fixnum k-inner))
(unless (= a-value #c(0d0 0d0))
(dotimes (j cols)
(incf (row-major-aref rr (+ i-rows j)) (* a-value (row-major-aref bb (+ k-inner j))))))))))
rr))
(defun %*rc (aa bb)
"Real by complex matrix multiplication"
(declare (optimize speed (safety 0) (debug 1)))
(let* ((rows (array-dimension aa 0))
(cols (array-dimension bb 1))
(inner (array-dimension aa 1))
(rr (map:zeros rows cols)))
(declare (type (simple-array double-float (* *)) aa)
(type (simple-array (complex double-float) (* *)) bb rr)
(type fixnum rows cols inner))
(dotimes (i rows)
(let ((i-rows (the fixnum (* i rows))))
(declare (type fixnum i-rows))
(dotimes (k inner)
(let ((a-value (row-major-aref aa (the fixnum (+ i-rows k))))
(k-inner (the fixnum (* k inner))))
(declare (type double-float a-value)
(type fixnum k-inner))
(unless (zerop a-value)
(dotimes (j cols)
(incf (row-major-aref rr (+ i-rows j)) (* a-value (row-major-aref bb (+ k-inner j))))))))))))
(defun %*cc (aa bb)
"Complex by complex matrix multiplication"
(declare (optimize speed (safety 0) (debug 1)))
(let* ((rows (array-dimension aa 0))
(cols (array-dimension bb 1))
(inner (array-dimension aa 1))
(rr (map:zeros rows cols)))
(declare (type (simple-array (complex double-float) (* *)) aa bb rr)
(type fixnum rows cols inner))
(dotimes (i rows)
(let ((i-rows (the fixnum (* i rows))))
(declare (type fixnum i-rows))
(dotimes (k inner)
(let ((a-value (row-major-aref aa (the fixnum (+ i-rows k))))
(k-inner (the fixnum (* k inner))))
(declare (type (complex double-float) a-value)
(type fixnum k-inner))
(unless (zerop a-value)
(dotimes (j cols)
(incf (row-major-aref rr (+ i-rows j)) (* a-value (row-major-aref bb (+ k-inner j))))))))))))
| 4,250 | Common Lisp | .lisp | 106 | 36.396226 | 95 | 0.646206 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | e5fa8e01cd767327e507613e168bbb36338044b0f28e164755041f55c1ea21c5 | 12,004 | [
-1
] |
12,005 | matrix-operations.lisp~ | fisxoj_map/matrix/matrix-operations.lisp~ | (in-package :map)
(export '(tensor-product
mtrace))
(defun tensor-product (A B)
(declare (type matrix A B))
(let* ((dimA (array-dimensions A)) (dimB (array-dimensions B))
(x (* (elt dimA 0) (elt dimB 0)))
(y (* (elt dimA 1) (elt dimB 1))))
(loop with M = (zeros x y)
for i from 0 upto (1- (elt dimA 0))
do (loop for j from 0 upto (1- (elt dimA 1))
do (loop for k from 0 upto (1- (elt dimB 0))
do (loop for l from 0 upto (1- (elt dimB 1))
for xx = (+ k (* (elt dimB 0) i))
for yy = (+ l (* (elt dimB 1) j))
do (setf (aref M xx yy) (* (aref A i j) (aref B k l))))))
finally (return-from tensor-product M))))
(defun mtrace (M)
(when (squarep M)
(loop for i from 0 to (1- (array-dimension M 0))
sum (aref M i i))))
(defun transpose (M)
(let ((new (make-array (array-dimensions M))))
(loop for i from 0 upto (1- (array-dimension M 0))
for j from 0 upto (1- (array-dimension M 1))
do (setf (aref new j i) (aref M i j))
return M)))
(defmethod .+ ((A simple-array) (B simple-array))
(if (same-size-p A B)
(let ((result (apply 'zeros (array-dimensions A))))
(loop for i from 0 upto (1- (array-total-size A))
do (setf (row-major-aref result i)
(+ (row-major-aref A i)
(row-major-aref B i)))
finally (return result)))
(error 'dimension-mismatch :a A :b B)))
(defmethod .+ ((A simple-array) (B number))
(let ((result (apply 'zeros (array-dimensions A))))
(loop for i from 0 upto (1- (array-total-size A))
do (setf (row-major-aref result i)
(+ (row-major-aref A i)
B))
finally (return result))))
(defmethod .+ ((A number) (B simple-array))
(.+ B A))
(defmethod .* ((A simple-array) (B simple-array))
(if (inner-dimensions-match-p A B)
(let* ((dimA (array-dimensions A))
(dimB (array-dimensions B))
(dimresult (list (first dimA) (second dimB)))
(result (make-array dimresult)))
(loop for i from 0 upto (1- (first dimresult))
do (loop for j from 0 upto (1- (second dimresult))
do (loop for k from 0 upto (1- (second dimA))
do (incf (aref result i j)
(* (aref A i k) (aref B k j)))))))))
(defmethod .* ((A number) (B simple-array))
(let* ((dimA (array-dimensions B))
(result (make-array dimA)))
(loop for i from 0 upto (1- (first dimA))
do (loop for j from 0 upto (1- (second dimA))
do (setf (aref result i j) (* A (aref B i j)))))
result))
| 2,448 | Common Lisp | .lisp | 63 | 34.31746 | 64 | 0.594526 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 89f83a34830237c35ee2ae6ff6c22fcc6d3bb4a51bacf066a5da25751d021bb1 | 12,005 | [
-1
] |
12,006 | matrix-decomposition.lisp | fisxoj_map/matrix/matrix-decomposition.lisp | ;; matrix-decomposition.lisp
;;
;; Copyright (c) 2012-2013 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package :map)
(defun lu-decomposition (matrix)
"Performs the LU decomposition of the matrix according to Golub & Van Loan, Matrix Computations, Algorithm 3.4.1, as referenced by the GSL docs."
;; See: http://books.google.com/books?id=mlOa7wPX6OYC&lpg=PA114&ots=lcfrg9N7fY&dq=Golub%20%26%20Van%20Loan%2C%20Matrix%20Computations%2C%20Algorithm%203.4.1&pg=PA112#v=onepage&q=Golub%20&%20Van%20Loan,%20Matrix%20Computations,%20Algorithm%203.4.1&f=false
(declare (optimize speed (safety 0)))
(let* ((length (array-dimension matrix 0))
;; The permutation vector will hold the
(p nil)
;; Copy matrix into U
(U (.* 1d0 matrix))
(rows (make-instance 'range :stop (1- length) :delta 1)))
(declare (optimize speed (safety 1) (debug 0))
(type (simple-array double-float) U))
(dotimes (k length)
(setf (range-start rows) k)
;; There seems to be an error in the book where the permutations should happen
;; to a whole row, now just k:n columns of it
(let ((ps (loop
with max double-float = 0d0
with row integer = 0
for i of-type integer from k below length
for v double-float = (aref U i k)
when (> v max)
do (setf max v) and do (setf row i)
finally (return row))))
(declare (type integer ps))
;; If the most significant row is the k-th row, don't juggle it with itself
(unless (= k ps)
(push ps p)
(rotatef (mref U k t) (mref U ps t))))
(unless (eps= (aref U k k) 0.0)
;; wow, this is straightforward with (mref), hopefully it's not super slow
(setf (range-start rows) (1+ k)
(mref U rows k) (./ (mref U rows k) (aref U k k))
(mref U rows rows) (.- (mref U rows rows) (.* (mref U rows k) (mref U k rows))))))
;; Finish the p-vector
(values
;; Put 1's on the diagonal
(let ((lower (lower-matrix U)))
(loop for i from 0 below length
do (setf (aref lower i i) 1d0) finally (return lower)))
;; Upper Matrix
(upper-matrix U)
(reverse p))))
(defun permutation-list (matrix &key (sort #'>) (column 0) (start 0))
(declare (optimize (speed 3))
(type function sort))
(mapcar
#'second
(sort (loop
for i from start below (array-dimension matrix 0)
collect (list (aref matrix i column) i))
sort :key (lambda (n) (abs (car n))))))
(defun permutation-matrix (p-list)
(let ((l (length p-list)))
(with-result (result (list l l))
(dotimes (i l)
(setf (aref result i (elt p-list i)) 1d0)))))
| 3,404 | Common Lisp | .lisp | 79 | 39.151899 | 256 | 0.677935 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | bc8a9912378b2b28b07b74b776a3dab141ad4c21bdc257d61517e9236f6a013b | 12,006 | [
-1
] |
12,007 | matrices.lisp | fisxoj_map/matrix/matrices.lisp | ;; matrices.lisp
;;
;; Copyright (c) 2012 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package #:map)
(defun zeros (&rest dimensions)
(make-array dimensions :element-type 'double-float :initial-element 0.0d0))
(defun ones (&rest dimensions)
(make-array dimensions :element-type 'double-float :initial-element 1.0d0))
(defun complex-zeros (&rest dimensions)
(make-array dimensions :element-type '(complex double-float) :initial-element #c(0.0d0 0.0d0)))
(defun eye (dimension)
(loop with m = (zeros dimension dimension)
for i from 0 to (1- dimension)
do (setf (aref m i i) 1.0d0)
finally (return m)))
(defmacro make-plane (range1 range2 function &optional (element-type ''double-float))
(let ((result (gensym))
(l1 (gensym))
(l2 (gensym))
(i (gensym))
(j (gensym)))
`(let* ((,l1 (range-length ,range1))
(,l2 (range-length ,range2))
(,result (make-array (list ,l1 ,l2) :element-type ,element-type)))
(declare (optimize speed))
(loop for ,j of-type fixnum from 0 below ,l2
do (loop for ,i of-type fixnum from 0 below ,l1
do (setf (aref ,result ,i ,j)
(funcall ,function
(+ (range-start ,range1) (* ,i (range-delta ,range1)))
(+ (range-start ,range2) (* ,j (range-delta ,range2))))))
finally (return ,result)))))
(declaim (inline row-major-subscripts))
(defun row-major-subscripts (matrix-dimensions row-major-index)
(declare (optimize speed))
(loop
with p
for i of-type fixnum in (reverse matrix-dimensions)
for rmi of-type fixnum = row-major-index then m
for (m r) (fixnum fixnum) = (multiple-value-list (floor rmi i))
do (push r p)
finally (return p)))
(defun subscripts-row-major (matrix &rest subscripts)
(let ((array-dimensions (array-dimensions matrix))
(subscripts subscripts))
(%subscripts-row-major (cdr array-dimensions) subscripts)))
(defun %subscripts-row-major (dimensions subscripts)
(+ (* (car subscripts) (reduce #'* dimensions))
(if (cdr dimensions)
(%subscripts-row-major (cdr dimensions) (cdr subscripts))
(second subscripts))))
| 2,916 | Common Lisp | .lisp | 69 | 38.898551 | 97 | 0.702503 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | efb6d8d128f6b27a8127224179f38f87dba4369a19ae1b12e2bc58638e136401 | 12,007 | [
-1
] |
12,008 | matrix-predicates.lisp | fisxoj_map/matrix/matrix-predicates.lisp | ;; matrix-predicates.lisp
;;
;; Copyright (c) 2012 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package #:map)
(export '(same-size-p
squarep
hermitianp))
(defun same-size-p (A B)
(loop for a in (mapcar #'= (array-dimensions A) (array-dimensions B))
when (not a) do (return nil)
finally (return t)))
(defun inner-dimensions-match-p (A B)
(let ((dimA (array-dimensions A))
(dimB (array-dimensions B)))
(and (= (second dimA) (first dimB)))))
(defun squarep (M)
(apply #'= (array-dimensions M)))
(defun hermitianp (M)
(and (loop for i from 0 to (1- (array-dimension M 0))
collect (loop for j from 0 to (- (array-dimension M 1) i 1)
collect (= (conjugate (aref M i j)) (aref M j i))))))
(defun singularp (M)
(zerop (determinant M)))
| 1,588 | Common Lisp | .lisp | 41 | 36.463415 | 76 | 0.708442 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | f1a27a00dec58c4aede11e030619fd363ece7194b2866e24f1536d152b1a5b9a | 12,008 | [
-1
] |
12,009 | matrix-macros.lisp | fisxoj_map/matrix/matrix-macros.lisp | ;; matrix-macros.lisp
;;
;; Copyright (c) 2012 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package #:map)
(defmacro do-matrix ((matrix &optional subscripts) &body body)
; (assert (or (not subscripts) (= (length subscripts) (array-rank matrix))))
(let ((i (gensym))
(dimensions (gensym)))
`(loop
with ,dimensions = (array-dimensions ,matrix)
for ,i from 0 below (array-total-size ,matrix)
for ,subscripts = (row-major-subscripts ,dimensions ,i)
do (progn ,@body))))
(defmacro do-matrix-with-result ((matrix subscripts result result-dimensions &optional (element-type 'double-float)) &body body)
; (assert (or (not subscripts) (= (length subscripts) (array-rank matrix))))
(let ((i (gensym))
(dimensions (gensym)))
`(loop
with ,result = (make-array ,result-dimensions :element-type (quote ,element-type))
with ,dimensions = (array-dimensions ,matrix)
for ,i from 0 below (array-total-size ,matrix)
for ,subscripts = (row-major-subscripts ,dimensions ,i)
do (progn ,@body)
finally (return ,result))))
(defmacro as-vector (matrix)
`(make-array (array-total-size ,matrix)
:element-type (array-element-type ,matrix)
:displaced-to ,matrix
:displaced-index-offset 0))
| 2,025 | Common Lisp | .lisp | 47 | 40.93617 | 128 | 0.728977 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 4c0d5e4ea28b6a00f5232772a2208bbfdf83379cbd267f2222f4685b9532e713 | 12,009 | [
-1
] |
12,010 | matrix-slices.lisp | fisxoj_map/matrix/matrix-slices.lisp | ;; matrix-slices.lisp
;;
;; Copyright (c) 2012 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package :map)
(defun matrix-row (matrix row)
(mref matrix row t))
(defun matrix-column (matrix column)
(mref matrix t column))
(defun mref (matrix &rest subscripts)
"Functions like (aref), but accepts ranges or T and returns a submatrix of matrix."
(declare (optimize speed space (safety 0)))
(let* ((submatrix-instructions
(%submatrix-instructions (array-dimensions matrix) subscripts))
(submatrix-dimensions
(mapcar #'second submatrix-instructions))
(start-points (mapcar #'first submatrix-instructions))
(reduced-dimensions
(reduced-dimensions submatrix-dimensions)))
(declare (type (cons integer) start-points))
;; If submatrix-dimensions is nil, the array has one element and we should just
;; pass things along to regular old aref.
(if reduced-dimensions
(reshape-matrix
(with-result (submatrix submatrix-dimensions (array-element-type matrix))
(do-matrix (submatrix indices)
(let ()
(declare (type (cons integer) indices start-points))
(setf (apply #'aref submatrix indices)
(apply #'aref matrix (mapcar #'+ (the (cons integer) start-points)
(the (cons integer) indices))))))))
;; We received a set of integer subscripts, access the array normally
(apply #'aref matrix start-points))))
(defun (setf mref) (source-matrix target-matrix &rest subscripts)
(declare (optimize speed (safety 0))
(inline %submatrix-instructions reduced-dimensions))
(let* ((submatrix-instructions
(%submatrix-instructions (array-dimensions target-matrix) subscripts))
(submatrix-dimensions
(mapcar #'second submatrix-instructions))
(start-points (mapcar #'first submatrix-instructions))
(reduced-dimensions
(reduced-dimensions submatrix-dimensions)))
(declare (type (cons fixnum) submatrix-dimensions start-points))
(if reduced-dimensions
;; reduced-dimensons will be nil if all dimensions were 1
(loop
with total-size fixnum = (array-total-size source-matrix)
for i from 0 below total-size
do (setf (apply #'aref target-matrix
(mapcar (lambda (a b) (declare (type fixnum a b)) (+ a b))
start-points (row-major-subscripts submatrix-dimensions i)))
(row-major-aref source-matrix i))
finally (return target-matrix))
;; If we're just setting a single value, pass that off to aref
(setf (apply #'aref target-matrix start-points) source-matrix))))
(defun %submatrix-instructions (matrix-dimensions subscripts)
(declare (optimize speed)
(type (cons fixnum) matrix-dimensions)
(type cons subscripts))
(assert (= (length matrix-dimensions) (length subscripts)))
(destructuring-bind (sub . rest) subscripts
(cons
(typecase sub
;; Ranges should have integer values with the exception of the end
;; which can be -1
(range
(list
(range-start sub)
;; For the end, accept -1 and calculate the remaining length from
;; the start value
(cond
((= (the fixnum (range-stop sub)) -1)
(- (car matrix-dimensions) (the fixnum (range-start sub))))
(t (range-length sub)))))
(integer
(list sub 1))
(t
(list 0 (car matrix-dimensions))))
(when rest (%submatrix-instructions (cdr matrix-dimensions) rest)))))
(defun reduced-dimensions (dimensions)
"Removes 1's from dimension lists.
NOTE: This will return nil if all dimensions are 1"
(declare (optimize speed))
(remove-if (lambda (a) (declare (type fixnum a)) (= a 1)) dimensions))
(defun reshape-matrix (matrix)
(declare (optimize speed))
"Utility for the mref functions which takes a submatrix, which sometimes contains arrays with dimensions that are 1. i.e. a 2x4x1 matrix, which will be far more useful as a 2x4 matrix. This function makes a displaced array to the original, but with the more useful shape."
(make-array (reduced-dimensions (array-dimensions matrix))
:element-type (array-element-type matrix)
:displaced-to matrix
:displaced-index-offset 0))
| 4,858 | Common Lisp | .lisp | 109 | 40.93578 | 276 | 0.726736 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 3cd0a8382a199b1b10c4638f8c455774b5c21a653c06f7a5bfb1f78189698750 | 12,010 | [
-1
] |
12,011 | matrix-functions.lisp | fisxoj_map/matrix/matrix-functions.lisp | ;; matrix-functions.lisp
;;
;; Copyright (c) 2012-2013 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package :map)
(defun determinant (matrix)
(multiple-value-bind (l u p) (lu-decomposition matrix)
(declare (ignore l))
;; L is unitriangular, so (det L) == 1
(loop
with u-terms = 1d0
for i from 0 below (array-dimension matrix 0)
do (multf u-terms (aref u i i))
finally (return (* u-terms (expt -1.0 (length p)))))))
(defun inverse (matrix)
; (declare (type matrix matrix))
(.* (1/ (determinant matrix))
(adjugate matrix)))
(defun adjugate (matrix)
(with-result (result (array-dimensions matrix))
(do-matrix (result subscripts)
(setf (apply #'aref result subscripts)
;; -1^(i+j+k+...) power * determinant of the minor matrix
(* (expt -1 (reduce #'+ (mapcar #'1+ subscripts)))
(determinant (apply #'minor-matrix matrix subscripts)))))))
| 1,727 | Common Lisp | .lisp | 42 | 38.119048 | 76 | 0.700773 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | ae71026c7c224591e235fd9ac5978a388b1cc01034004e5fb6aa32e0df6b17e5 | 12,011 | [
-1
] |
12,012 | matrix-operations.lisp | fisxoj_map/matrix/matrix-operations.lisp | ;; matrix-operations.lisp
;;
;; Copyright (c) 2012 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package #:map)
(declaim (optimize (speed 3)))
(defun minor-matrix (matrix &rest subscripts)
;; Result matrix is of dimensions N-1xN-1 compared to the original matrix
(let ((row-major 0))
(do-matrix-with-result (matrix indices result (mapcar #'1- (array-dimensions matrix)) (array-element-type matrix))
;; Don't copy a number if any of the indices matches a sprcified subscript
(unless (reduce (lambda (a b) (or a b)) (mapcar #'= indices subscripts))
(setf (row-major-aref result row-major) (apply #'aref matrix indices))
(incf row-major)))))
(defun random-matrix (&rest dimensions)
(declare (optimize speed (safety 0) (debug 1)))
(let* ((result (apply #'zeros dimensions))
(total-size (reduce #'* dimensions)))
(declare (type fixnum total-size)
(type (simple-array double-float) result))
(loop for i of-type fixnum from 0 below total-size do
(setf (row-major-aref result i)
(random 1d0)))
result))
(defun complex-random-matrix (&rest dimensions)
(declare (optimize speed (safety 0) (debug 1)))
(let* ((result (apply #'complex-zeros dimensions))
(total-size (reduce #'* dimensions)))
(declare (type fixnum total-size)
(type (simple-array (complex double-float)) result))
(loop for i of-type fixnum from 0 below total-size do
(setf (row-major-aref result i)
(complex (random 1d0) (random 1d0))))
result))
(defun mapply (func data)
(with-result (result (array-dimensions data))
(loop
for i from 0 below (array-total-size result)
do (setf (row-major-aref result i)
(funcall func (row-major-aref result i))))))
(defun tensor-product (A B)
(declare (type matrix A B))
(let* ((dimA (array-dimensions A)) (dimB (array-dimensions B))
(x (* (elt dimA 0) (elt dimB 0)))
(y (* (elt dimA 1) (elt dimB 1))))
(loop with M = (zeros x y)
for i from 0 upto (1- (elt dimA 0))
do (loop for j from 0 upto (1- (elt dimA 1))
do (loop for k from 0 upto (1- (elt dimB 0))
do (loop for l from 0 upto (1- (elt dimB 1))
for xx = (+ k (* (elt dimB 0) i))
for yy = (+ l (* (elt dimB 1) j))
do (setf (aref M xx yy) (* (aref A i j) (aref B k l))))))
finally (return-from tensor-product M))))
(defun mtrace (M)
(when (squarep M)
(loop for i from 0 to (1- (array-dimension M 0))
sum (aref M i i))))
(defun transpose (matrix)
(do-matrix-with-result (result (i j) result (nreverse (array-dimensions matrix)))
(setf (aref result i j) (aref matrix j i))))
(defgeneric .+ (A B)
(:documentation "Matrix addition function, will also add single numbers elementwise to the matrix."))
(defmethod .+ ((A array) (B array))
(if (same-size-p A B)
(let ((result (apply 'zeros (array-dimensions A))))
(loop for i from 0 upto (1- (array-total-size A))
do (setf (row-major-aref result i)
(+ (row-major-aref A i)
(row-major-aref B i)))
finally (return result)))
(error 'dimension-mismatch :a A :b B)))
(defmethod .+ ((A array) (B number))
(let ((result (apply 'zeros (array-dimensions A))))
(loop for i from 0 upto (1- (array-total-size A))
do (setf (row-major-aref result i)
(+ (row-major-aref A i)
B))
finally (return result))))
(defmethod .+ ((A number) (B array))
(.+ B A))
(defmethod .+ ((A number) (B number))
(+ A B))
(defmethod .+ (A B)
(error ".+ Not implelented for types ~a and ~a" (type-of A) (type-of B)))
(defgeneric .* (A B))
(defmethod .* ((A number) (B number))
(declare (optimize speed)
(type double-float A B))
(* A B))
(defmethod .* ((A simple-array) (B simple-array))
(declare (optimize speed (safety 1) (debug 0))
(inline %*rr %*rc %*cr %*cc))
(if (eq (array-element-type A) 'double-float)
(if (eq (array-element-type B) 'double-float)
(%*rr A B)
(%*rc A B))
(if (eq (array-element-type B) 'double-float)
(%*cr A B)
(%*cc A B))))
(defmethod .* ((A array) (B array))
(declare (optimize speed)
(type (vector double-float) A)
(type (array double-float (* *)) B))
(do-matrix-with-result (result (i j) result (list (array-dimension A 0) (array-dimension B 1)))
(setf (aref result i j) (dot (mref a i t) (mref b t j)))))
(defmethod .* ((A vector) (B vector))
(declare (optimize speed (safety 0)))
(let ((rows (length A))
(cols (length B)))
(if (eq (array-element-type A) 'double-float)
(if (eq (array-element-type B) 'double-float)
;; A and B are real
(let ((result (zeros rows cols)))
(declare (type (simple-array double-float (* *)) result)
(type (vector double-float) A B))
(dotimes (j cols)
(dotimes (i rows)
(setf (aref result i j) (* (the double-float (elt A i)) (the double-float (elt B j))))))
(return-from .* result))
;; A is real and B is complex
(let ((result (complex-zeros rows cols)))
(declare (type (simple-array (complex double-float) (* *)) result)
(type (simple-array double-float (*)) A)
(type (simple-array (complex double-float) (*)) B))
(dotimes (j cols)
(dotimes (i rows)
(setf (aref result i j) (* (aref A i) (aref B j)))))
(return-from .* result)))
(if (eq (array-element-type B) 'double-float)
;; A is complex and B is real
(let ((result (complex-zeros rows cols)))
(declare (type (simple-array (complex double-float) (* *)) result)
(type (simple-array (complex double-float) (*)) A)
(type (simple-array double-float (*)) B))
(dotimes (j cols)
(dotimes (i rows)
(setf (aref result i j) (* (aref A i) (aref B j)))))
(return-from .* result))
;; A and B are complex
(let ((result (complex-zeros rows cols)))
(declare (type (simple-array (complex double-float) (* *)) result)
(type (simple-array (complex double-float) (*)) A B))
(dotimes (j cols)
(dotimes (i rows)
(setf (aref result i j) (* (aref A i) (aref B j)))))
(return-from .* result)))))
(defmethod .* ((A simple-array) (B vector))
(declare (optimize speed)
(type (simple-array double-float (* *)) A)
(type (vector double-float) B))
(with-result (result (array-dimensions B))
(loop for i from 0 below (length B)
do (setf (aref result i) (.* B (mref A i t)))))))
(defmethod .* ((A vector) (B simple-array))
(declare (optimize speed)
(type (vector double-float) A)
(type (simple-array double-float (* *)) B))
(with-result (result (list (length A)))
(loop for i from 0 below (1- (length A))
do (setf (aref result i) (.* A (mref B i t))))))
(defmethod .* ((A number) (B array))
(with-result (result (array-dimensions B))
(loop for i from 0 below (array-total-size B)
do (setf (row-major-aref result i) (* A (row-major-aref B i))))
result))
(defmethod .* ((A number) (B simple-array))
(declare (optimize speed)
(type double-float A)
(type (simple-array double-float) B))
(with-result (result (array-dimensions B))
(loop for i from 0 below (array-total-size B)
do (setf (row-major-aref result i) (* A (row-major-aref B i))))
result))
(defmethod .* ((A number) (B array))
(declare (optimize speed)
(type double-float A)
(type (array double-float) B))
(with-result (result (array-dimensions B))
(loop for i from 0 below (array-total-size B)
do (setf (row-major-aref result i) (* A (row-major-aref B i))))
result))
(defmethod .* ((A array) (B number))
(.* B A))
(defmethod .* ((A number) (B vector))
(declare (optimize speed))
(if (typep A 'double-float)
;; A is real
(if (typep B '(vector double-float))
;; B is real
(let* ((length (length B))
(result (zeros length)))
(declare (type double-float A)
(type (simple-array double-float (*)) result)
(type (vector double-float) B))
(dotimes (i length)
(setf (aref result i) (* A (aref B i))))
(return-from .* result))
;; B is complex
(let* ((length (length B))
(result (complex-zeros length)))
(declare (type double-float A)
(type (simple-array (complex double-float) (*)) result)
(type (vector (complex double-float)) B))
(dotimes (i length)
(setf (aref result i) (* A (aref B i))))
(return-from .* result)))
;; A is complex
(if (typep B '(vector double-float))
;; B is real
(let* ((length (length B))
(result (complex-zeros length)))
(declare (type (complex double-float) A)
(type (simple-array (complex double-float) (*)) result)
(type (vector double-float) B))
(dotimes (i length)
(setf (aref result i) (* A (aref B i))))
(return-from .* result))
;; B is complex
(let* ((length (length B))
(result (complex-zeros length)))
(declare (type (complex double-float) A)
(type (simple-array (complex double-float) (*)) result)
(type (vector (complex double-float)) B))
(dotimes (i length)
(setf (aref result i) (* A (aref B i))))
(return-from .* result)))))
(defmethod .* ((A number) (B simple-vector))
(declare (optimize speed)
(type double-float A)
(type simple-vector B))
(do-matrix-with-result (B (i) result (list (length B)))
(setf (aref result i) (* A (aref B i)))))
(defmethod .* ((A vector) (B number))
(.* B A))
(defgeneric .- (A B))
(defmethod .- (A B)
(.+ A (.* -1d0 B)))
(defmethod norm ((matrix array))
(.* (1/ (loop for element across (as-vector matrix)
maximize element))
matrix))
(defgeneric .^ (A B))
(defmethod .^ ((A array) (p integer))
(assert (squarep A))
(cond
((zerop p) (eye (array-dimension A 0)))
((= 1 p) A)
((> p 1) (.* A (.^ A (1- p))))
(t (error ".^ Not implemented for non-positive-integer powers"))))
(defgeneric ./ (A B))
(defmethod ./ ((A simple-array) (B number))
(do-matrix-with-result (result subs result (array-dimensions A))
(setf (apply #'aref result subs) (/ (apply #'aref A subs) B))))
(defmethod ./ ((A vector) (B number))
(do-matrix-with-result (A (i) result (list (length A)))
(setf (aref result i) (/ (aref A i) B))))
(defmethod ./ ((A number) (B number))
(/ A B))
(defun upper-matrix (matrix)
(with-result (result (array-dimensions matrix) (array-element-type matrix))
(loop
for i from 0 below (array-dimension matrix 1) by 1
with range = #r(0 -1)
do (setf (range-start range) i
(mref result i range ) (mref matrix i range)))))
(defun lower-matrix (matrix)
(with-result (result (array-dimensions matrix) (array-element-type matrix))
(loop
for i from 0 below (array-dimension matrix 1) by 1
with range = #r(0 -1)
do (setf (range-start range) i
(mref result range i) (mref matrix range i)))))
| 11,665 | Common Lisp | .lisp | 290 | 35.624138 | 118 | 0.624326 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 65e16ec14c69aefdee437b26433b6eed74da4b7bdadab63fd92b0c3e60017fb6 | 12,012 | [
-1
] |
12,013 | matrices.lisp~ | fisxoj_map/matrix/matrices.lisp~ | (in-package :map)
(deftype real-matrix () '(simple-array double-float *))
(deftype complex-matrix () '(simple-array (complex double-float) *))
(deftype matrix () '(simple-array (or real-matrix complex-matrix)))
(defun zeros (&rest dimensions)
(make-array dimensions :element-type 'double-float :initial-element 0.0d0))
(defun czeros (&rest dimensions)
(make-array dimensions :element-type '(complex double-float) :initial-element #c(0.0d0 0.0d0)))
(defun eye (dimension)
(loop with m = (zeros dimension dimension)
for i from 0 to (1- dimension)
do (setf (aref m i i) 1.0d0)
finally (return m)))
| 621 | Common Lisp | .lisp | 13 | 44.769231 | 97 | 0.711443 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 63439c5fe81292c376c241a48eae96de612212377533c77352d5e820ebd7f291 | 12,013 | [
-1
] |
12,014 | matrix-predicates.lisp~ | fisxoj_map/matrix/matrix-predicates.lisp~ | (in-package :map)
(export '(same-size-p
squarep
hermitianp))
(defun same-size-p (A B)
(loop for a in (mapcar #'= (array-dimensions A) (array-dimensions B))
when (not a) do (return nil)
finally (return t)))
(defun inner-dimensions-match-p (A B)
(let ((dimA (array-dimensions A))
(dimB (array-dimensions B)))
(and (= (second dimA) (first dimB)))))
(defun squarep (M)
(apply #'= (array-dimensions M)))
(defun hermitianp (M)
(and (loop for i from 0 to (1- (array-dimension M 0))
collect (loop for j from 0 to (- (array-dimension M 1) i 1)
collect (= (conjugate (aref M i j)) (aref M j i))))))
| 637 | Common Lisp | .lisp | 18 | 31.722222 | 71 | 0.63355 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | ccdaddbb0da9f050a8873060d6382a300fa45d2f6cd56a4562cd138f58969226 | 12,014 | [
-1
] |
12,015 | matrix-macros.lisp~ | fisxoj_map/matrix/matrix-macros.lisp~ | (in-package :map)
(defmacro loop-over-matrix (M indices &body body)
(loop
for var in indices
for i from 0 by 1
))
(defmacro compose-matrix-loop (M indices index &body body)
(if (not (cdr indices))
`(loop for ,@(car indices) from 0 to ,(array-dimension M index)
do ,(compose-matrix-loop M (cdr indices) (1- index body)))
body))
(defmacro loop-over-vector (V index)
) | 411 | Common Lisp | .lisp | 13 | 27.153846 | 69 | 0.664948 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 9b62b67ed52918815185c42101a02f87ff6bbf090a2537872388a5fba82ea922 | 12,015 | [
-1
] |
12,016 | integration.lisp | fisxoj_map/calculus/integration.lisp | ;; integration.lisp
;;
;; Copyright (c) 2012 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package :map)
(defun riemann (func range)
(loop for i from (range-start range)
to (range-stop range)
by (range-delta range)
sum (* (range-delta range) (funcall func i))))
| 1,089 | Common Lisp | .lisp | 27 | 38.592593 | 76 | 0.744098 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 710755d8ee2686f75ee90b8b56e295472b41952ebbc50a814a46bfeae0648382 | 12,016 | [
-1
] |
12,017 | rkf45.lisp | fisxoj_map/calculus/rkf45.lisp | ;; rkf45.lisp
;;
;; Copyright (c) 2012 Matt Novenstern <[email protected]>
;;
;; This code is free software; you can redistribute it and/or
;; modify it under the terms of the version 3 of
;; the GNU Affero General Public License as published by
;; the Free Software Foundation.
;;
;; This code is distributed in the hope that it will be useful,
;; but without any warranty; without even the implied warranty of
;; merchantability or fitness for a particular purpose. See the GNU
;; Affero General Public License for more details.
;;
;; Version 3 of the GNU Affero General Public License is in the file
;; LICENSE that was distributed with this file.
;; If it is not present, you can access it from
;; https://www.gnu.org/licenses/agpl.txt (until superseded by a newer
;; version) or write to the Free Software Foundation, Inc., 59 Temple Place,
;; Suite 330, Boston, MA 02111-1307 USA
;;
(in-package #:map)
(defun rkf45 (func range y0 &optional (tolerance 1d-7))
"rkf45
Implementation of the Runge-Kutta-Feldberg differential equation solver.
func: function handle that should accept a time, ti, and a Nx2
t-range: a map:range object that contains the start and stop values and a suggested step as the interval. Since the algorithm picks its own optimal step, it will use that value as guidance only.
tolerance: tolerance"
(declare (optimize (speed 3) (debug 0) (safety 0)))
(let* ((array-width (length (the vector y0)))
(array-length 100)
(ys (make-array (list array-length array-width) :element-type 'double-float :adjustable t))
(ts (make-array array-length :element-type 'double-float :adjustable t))
(step (/ (- (range-stop range) (range-start range)) 1d2)))
(declare (type function func)
(type double-float tolerance step)
(type (simple-vector *) y0)
(type (function (double-float (vector double-float)) (vector double-float)) func))
;; Set initial conditions from y0
(setf (aref ts 0) (range-start range))
(loop for j from 0 upto (1- array-width)
do (setf (aref ys 0 j) (aref y0 j)))
(loop
;; Just keep track of which element we're on...
for i from 1 by 1;; upto (1- array-length)
for ti = (the double-float (elt ts (1- i)))
;; Collect last step's y-values in a vector
for yi = (make-array array-width
:element-type 'double-float
:displaced-to ys
:displaced-index-offset (* array-width (1- i)))
;; Stop at the end of the given interval
until (>= ti (the double-float (range-stop range)))
; when (zerop (mod i 1000)) do (format t "Step size: ~g (time: ~d)~%" step ti)
do (setf array-length i)
do (loop
with looped = nil
;; do (format t "Step size: ~g~%" step)
do (let* ((k1 (.* step (funcall func ti yi)))
(k2 (.* step (funcall func (+ ti (* .25d0 step)) (.+ yi (.* .25d0 k1)))))
(k3 (.* step (funcall func (+ ti (* .375d0 step))
(reduce #'.+ (list yi (.* .09375d0 k1) (.* 0.28125d0 k2))))))
(k4 (.* step (funcall func (+ ti (* 0.9230769230769231d0 step))
(reduce #'.+ (list yi
(.* 0.8793809740555303d0 k1)
(.* -3.277196176604461d0 k2)
(.* 3.3208921256258535d0 k3))))))
(k5 (.* step (funcall func (+ ti step)
(reduce #'.+ (list yi
(.* 2.0324074074074074d0 k1)
(.* -8d0 k2) (.* 7.173489278752436d0 k3)
(.* -0.20589668615984405d0 k4))))))
(k6 (.* step (funcall func (+ ti (* .5d0 step))
(reduce #'.+ (list yi
(.* -0.2962962962962963d0 k1)
(.* 2d0 k2)
(.* -1.3816764132553607d0 k3)
(.* 0.4529727095516569d0 k4)
(.* -0.275d0 k5))))))
(rk4 (the (simple-array double-float *)
(reduce #'.+ (list yi
(.* 0.11574074074074074d0 k1)
(.* 0.5489278752436647d0 k3)
(.* 0.5353313840155945d0 k4)
(.* -.2d0 k5)))))
(rk5 (the (simple-array double-float *)
(reduce #'.+ (list yi
(.* 0.11851851851851852d0 k1)
(.* 0.5189863547758284d0 k3)
(.* 0.5061314903420167d0 k4)
(.* -0.18d0 k5)
(.* 0.03636363636363636d0 k6)))))
(err (/ (max (the double-float (norm (.- rk5 rk4))) double-float-epsilon)
tolerance)))
(declare (type double-float err))
;; If err is less > one, the step is not precise enough
;; if it's smaller than .1, it's too precise!
;; also, don't adjust the size more than once...
(if (and (not looped)
(or (> (abs err) 1d0)
;; I'm pretty ok with things being a bit too precise for now
(< (abs err) 1d-3)))
(setf step (* step 8d-1 (the double-float (expt (* 2d0 err) -1/6)))
looped t)
;; Error is low enough, keep the value
(progn
;; If there's not enough space, make the arrays longer
(when (= (1- (array-dimension ys 0)) i)
(adjust-array ys (list (* 2 (array-dimension ys 0)) array-width))
(adjust-array ts (* 2 (length ts))))
(setf (aref ts i) (+ (the double-float ti) step))
(loop for j from 0 upto (1- array-width)
do (setf (aref ys i j) (elt rk5 j)))
(return)))
)))
(values (adjust-array ts array-length)
(adjust-array ys (list array-length array-width)))
))
| 5,233 | Common Lisp | .lisp | 118 | 38.59322 | 195 | 0.622893 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 6d7a2833bd00e4d213ba3fbc0577a32f92921d999eb734e0a39210164adcc0d6 | 12,017 | [
-1
] |
12,018 | map.asd | fisxoj_map/map.asd | (defsystem :map
:serial t
:description "Octave-like functionality for lisp!"
:version "0.1.0"
:author "Matt Novenstern <[email protected]>"
:components ((:file "package")
(:file "conditions")
(:file "types")
(:module utilities
:components ((:file "printing")
(:file "missing-functions")
(:file "convenience")))
(:module vectors
:components ((:file "vector")
(:file "range")
(:file "vector-operations")))
(:module matrix
:components ((:file "matrices")
(:file "matrix-macros")
(:file "matrix-predicates")
(:file "matrix-multiply")
(:file "matrix-operations")
(:file "matrix-slices")
(:file "matrix-decomposition")
(:file "matrix-functions")))
(:module calculus
:components ((:file "integration")
(:file "rkf45")))
(:module plotting
:components ((:file "plot")))
(:module images
:components ((:file "image"))))
:depends-on (#:cl-jpeg #:external-program))
| 1,054 | Common Lisp | .asd | 33 | 24.818182 | 52 | 0.576885 | fisxoj/map | 8 | 0 | 5 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 12eb8b4de039d9c8b84e1ed5367a60afe9e34e0ad34c58d5fda95a805ce31685 | 12,018 | [
-1
] |
12,058 | device.lisp | ngwese_siren/matron/device.lisp | (in-package :matron)
(defctype ssize-t :int) ; MAINT: confirm against ssize_t
;;;
;;; device common
;;;
(defcenum dev-type-t
:dev-type-monome
:dev-type-hid
:dev-type-midi
:dev-type-count
:dev-type-invalid)
(defctype dev-start-t :pointer)
(defctype dev-deinit-t :pointer)
(defctype pthread-t :uint32) ; FIXME: this needs to be confirmed or dev-common-t is possibly wrong
(defcstruct dev-common-t
(type dev-type-t)
(id :uint32)
(tid pthread-t)
(path :string)
(serial :string)
(name :string)
(start dev-start-t)
(deinit dev-deinit-t))
;;;
;;; device monome
;;;
(defcenum device-monome-type-t
:device-monome-type-grid
:device-monome-type-arc)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defconstant +monome-buffer-size+ 256))
(defcstruct dev-monome-t
(dev (:struct dev-common-t))
(type device-monome-type-t)
(m monome:monome-ptr-t) ; libmonome device pointer
(data :uint8 :count 256) ; led data by quad
(dirty :bool :count 4))
(defctype dev-monome-ptr-t (:pointer (:struct dev-monome-t)))
(defcfun "dev_monome_grid_set_led" :void
(md dev-monome-ptr-t)
(x :uint8)
(y :uint8)
(val :uint8))
(defcfun "dev_monome_arc_set_led" :void
(md dev-monome-ptr-t)
(x :uint8)
(y :uint8)
(val :uint8))
(defcfun "dev_monome_all_led" :void
(md dev-monome-ptr-t)
(val :uint8))
(defcfun "dev_monome_set_quad" :void
(md dev-monome-ptr-t)
(quad :uint8)
(data (:pointer :uint8)))
(defcfun "dev_monome_refresh" :void (md dev-monome-ptr-t))
(defcfun "dev_monome_grid_rows" :int (md dev-monome-ptr-t))
(defcfun "dev_monome_grid_cols" :int (md dev-monome-ptr-t))
(defcfun "dev_monome_set_rotation" :void
(md dev-monome-ptr-t)
(val :uint8))
(defctype %monome-self-ptr-t (:pointer :void))
(defcfun "dev_monome_init" :int (self %monome-self-ptr-t))
(defcfun "dev_monome_deinit" :void (self %monome-self-ptr-t))
(defcfun "dev_monome_start" :void (self %monome-self-ptr-t))
;;;
;;; device hid
;;;
(defctype dev-vid-t :uint8)
(defctype dev-pid-t :uint8)
(defctype dev-code-t :uint16)
(defctype libevdev :void)
(defcstruct dev-hid-t
(base (:struct dev-common-t))
(dev (:pointer libevdev))
(vid dev-vid-t)
(pid dev-pid-t)
(num-types :int)
(types (:pointer :uint8))
(num-codes (:pointer :int))
(codes (:pointer (:pointer dev-code-t))))
(defctype %hid-self-ptr-t (:pointer :void))
(defcfun "dev_hid_init" :int (self %hid-self-ptr-t) (print :bool))
(defcfun "dev_hid_deinit" :void (self %hid-self-ptr-t))
(defcfun "dev_hid_start" (:pointer :void) (self %hid-self-ptr-t))
;;;
;;; device midi
;;;
(defctype snd-rawmidi-t :void)
(defcstruct dev-midi-t
(dev (:struct dev-common-t))
(handle-in (:pointer snd-rawmidi-t))
(handle-out (:pointer snd-rawmidi-t)))
(defctype %midi-self-ptr-t (:pointer :void))
(defcfun "dev_midi_init" :int (self %midi-self-ptr-t))
(defcfun "dev_midi_deinit" :void (self %midi-self-ptr-t))
(defcfun "dev_midi_start" (:pointer :void) (self %midi-self-ptr-t))
(defcfun "dev_midi_send" ssize-t
(self %midi-self-ptr-t)
(data (:pointer :uint8))
(n size-t))
;;;
;;; device
;;;
(defcunion dev-t
(base (:struct dev-common-t))
(monome (:struct dev-monome-t))
(hid (:struct dev-hid-t))
(midi (:struct dev-midi-t)))
(defctype dev-ptr-t (:pointer (:union dev-t)))
(defcfun "devices_init" :void)
(defcfun "dev_new" dev-ptr-t
(type dev-type-t)
(path :string)
(name :string))
(defcfun "dev_delete" :void (d dev-ptr-t))
(defcfun "dev_id" :int (d dev-ptr-t))
(defcfun "dev_serial" :string (d dev-ptr-t))
(defcfun "dev_name" :string (d dev-ptr-t))
;;;
;;; device list
;;;
(defcfun "dev_list_init" :void)
(defcfun "dev_list_add" :void
(type dev-type-t)
(node :string)
(name :string))
(defcfun "dev_list_remove" :void
(type dev-type-t)
(name :string))
;;;
;;; device monitor
;;;
(defcfun "dev_monitor_init" :void)
(defcfun "dev_monitor_deinit" :void)
(defcfun "dev_monitor_scan" :void)
| 3,932 | Common Lisp | .lisp | 136 | 26.713235 | 98 | 0.68379 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 9b0c6ed5223bdc37a92239fed9401e2900fd16e98014e16e22f0626f8be47386 | 12,058 | [
-1
] |
12,059 | package.lisp | ngwese_siren/matron/package.lisp | (defpackage :matron
(:use :common-lisp :cffi)
(:export
"GPIO-INIT"
"GPIO-DEINIT"
"I2C-INIT"
"I2C-DEINIT"
"I2C-HP"
"BATTERY-INIT"
"BATTERY-DEINIT"
;; screen functions
"SCREEN-INIT"
"SCREEN-DEINIT"
"SCREEN-UPDATE"
"SCREEN-SAVE"
"SCREEN-RESTORE"
"SCREEN-FONT-FACE"
"SCREEN-FONT-SIZE"
"SCREEN-AA"
"SCREEN-LEVEL"
"SCREEN-LINE"
"SCREEN-LINE-REL"
"SCREEN-LINE-WIDTH"
"SCREEN-LINE-CAP"
"SCREEN-LINE-JOIN"
"SCREEN-MITER-LIMIT"
"SCREEN-MOVE"
"SCREEN-MOVE-REL"
"SCREEN-CURVE"
"SCREEN-CURVE-REL"
"SCREEN-CURVE"
"SCREEN-ARC"
"SCREEN-RECT"
"SCREEN-STROKE"
"SCREEN-FILL"
"SCREEN-TEXT"
"SCREEN-CLEAR"
"SCREEN-CLOSE-PATH"
"SCREEN-EXTENTS"
;; screen helpers
"SCREEN-TEXT-CENTER"
"SCREEN-TEXT-RIGHT"
"SCREEN-CIRCLE"
;; screen cap/miter constants
"+CAP-BUTT+"
"+CAP-ROUND+"
"+CAP-SQUARE+"
"+JOIN-MITER+"
"+JOIN-ROUND+"
"+JOIN-BEVEL+"
;; events and types
"SIZE-T"
"EVENT-HANDLER-T"
"FREE-EVENT-DATA-T"
"POLL-TYPE-T"
"ENGINE-COMMAND-T"
"ENGINE-POLL-T"
"ENGINE-PARAM-T"
"OSC-MESSAGE-T"
"EVENT-T"
"QUAD-LEVELS-T"
"EVENT-COMMON-T"
"EVENT-EXEC-CODE-LINE-T"
"EVENT-MONOME-ADD-T"
"EVENT-MONOME-REMOVE-T"
"EVENT-GRID-KEY-T"
"EVENT-ARC-ENCODER-DELTA-T"
"EVENT-ARC-ENCODER-KEY-T"
"EVENT-HID-ADD-T"
"EVENT-HID-REMOVE-T"
"EVENT-HID-EVENT-T"
"EVENT-MIDI-ADD-T"
"EVENT-MIDI-REMOVE-T"
"EVENT-MIDI-EVENT-T"
"EVENT-OSC-T"
"EVENT-METRO-T"
"EVENT-KEY-T"
"EVENT-BATTERY-T"
"EVENT-POWER-T"
"EVENT-STAT-T"
"EVENT-ENC-T"
"EVENT-POLL-VALUE-T"
"EVENT-POLL-IO-LEVELS-T"
"EVENT-POLL-DATA-T"
"EVENT-POLL-WAVE-T"
"EVENT-STARTUP-READY-OK-T"
"EVENT-STARTUP-READY-TIMEOUT-T"
"EVENT-DATA-T"
"EVENT-DATA-PTR-T"
;; event globals, constants
"*EVENT-LOOP-QUIT*"
"+EVENT-WAVE-DISPLAY-BYTES+"
;; event functions
"EVENTS-INIT"
"EVENT-SET-HANDLER"
"EVENT-LOOP"
"EVENT-DATA-NEW"
"EVENT-DATA-FREE"
"EVENT-POST"
;; metro functions
"METROS-INIT"
"METRO-START"
"METRO-STOP"
"METRO-SET-TIME"
;; device
"SSIZE-T"
"DEVICE-T"
"DEV-START-T"
"DEV-DEINIT-T"
"DEV-COMMON-T"
"DEVICE-MONOME-TYPE-T"
"MONOME-T"
"+MONOME-BUFFER-SIZE+"
"DEV-MONOME-T"
"DEV-MONOME-PTR-T"
"DEV-MONOME-GRID-SET-LED"
"DEV-MONOME-ARC-SET-LED"
"DEV-MONOME-ALL-LED"
"DEV-MONOME-SET-QUAD"
"DEV-MONOME-REFRESH"
"DEV-MONOME-GRID-ROWS"
"DEV-MONOME-GRID-COLS"
"DEV-MONOME-SET-ROTATION"
"%MONOME-SELF-PTR-T"
"DEV-MONOME-INIT"
"DEV-MONOME-DEINIT"
"DEV-MONOME-START"
"DEV-VID-T"
"DEV-PID-T"
"DEV-CODE-T"
"DEV-HID-T"
"%HID-SELF-PTR-T"
"DEV-HID-INIT"
"DEV-HID-DEINIT"
"DEV-HID-START"
"DEV-MIDI-T"
"%MIDI-SELF-PTR-T"
"DEV-MIDI-INIT"
"DEV-MIDI-DEINIT"
"DEV-MIDI-START"
"DEV-MIDI-SEND"
"DEV-T"
"DEV-PTR-T"
"DEVICES-INIT"
"DEV-NEW"
"DEV-DELETE"
"DEV-ID"
"DEV-SERIAL"
"DEV-NAME"
"DEV-LIST-INIT"
"DEV-LIST-ADD"
"DEV-LIST-REMOVE"
"DEV-MONITOR-INIT"
"DEV-MONITOR-DEINIT"
"DEV-MONITOR-SCAN"
))
| 3,160 | Common Lisp | .lisp | 156 | 16.121795 | 34 | 0.629953 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 0d2d0745730e090ec8be60080f0f33c14f037625821862a09b65dbb196a87016 | 12,059 | [
-1
] |
12,060 | events.lisp | ngwese_siren/matron/events.lisp | (in-package :matron)
(defctype size-t :unsigned-int) ; MAINT: confirm against size_t
;;;
;;; callback types
;;;
(defctype event-handler-t :pointer)
(defctype free-event-data-t :pointer)
;;;
;;; oracle types
;;;
(defcenum poll-type-t
:poll-type-value
:poll-type-data)
(defcstruct engine-command-t
(name :string)
(format :string))
(defcstruct engine-poll-t
(name :string)
(type poll-type-t))
(defcstruct engine-param-t
(name :string)
(bus-idx :int))
;;;
;;; osc types
;;;
(defctype osc-message-t :pointer)
;;;
;;; event structures
;;;
(defcenum event-t
:event-first-event
:event-exec-code-line
:event-metro
:event-key
:event-enc
:event-battery
:event-power
:event-stat
:event-monome-add
:event-monome-remove
:event-grid-key
:event-arc-encoder-delta
:event-arc-encoder-key
:event-hid-add
:event-hid-remove
:event-hid-event
:event-midi-add
:event-midi-remove
:event-midi-event
:event-osc
:event-engine-report
:event-engine-loaded
:event-poll-value
:event-poll-data
:event-poll-wave
:event-poll-io-levels
:event-startup-ready-ok
:event-startup-ready-timeout
:event-reset-lvm
:event-quit)
(defcunion quad-levels-t
(bytes :uint8 :count 4)
(uint :uint32))
(defmacro %defevent (name &rest body)
`(defcstruct ,name
(common (:struct event-common-t))
,@body))
(defcstruct event-common-t
(type :uint32)
(free free-event-data-t))
(%defevent event-exec-code-line-t
(line :string))
(%defevent event-monome-add-t
(dev :pointer))
(%defevent event-monome-remove-t
(id :uint32))
(%defevent event-grid-key-t
(id :uint8)
(x :uint8)
(y :uint8)
(state :uint8))
(%defevent event-arc-encoder-delta-t
(id :uint8)
(number :uint8)
(delta :int8))
(%defevent event-arc-encoder-key-t
(id :uint8)
(number :uint8)
(state :int8))
(%defevent event-hid-add-t
(dev :pointer))
(%defevent event-hid-remove-t
(id :uint32))
(%defevent event-hid-event-t
(id :uint8)
(type :uint8)
(code :uint16)
(value :int32))
(%defevent event-midi-add-t
(dev :pointer))
(%defevent event-midi-remove-t
(id :uint32))
(%defevent event-midi-event-t
(id :uint32)
(data :uint8 :count 3)
(nbytes size-t))
(%defevent event-osc-t
(path :string)
(from-host :string)
(from-port :string)
(msg osc-message-t))
(%defevent event-metro-t
(id :uint32)
(stage :uint32))
(%defevent event-key-t
(id :uint8)
(val :uint8))
(%defevent event-battery-t
(percent :uint8)
(current :int16))
(%defevent event-power-t
(present :uint8))
(%defevent event-stat-t
(disk :uint16)
(temp :uint8)
(cpu :uint8))
(%defevent event-enc-t
(n :uint8)
(delta :int8))
(%defevent event-poll-value-t
(idx :uint32)
(value :float))
(%defevent event-poll-io-levels-t
(idx :uint32)
(value (:union quad-levels-t)))
(%defevent event-poll-data-t
(idx :uint32)
(size :uint32)
(data (:pointer :uint8)))
(%defevent event-poll-wave-t
(idx :uint32)
(data (:pointer :uint8)))
(%defevent event-startup-ready-ok-t)
(%defevent event-startup-ready-timeout-t)
(defcunion event-data-t
(type :uint32)
(common (:struct event-common-t))
(exec-code-line (:struct event-exec-code-line-t))
(monome-add (:struct event-monome-add-t))
(monome-remove (:struct event-monome-remove-t))
(grid-key (:struct event-grid-key-t))
(arc-encoder-delta (:struct event-arc-encoder-delta-t))
(arc-encoder-key (:struct event-arc-encoder-key-t))
(hid-add (:struct event-hid-add-t))
(hid-remove (:struct event-hid-remove-t))
(hid-event (:struct event-hid-event-t))
(midi-add (:struct event-midi-add-t))
(midi-remove (:struct event-midi-remove-t))
(midi-event (:struct event-midi-event-t))
(osc-event (:struct event-osc-t))
(key (:struct event-key-t))
(enc (:struct event-enc-t))
(battery (:struct event-battery-t))
(power (:struct event-power-t))
(stat (:struct event-stat-t))
(metro (:struct event-metro-t))
(poll-value (:struct event-poll-value-t))
(poll-data (:struct event-poll-data-t))
(poll-io-levels (:struct event-poll-io-levels-t))
(poll-wave (:struct event-poll-wave-t))
(startup-ready-ok (:struct event-startup-ready-ok-t))
(startup-ready-timeout (:struct event-startup-ready-timeout-t)))
;;;
;;; event api
;;;
(defctype event-data-ptr-t (:pointer (:union event-data-t)))
;; signals the event_loop to stop
(defcvar ("quit" *event-loop-quit*) :bool)
(defconstant +event-wave-display-bytes+ 128)
(defcfun "events_init" :void)
(defcfun "event_set_handler" :void (h event-handler-t))
(defcfun "event_loop" :void)
(defcfun "event_data_new" event-data-ptr-t
(evcode event-t)
(cb free-event-data-t))
(defcfun "event_data_free" :void
(ev event-data-ptr-t))
(defcfun "event_post" :void
(ev event-data-ptr-t))
| 4,752 | Common Lisp | .lisp | 189 | 22.592593 | 66 | 0.699558 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | d4dda1c95418621875924e4ac423865eb016078bdac4060466a7c21193507318 | 12,060 | [
-1
] |
12,061 | screen.lisp | ngwese_siren/matron/screen.lisp | (in-package :matron)
(defcfun "screen_init" :void)
(defcfun "screen_deinit" :void)
(defcfun "screen_update" :void)
(defcfun "screen_save" :void)
(defcfun "screen_restore" :void)
(defcenum screen-font
(:default-font 0)
(:04B_03 1)
(:aleph 2)
(:roboto-thin 3)
(:roboto-light 4)
(:roboto-regular 5)
(:roboto-medium 6)
(:roboto-bold 7)
(:roboto-black 8)
(:roboto-thin-italic 9)
(:roboto-light-italic 10)
(:roboto-italic 11)
(:roboto-medium-italic 12)
(:roboto-bold-italic 13)
(:roboto-black-italic 14))
(defcfun ("screen_font_face" %screen-font-face) :void (i :int))
(defun screen-font-face (enum)
"set current font by keyword"
(%screen-font-face (foreign-enum-value 'screen-font enum)))
(defcfun "screen_font_size" :void (z :double))
(defcfun "screen_aa" :void (s :int))
(defcfun "screen_level" :void (z :int))
(defcfun "screen_line" :void (x :double) (y :double))
(defcfun "screen_line_rel" :void (x :double) (y :double))
(defcfun "screen_line_width" :void (w :double))
(defconstant +cap-butt+ "butt")
(defconstant +cap-round+ "round")
(defconstant +cap-square+ "square")
(defcfun "screen_line_cap" :void (style :string))
(defconstant +join-miter+ "miter")
(defconstant +join-round+ "round")
(defconstant +join-bevel+ "bevel")
(defcfun "screen_line_join" :void (style :string))
(defcfun "screen_miter_limit" :void (limit :double))
(defcfun "screen_move" :void (x :double) (y :double))
(defcfun "screen_move_rel" :void (x :double) (y :double))
(defcfun "screen_curve" :void
(x1 :double)
(y1 :double)
(x2 :double)
(y2 :double)
(x3 :double)
(y3 :double))
(defcfun "screen_curve_rel" :void
(dx1 :double)
(dy1 :double)
(dx2 :double)
(dy2 :double)
(dx3 :double)
(dy3 :double))
(defcfun "screen_arc" :void
(x :double)
(y :double)
(r :double)
(a1 :double)
(a2 :double))
(defcfun "screen_rect" :void
(x :double)
(y :double)
(w :double)
(h :double))
(defcfun "screen_stroke" :void)
(defcfun "screen_fill" :void)
(defcfun "screen_text" :void (s :string))
(defcfun "screen_clear" :void)
(defcfun "screen_close_path" :void)
(defcfun ("screen_extents" %screen-extents) (:pointer :double) (s :string))
(defun screen-extents (s)
(let ((p (%screen-extents s)))
(values (mem-aref p :double 0)
(mem-aref p :double 1))))
;;;
;;; helpers
;;;
(defun screen-pixel (x y)
"draw single pixel (requires integer x/y, fill afterwards)"
(screen-rect x y 1d0 1d0))
(defun screen-text-right (s)
"draw text right justified at current vertical position"
(let ((x (screen-extents s)))
(screen-move-rel (- x) 0d0)
(screen-text s)))
(defun screen-text-center (s)
"draw text centered at current vertical position"
(let ((x (screen-extents s)))
(screen-move-rel (/ (- x) 2d0) 0d0)
(screen-text s)))
(defconstant +circle-arc-length+ (* pi 2))
(defun screen-circle (x y r)
"draw circle at x,y with the given radius"
(screen-arc x y r 0d0 +circle-arc-length+))
| 2,948 | Common Lisp | .lisp | 98 | 27.744898 | 75 | 0.682382 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | b2c0541417b763e8397ff9d4c96b3a6751fc66bb08898bfe7309e9c4c67fbdc2 | 12,061 | [
-1
] |
12,062 | ffi.lisp | ngwese_siren/matron/ffi.lisp | (in-package :matron)
(eval-when (:compile-toplevel :load-toplevel :execute)
(progn
;;
;; paths
;;
(setf (logical-pathname-translations "norns-src")
`(("**;*.*.*" #p"/home/we/norns/**/*.*")))
(setf (logical-pathname-translations "matron-build")
`(("**;*.*.*" "norns-src:build;matron;**;*.*")))
(setf (logical-pathname-translations "matron-src")
`(("**;*.*.*" "norns-src:matron;src;**;*.*")))
;;
;; libraries
;;
(cffi:define-foreign-library :cairo
(t (:default "libcairo")))
(cffi:define-foreign-library :freetype
(t (:default "libfreetype")))
(cffi:define-foreign-library :monome
(t (:default "libmonome")))
(cffi:define-foreign-library :udev
(t (:default "libudev")))
(cffi:define-foreign-library :evdev
(t (:default "libevdev")))
(cffi:define-foreign-library :pthread
(t (:default "libpthread")))
(cffi:define-foreign-library :matron
(t (:default "libmatron")))
(pushnew (translate-logical-pathname "matron-build:") cffi:*foreign-library-directories*
:test #'equal)
(defun load-libraries ()
(progn
(cffi:use-foreign-library :udev)
(cffi:use-foreign-library :evdev)
(cffi:use-foreign-library :cairo)
(cffi:use-foreign-library :freetype)
(cffi:use-foreign-library :monome)
(cffi:use-foreign-library :matron)))
(load-libraries)
))
;;;
;;; ffi
;;;
;;;
;;; ffi generation
;;;
;; (c-include
;; (translate-logical-pathname "matron-src:hardware;gpio.h")
;; :exclude-sources ("/usr*"))
;; (c-include
;; (translate-logical-pathname "matron-src:hardware;i2c.h")
;; :exclude-sources ("/usr*"))
;; (c-include
;; (translate-logical-pathname "matron-src:hardware;screen.h")
;; :exclude-sources ("/usr*"))
;; (c-include
;; (translate-logical-pathname "matron-src:hardware;battery.h")
;; :exclude-sources ("/usr*"))
;; (c-include
;; (translate-logical-pathname "matron-src:hardware;stat.h")
;; :exclude-sources ("/usr*"))
;; (c-include
;; (translate-logical-pathname "matron-src:device;device_hid.h")
;; :exclude-sources ("/usr*"))
;; (c-include
;; (translate-logical-pathname "matron-src:device;device_midi.h")
;; :exclude-sources ("/usr*"))
;; (c-include
;; (translate-logical-pathname "matron-src:device;device_monitor.h")
;; :exclude-sources ("/usr*"))
;; (c-include
;; (translate-logical-pathname "matron-src:device;device_monome.h")
;; :exclude-sources ("/usr*"))
;; (c-include
;; (translate-logical-pathname "matron-src:device;device_list.h")
;; :exclude-sources ("/usr*"))
;; (c-include
;; (translate-logical-pathname "matron-src:device;device.h")
;; :exclude-sources ("/usr*"))
;; (c-include
;; (translate-logical-pathname "matron-src:events.h")
;; :exclude-sources ("/usr*"))
;; (c-include
;; (translate-logical-pathname "matron-src:metro.h")
;; :exclude-sources ("/usr*"))
| 2,815 | Common Lisp | .lisp | 86 | 30.325581 | 89 | 0.671887 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 93155cbb1e8ba871da1598cf59401416b0d9cfddcbe27958a838cdf44213499b | 12,062 | [
-1
] |
12,063 | metro.lisp | ngwese_siren/matron/metro.lisp | (in-package :matron)
;;;(defconstant +max-num-metros+ ??)
(defcfun "metros_init" :void)
(defcfun "metro_start" :void
(idx :int)
(seconds :double)
(count :int)
(stage :int))
(defcfun "metro_stop" :void
(idx :int))
(defcfun "metro_set_time" :void
(idx :int)
(sec :float))
| 290 | Common Lisp | .lisp | 13 | 19.769231 | 36 | 0.656827 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 7b40e44f999d7cbd581da8e8d19a98dc387e15a0fd4d917d94ed96b58e9fbbf2 | 12,063 | [
-1
] |
12,064 | i2c.lisp | ngwese_siren/matron/i2c.lisp | (in-package :matron)
(defcfun "i2c_init" :void)
(defcfun "i2c_deinit" :void)
(defcfun "i2c_hp" :void (level :int))
| 117 | Common Lisp | .lisp | 4 | 27.75 | 37 | 0.693694 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | c25ccb84c2c104f573d0a5991c09c009f8bad1f02bc15a889a5634d447672476 | 12,064 | [
-1
] |
12,065 | ffi.lisp | ngwese_siren/sporth/ffi.lisp | (in-package :sporth)
;; /* This is a generated header file */
;; #ifdef MINIMAL
;; #include <stdlib.h>
;; #endif
;; enum {
;; SPORTH_FLOAT,
;; SPORTH_STRING,
;; SPORTH_IGNORE,
;; SPORTH_FUNC,
;; SPORTH_NOTOK,
;; SPORTH_OK,
;; SPORTH_WORD
;; };
(defcenum value-type-t
:sporth-float
:sporth-string
:sporth-ignore
:sporth-func
:sporth-notok
:sporth-ok
:sporth-word)
;; #define SPORTH_FOFFSET 2
;; #define SPORTH_MAXCHAR 200
;; #define SPORTH_STACK_SIZE 32
(defconstant +sporth-foffset+ 2)
(defconstant +sporth-maxchar+ 200)
(defconstant +sporth-stack-size+ (coerce 32 'real))
;; typedef struct {
;; float fval;
;; char *sval;
;; int type;
;; } sporth_stack_val;
(defcstruct sporth-stack-val-t
(fval :float)
(sval :string)
(type :int))
;; typedef struct {
;; int pos;
;; uint32_t error;
;; sporth_stack_val stack[SPORTH_STACK_SIZE];
;; } sporth_stack;
(defcstruct sporth-stack-t
(pos :int)
(error :uint32)
(stack (:struct sporth-stack-val-t) :count 32)) ; FIXME: switch to +sporth-stack-size+
(defctype sporth-stack-ptr-t (:pointer (:struct sporth-stack-t)))
;; typedef struct sporth_entry {
;; uint32_t val;
;; char *key;
;; struct sporth_entry *next;
;; } sporth_entry;
(defcstruct sporth-entry-t
(val :uint32)
(key :string)
(next (:pointer (:struct sporth-entry-t))))
;; typedef struct {
;; uint32_t count;
;; sporth_entry root;
;; sporth_entry *last;
;; } sporth_list ;
(defcstruct sporth-list-t
(count :uint32)
(root (:struct sporth-entry-t))
(last (:pointer (:struct sporth-entry-t))))
;; typedef struct {
;; sporth_list list[256];
;; } sporth_htable;
(defcstruct sporth-htable-t
(list sporth-list-t :count 256))
(defctype sporth-htable-ptr-t (:pointer sporth-htable-t))
;; typedef struct {
;; const char *name;
;; int (*func)(sporth_stack *, void *);
;; void *ud;
;; } sporth_func;
(defctype sporth-func-impl-t (:pointer :void))
(defcstruct sporth-func-t
(name :string)
(func sporth-func-impl-t) ; FIXME: define type for callback
(ud (:pointer :void)))
;; typedef struct sporth_data {
;; sporth_htable dict;
;; uint32_t nfunc;
;; sporth_func *flist;
;; sporth_stack stack;
;; } sporth_data;
(defcstruct sporth-data-t
(dict sporth-htable-t)
(nfunc :uint32)
(flist (:pointer (:struct sporth-func-t)))
(stack (:struct sporth-stack-t)))
;; uint32_t sporth_hash(const char *str);
(defcfun "sporth_hash" :uint32 (str :string))
;; int sporth_search(sporth_htable *ht, const char *key, uint32_t *val);
;; int sporth_htable_add(sporth_htable *ht, const char *key, uint32_t val);
;; int sporth_htable_init(sporth_htable *ht);
;; int sporth_htable_destroy(sporth_htable *ht);
(defcfun "sporth_search" :int
(ht sporth-htable-ptr-t)
(key :string)
(val :uint32))
(defcfun "sporth_htable_add" :int
(ht sporth-htable-ptr-t)
(key :string)
(val :uint32))
(defcfun "sport_htable_init" :int (ht sporth-htable-ptr-t))
(defcfun "sport_htable_destroy" :int (ht sporth-htable-ptr-t))
;; int sporth_stack_init(sporth_stack *stack);
;; int sporth_stack_push_float(sporth_stack *stack, float val);
;; int sporth_stack_push_string(sporth_stack *stack, char **str);
;; float sporth_stack_pop_float(sporth_stack *stack);
;; const char * sporth_stack_pop_string(sporth_stack *stack);
;; int sporth_check_args(sporth_stack *stack, const char *args);
;; int sporth_register_func(sporth_data *sporth, sporth_func *flist);
;; int sporth_exec(sporth_data *sporth, const char *keyword);
;; int sporth_init(sporth_data *sporth);
;; int sporth_destroy(sporth_data *sporth);
;; int sporth_stack_pos(sporth_stack *stack);
;; int sporth_gettype(sporth_data *sporth, char *str, int mode);
;; int sporth_parse(sporth_data *sporth, const char *filename);
;; char * sporth_tokenizer(const char *str,
;; uint32_t size, uint32_t *pos);
;; int sporth_lexer(char *str, int32_t size);
;; sporth_stack_val * sporth_stack_get_last(sporth_stack *stack);
;; size_t sporth_getline(char **lineptr, size_t *n, FILE *stream);
;; void sporth_print(sporth_data *sporth, const char *fmt, ...);
(defcenum sporth-token-t
(:sp-dummy 1) ; FIXME: this is (- +sporth-foffset+ 1)
:sporth-mul
:sporth-add
:sporth-sub
:sporth-div
:sporth-markleft
:sporth-markright
:sporth-and
:sporth-or
:sporth-xor
:sporth-leftshift
:sporth-rightshift
:sporth-mod
:sporth-abs
:sporth-adsr
:sporth-allpass
:sporth-atone
:sporth-autowah
:sporth-addv2
:sporth-ampdb
:sporth-bal
:sporth-biscale
:sporth-bitcrush
:sporth-blsaw
:sporth-blsquare
:sporth-bltriangle
:sporth-bpm2dur
:sporth-bpm2rate
:sporth-branch
:sporth-brown
:sporth-butbp
:sporth-butbr
:sporth-buthp
:sporth-butlp
:sporth-cdb
:sporth-cdbload
:sporth-cdbtab
:sporth-cf
:sporth-changed
:sporth-clip
:sporth-clock
:sporth-comb
:sporth-conv
:sporth-count
:sporth-crossfade
:sporth-dcblk
:sporth-delay
:sporth-diode
:sporth-diskin
:sporth-dist
:sporth-divv2
:sporth-dmetro
:sporth-drip
:sporth-drop
:sporth-dtrig
:sporth-dup
:sporth-dup2
:sporth-dur
:sporth-durs
:sporth-dust
:sporth-eq
:sporth-eqfil
:sporth-eval
:sporth-expon
:sporth-f
:sporth-fload
:sporth-floadi
:sporth-fclose
:sporth-fexec
:sporth-floor
:sporth-fm
:sporth-fof
:sporth-fofilt
:sporth-fog
:sporth-fosc
:sporth-frac
:sporth-ftsum
:sporth-gbuzz
:sporth-gen-eval
:sporth-gen-file
:sporth-gen-line
:sporth-gen-padsynth
:sporth-gen-sine
:sporth-gen-rand
:sporth-gen-composite
:sporth-gen-sinesum
:sporth-gen-sporth
:sporth-gen-vals
:sporth-get
:sporth-gt
:sporth-hilbert
:sporth-in
:sporth-incr
:sporth-inv
:sporth-jcrev
:sporth-jitter
:sporth-limit
:sporth-line
:sporth-load
:sporth-sdelay
:sporth-slice
:sporth-slist
:sporth-sqrt
:sporth-loadfile
:sporth-loadspa
:sporth-log
:sporth-log10
:sporth-lpc
:sporth-lpcsynth
:sporth-lpf18
:sporth-lsys
:sporth-lt
:sporth-max
:sporth-maygate
:sporth-maytrig
:sporth-metro
:sporth-mincer
:sporth-min
:sporth-mix
:sporth-mode
:sporth-moogladder
:sporth-mtof
:sporth-mulv2
:sporth-ne
:sporth-noise
:sporth-nsmp
:sporth-osc
:sporth-oscmorph4
:sporth-oscmorph2
:sporth-p
:sporth-palias
:sporth-pan
:sporth-panst
:sporth-pareq
:sporth-paulstretch
:sporth-pdhalf
:sporth-peaklim
:sporth-phaser
:sporth-phasor
:sporth-pinknoise
:sporth-pluck
:sporth-port
:sporth-pos
:sporth-posc3
:sporth-print
:sporth-prop
:sporth-polysporth
:sporth-pset
:sporth-psh
:sporth-pshift
:sporth-pst
:sporth-ptrack
:sporth-rand
:sporth-randh
:sporth-randi
:sporth-ref
:sporth-render
:sporth-reson
:sporth-reverse
:sporth-revsc
:sporth-rms
:sporth-rot
:sporth-round
:sporth-rpt
:sporth-rspline
:sporth-samphold
:sporth-saturator
:sporth-saw
:sporth-say
:sporth-scale
:sporth-scrambler
:sporth-set
:sporth-setdurs
:sporth-sget
:sporth-sine
:sporth-smoothdelay
:sporth-slick
:sporth-spa
:sporth-sparec
:sporth-square
:sporth-sr
:sporth-srand
:sporth-subv2
:sporth-streson
:sporth-swap
:sporth-switch
:sporth-tabread
:sporth-tadsr
:sporth-talias
:sporth-talkbox
:sporth-tbldur
:sporth-tblrec
:sporth-tblsize
:sporth-tdiv
:sporth-tenv
:sporth-tenv2
:sporth-tenvx
:sporth-tgate
:sporth-tget
:sporth-thresh
:sporth-timer
:sporth-tin
:sporth-tick
:sporth-tog
:sporth-tone
:sporth-tphasor
:sporth-tport
:sporth-tprop
:sporth-trand
:sporth-triangle
:sporth-tri
:sporth-tseq
:sporth-tseg
:sporth-tset
:sporth-var
:sporth-varset
:sporth-vdelay
:sporth-voc
:sporth-vocoder
:sporth-waveset
:sporth-writecode
:sporth-wpkorg35
:sporth-zeros
:sporth-zitarev
:sporth-zrev
:sporth-las)
;; #ifndef PLUMBER_H
;; #define PLUMBER_H
;; /* it just so happens that PLUMBER_OK and SPORTH_OK are the same values */
;; enum {
;; PLUMBER_CREATE,
;; PLUMBER_INIT,
;; PLUMBER_COMPUTE,
;; PLUMBER_DESTROY,
;; PLUMBER_NOTOK,
;; PLUMBER_OK,
;; PLUMBER_PANIC
;; };
;; enum {
;; PTYPE_NIL,
;; PTYPE_TABLE,
;; PTYPE_USERDATA
;; };
;; typedef int (* plumber_func) (sporth_stack *, void *) ;
;; typedef struct plumber_ftbl {
;; void *ud;
;; char *name;
;; char to_delete;
;; char type;
;; struct plumber_ftbl *next;
;; } plumber_ftbl;
;; typedef struct {
;; uint32_t nftbl;
;; plumber_ftbl root;
;; plumber_ftbl *last;
;; } plumber_ftentry;
;; typedef struct plumber_pipe {
;; uint32_t type;
;; size_t size;
;; void *ud;
;; struct plumber_pipe *next;
;; } plumber_pipe;
;; typedef struct {
;; plumber_func fun;
;; void *ud;
;; } sporth_func_d;
;; typedef struct {
;; uint32_t npipes;
;; int tick;
;; plumber_pipe root;
;; plumber_pipe *last;
;; } plumbing;
;; typedef struct plumber_data {
;; int mode;
;; uint32_t seed;
;; sp_data *sp;
;; FILE *fp;
;; char *filename;
;; sporth_data sporth;
;; plumbing *pipes;
;; /* for add_module function */
;; plumbing *tmp;
;; int current_pipe;
;; plumbing main, alt;
;; plumber_ftentry ft1[256];
;; plumber_ftentry ft2[256];
;; plumber_ftentry *ftmap;
;; plumber_ftentry *ftnew, *ftold;
;; char delete_ft;
;; SPFLOAT p[16];
;; void *ud;
;; plumber_pipe *next;
;; plumber_pipe *last;
;; sp_progress *prog;
;; int showprog;
;; int recompile;
;; int stacksize;
;; char *str;
;; FILE *log;
;; } plumber_data;
;; typedef int (* plumber_dyn_func) (plumber_data *, sporth_stack *, void **);
;; /* needed for dynamic loading */
;; typedef struct {
;; sporth_func_d *fd;
;; plumber_dyn_func fun;
;; plumber_dyn_func (*getter)(void);
;; int (*getter_multi)(int, plumber_dyn_func *);
;; const char *filename;
;; const char *name;
;; void *handle;
;; void *ud;
;; } sporth_fload_d;
;; #ifdef LIVE_CODING
;; #include <pthread.h>
;; typedef struct {
;; plumber_data *pd;
;; int start;
;; pthread_t thread;
;; int portno;
;; } sporth_listener;
;; void sporth_start_listener(sporth_listener *sl);
;; #endif
;; typedef struct {
;; unsigned short type;
;; void *ud;
;; } plumber_ptr;
;; int plumber_init(plumber_data *plumb);
;; int plumber_register(plumber_data *plumb);
;; int plumber_clean(plumber_data *plumb);
;; int plumber_add_float(plumber_data *plumb, plumbing *pipes, float num);
;; char * plumber_add_string(plumber_data *plumb, plumbing *pipes, const char *str);
;; int plumber_add_ugen(plumber_data *plumb, uint32_t id, void *ud);
;; int plumber_compute(plumber_data *plumb, int mode);
;; int plumber_parse(plumber_data *plumb);
;; int plumber_parse_string(plumber_data *plumb, const char *str);
;; int plumber_recompile(plumber_data *plumb);
;; int plumber_recompile_string(plumber_data *plumb, char *str);
;; plumbing *plumbing_choose(plumber_data *plumb,
;; plumbing *main, plumbing *alt, int *current_pipe);
;; int plumber_reinit(plumber_data *plumb);
;; int plumber_reparse(plumber_data *plumb);
;; int plumber_reparse_string(plumber_data *plumb, char *str);
;; int plumber_recompile_string(plumber_data *plumb, char *str);
;; int plumber_recompile_string_v2(plumber_data *plumb,
;; char *str,
;; void *ud,
;; int (*callback)(plumber_data *, void *));
;; int plumber_recompile_v2(plumber_data *plumb,
;; void *ud,
;; int (*callback)(plumber_data *, void *));
;; int plumber_swap(plumber_data *plumb, int error);
;; int plumber_open_file(plumber_data *plumb, const char *filename);
;; int plumber_close_file(plumber_data *plumb);
;; int plumber_gettype(plumber_data *plumb, char *str, int mode);
;; void plumber_show_pipes(plumber_data *plumb);
;; int plumber_error(plumber_data *plumb, const char *str);
;; int plumber_ftmap_init(plumber_data *plumb);
;; int plumber_ftmap_add(plumber_data *plumb, const char *str, sp_ftbl *ft);
;; int plumber_ftmap_add_userdata(plumber_data *plumb, const char *str, void *ud);
;; int plumber_ftmap_add_function(plumber_data *plumb,
;; const char *str, plumber_dyn_func f, void *ud);
;; int plumber_ftmap_search(plumber_data *plumb, const char *str, sp_ftbl **ft);
;; int plumber_ftmap_search_userdata(plumber_data *plumb, const char *str, void **ud);
;; int plumber_ftmap_destroy(plumber_data *plumb);
;; int plumber_ftmap_delete(plumber_data *plumb, char mode);
;; void plumber_ftmap_dump(plumber_ftentry *ft);
;; plumbing * plumber_get_pipes(plumber_data *plumb);
;; int plumber_search(plumber_data *plumb, const char *str, plumber_ftbl **ft);
;; int plumber_add(plumber_data *plumb, const char *str, plumber_ftbl **ft);
;; void sporth_run(plumber_data *pd, int argc, char *argv[],
;; void *ud, void (*process)(sp_data *, void *));
;; int plumber_lexer(plumber_data *plumb, plumbing *pipes, char *out, uint32_t len);
;; int plumbing_init(plumbing *pipes);
;; int plumbing_destroy(plumbing *pipes);
;; int plumbing_add_pipe(plumbing *pipes, plumber_pipe *pipe);
;; int plumbing_compute(plumber_data *plumb, plumbing *pipes, int mode);
;; int plumbing_parse(plumber_data *plumb, plumbing *pipes);
;; int plumbing_parse_string(plumber_data *plumb, plumbing *pipes, const char *str);
;; void plumbing_show_pipes(plumber_data *plumb, plumbing *pipes);
;; void plumbing_write_code(plumber_data *plumb, plumbing *pipes, FILE *fp);
;; void plumber_write_code(plumber_data *plumb, FILE *fp);
;; int plumber_process_null(sp_data *sp, void *ud, void (*callback)(sp_data *, void *));
;; int plumber_create_var(plumber_data *pd, const char *name, SPFLOAT **var);
;; int plumber_get_userdata(plumber_data *plumb, const char *name, plumber_ptr **p);
;; int polysporth_eval(plumber_ptr *p, const char *str);
;; void plumber_print(plumber_data *pd, const char *fmt, ...);
;; int plumber_cdbtab(plumber_data *pd, int fd, const char *key, sp_ftbl **ft);
;; int plumber_stack_pos(plumber_data *pd);
;; void plumber_check_stack(plumber_data *pd, int nitems);
;; #endif
| 14,106 | Common Lisp | .lisp | 518 | 25.104247 | 88 | 0.690527 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 75ff1980b3fcf84f5c3f70f3176f93d026ab5f20afb380c2a8367bad81e61402 | 12,065 | [
-1
] |
12,066 | test-screen.lisp | ngwese_siren/siren/test-screen.lisp | (in-package :siren-user)
(defun draw-demo ()
(screen-aa 1)
(screen-clear)
(screen-level 15)
(screen-line-width 1d0)
(screen-move 0d0 0d0)
(screen-line 10d0 20d0)
(screen-stroke)
;; draw arc: x-center, y-center, radius, angle1, angle2
(screen-arc 20d0 0d0 10d0 0d0 (* pi 0.8d0))
(screen-stroke)
;; draw rect: x,y,w,h
(screen-rect 30d0 10d0 15d0 20d0)
(screen-level 3)
(screen-stroke)
;; draw curve
(screen-move 50d0 0d0)
(screen-curve 50d0 20d0 60d0 0d0 70d0 10d0)
(screen-level 15)
(screen-stroke)
;; draw poly and fill
(screen-move 60d0 20d0)
(screen-line 80d0 10d0)
(screen-line 70d0 40d0)
(screen-close-path)
(screen-level 10)
(screen-fill)
;; draw circle
(screen-circle 100d0 20d0 10d0)
(screen-stroke)
(screen-level 15)
(screen-move 0d0 63d0)
;; set text face
(screen-font-face :roboto-thin-italic)
;; set text size
(screen-font-size 20d0)
;; draw text
(screen-text "new!")
;; draw centered text
(screen-move 63d0 50d0)
(screen-font-face :default-font)
(screen-font-size 8d0)
(screen-text-center "center")
;; draw right aligned text
(screen-move 127d0 63d0)
(screen-text-right "1992")
(screen-update))
(defun test-screen ()
(screen-init)
(gpio-init)
(battery-init)
(draw-demo)
(battery-deinit)
(gpio-deinit)
(screen-deinit))
| 1,351 | Common Lisp | .lisp | 56 | 20.964286 | 57 | 0.691406 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 3ca536e3a4c065d44cbf3344655a1009c85cb8d73608ce41932c797e6c887483 | 12,066 | [
-1
] |
12,067 | package.lisp | ngwese_siren/siren/package.lisp | (defpackage :siren
(:use :common-lisp :matron :bordeaux-threads))
(defpackage :siren-user
(:use :common-lisp :siren :matron :bordeaux-threads))
| 149 | Common Lisp | .lisp | 4 | 35 | 55 | 0.743056 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | b2723f520cbd8c39efcf8cf5ed99397648144587e82d2c5e53f099fd78a045ba | 12,067 | [
-1
] |
12,068 | test-controls.lisp | ngwese_siren/siren/test-controls.lisp | (in-package :siren-user)
(cffi:defcallback demo-handler :void ((ev event-data-ptr-t))
(let* ((type-num (cffi:foreign-slot-value ev '(:union event-data-t) 'type))
(type (cffi:foreign-enum-keyword 'event-t type-num)))
(case type
(:event-key
(cffi:with-foreign-slots ((matron::id matron::val) ev (:struct event-key-t))
(screen-clear)
(screen-level 15)
(screen-move 10d0 10d0)
(screen-text (format nil "id: ~D val: ~D" matron::id matron::val))
(screen-update)
))
(:event-enc
(cffi:with-foreign-slots ((matron::n matron::delta) ev (:struct event-enc-t))
(screen-clear)
(screen-level 15)
(screen-move 10d0 20d0)
(screen-text (format nil "n: ~D delta: ~D" matron::n matron::delta))
(screen-update)))
(otherwise
(format t "=> no match? ~A ~A~%" (type-of type) (type-of :event-type-key))
))
(event-data-free ev)))
(defun test-controls-init ()
(events-init) ;; must come first
(event-set-handler (cffi:callback demo-handler))
(screen-init)
(gpio-init) ; for keys
(i2c-init)) ; for enc
(defun test-controls-deinit ()
(i2c-deinit)
(gpio-deinit)
(screen-deinit))
| 1,151 | Common Lisp | .lisp | 34 | 30.088235 | 81 | 0.65343 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 5e5163fb905e848477a570e3a8038eba0bf40c552071977107d6ab944fdf6502 | 12,068 | [
-1
] |
12,069 | monome-device.lisp | ngwese_siren/siren/monome-device.lisp | (in-package :siren)
;;;
;;; monome-device: common grid/arc behavior
;;;
(defclass monome-device (matron-device) ())
(defmethod monome-ptr-of ((device monome-device))
(cffi:foreign-slot-value (dev-ptr-of device)
'(:struct matron:dev-monome-t)
'matron::m))
;; (defmethod led-buffer ((device monome-device))
;; (cffi:foreign-slot-value (dev-ptr-of device) '(:struct matron:dev-monome-t) 'matron::data))
(defmethod led-refresh ((device monome-device))
(matron:dev-monome-refresh (dev-ptr-of device)))
(defmethod led-all ((device monome-device) value)
(matron:dev-monome-all-led (dev-ptr-of device) (clip value 0 15)))
(declaim (inline clip))
(defun clip (x low high) (min (max low x) high))
; FIXME: this should actually error on out of bounds instead of clip
;; (defun buffer-value (buffer index)
;; (cffi:mem-aref buffer :uint8 (clip index 0 255)))
;; (defun (setf buffer-value) (value buffer index)
;; (setf (cffi:mem-aref buffer :uint8 (clip index 0 255)) value))
;;;
;;; grid-device
;;;
(defun null-grid-key-handler (x y z))
(defun null-grid-remove-handler (id))
(defclass grid-device (monome-device)
((key-handler :initarg :key-handler
:accessor key-handler-of
:initform #'null-grid-key-handler)
(remove-handler :initarg :remove-handler
:accessor remove-handler-of
:initform #'null-grid-remove-handler)
(rows :reader rows-of :initform 0)
(columns :reader columns-of :initform 0)))
(defmethod initialize-instance :after ((device grid-device) &key)
(with-slots (dev-ptr rows columns) device
(setf rows (dev-monome-grid-rows dev-ptr))
(setf columns (dev-monome-grid-cols dev-ptr))))
(defmethod led-set ((device grid-device) x y value)
(matron:dev-monome-grid-set-led (dev-ptr-of device) x y (clip value 0 15)))
;;;
;;; arc-device
;;;
(defclass arc-device (monome-device)
())
;; FIXME: check this; should it be x in 0-3 and y in 0-63?
(defmethod led-set ((device arc-device) x y value)
(matron:dev-monome-arc-set-led (dev-ptr-of device) x y (clip value 0 15)))
| 2,048 | Common Lisp | .lisp | 50 | 38.3 | 96 | 0.705051 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 2ceaa8b708ab346db5b5913cb19f8c752a3165603bb29661cde76f74652654bd | 12,069 | [
-1
] |
12,070 | matron-device.lisp | ngwese_siren/siren/matron-device.lisp | (in-package :siren)
(defvar *devices* '())
;; TODO: move this into matron code?
(defclass matron-device ()
((dev-ptr :initarg :dev-ptr :reader dev-ptr-of)))
(defmethod dev-type-of ((device matron-device))
(cffi:foreign-slot-value (dev-ptr-of device)
'(:struct matron:dev-common-t)
'matron::type))
(defmethod id-of ((device matron-device))
(cffi:foreign-slot-value (dev-ptr-of device)
'(:struct matron:dev-common-t)
'matron::id))
(defmethod name-of ((device matron-device))
(cffi:foreign-slot-value (dev-ptr-of device)
'(:struct matron:dev-common-t)
'matron::name))
(defmethod serial-of ((device matron-device))
(cffi:foreign-slot-value (dev-ptr-of device)
'(:struct matron:dev-common-t)
'matron::serial))
;;;
;;; device registration; should this be made generic for all matron-devices?
;;;
(defun register-device (device)
(pushnew device *devices* :key #'id-of))
(defmethod deregister-device ((device-id fixnum))
(setf *devices* (delete-if #'(lambda (d) (eq (id-of d) device-id))
*devices*)))
(defmethod deregister-device ((device matron-device))
(deregister-matron-device (id-of device)))
| 1,193 | Common Lisp | .lisp | 31 | 34.16129 | 76 | 0.675629 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | dbebde5e6fe00188b1d0b9a81c39347e89a049b16e1c8e0bdbc5826596afb010 | 12,070 | [
-1
] |
12,071 | test-device.lisp | ngwese_siren/siren/test-device.lisp | (in-package :siren-user)
(defvar *midi-devices* '())
(cffi:defcallback demo-handler :void ((ev event-data-ptr-t))
(let* ((type-num (cffi:foreign-slot-value ev '(:union event-data-t) 'type))
(type (cffi:foreign-enum-keyword 'event-t type-num)))
(case type
(:event-key
(cffi:with-foreign-slots ((matron::id matron::val) ev (:struct event-key-t))
(screen-clear)
(screen-level 15)
(screen-move 10d0 10d0)
(screen-text (format nil "id: ~D val: ~D" matron::id matron::val))
(screen-update)
))
(:event-enc
(cffi:with-foreign-slots ((matron::n matron::delta) ev (:struct event-enc-t))
(screen-clear)
(screen-level 15)
(screen-move 10d0 20d0)
(screen-text (format nil "n: ~D delta: ~D" matron::n matron::delta))
(screen-update)))
(:event-midi-event
(cffi:with-foreign-slots ((matron::id matron::data matron::nbytes) ev (:struct event-midi-event-t))
(handle-event-midi-event matron::id matron::data matron::nbytes)))
(:event-midi-add
(cffi:with-foreign-slots ((matron::dev) ev (:struct event-midi-add-t))
(handle-event-midi-add matron::dev)))
(:event-midi-remove
(cffi:with-foreign-slots ((matron::id) ev (:struct event-midi-remove-t))
(handle-event-midi-remove matron::id)))
(:event-hid-event
(cffi:with-foreign-slots ((matron::id matron::type matron::code matron::value)
ev (:struct event-hid-event-t))
(handle-event-hid-event matron::id matron::type matron::code matron::value)))
(:event-hid-add
(handle-event-hid-add (cffi:foreign-slot-value ev '(:struct event-hid-add-t)
'matron::dev)))
(:event-hid-remove
(handle-event-hid-remove (cffi:foreign-slot-value ev '(:struct event-hid-remove-t)
'matron::id)))
(:event-grid-key
(cffi::with-foreign-slots ((matron::id matron::x matron::y matron::state) ev
(:struct event-grid-key-t))
(handle-event-grid-key matron::id matron::x matron::y matron::state)))
(:event-arc-encoder-delta
(cffi:with-foreign-slots ((matron::id matron::number matron::delta) ev
(:struct event-arc-encoder-delta-t))
(handle-event-arc-encoder-delta matron::id matron::number matron::delta)))
(:event-arc-encoder-key
(cffi:with-foreign-slots ((matron::id matron::number matron::state) ev
(:struct event-arc-encoder-key-t))
(handle-event-arc-encoder-key matron::id matron::number matron::state)))
(:event-monome-add
(handle-event-monome-add (cffi:foreign-slot-value ev '(:struct event-monome-add-t)
'matron::dev)))
(:event-monome-remove
(handle-event-monome-remove (cffi:foreign-slot-value ev '(:struct event-monome-remove-t)
'matron::id)))
(:event-metro
(cffi:with-foreign-slots ((matron::id matron::stage) ev
(:struct event-metro-t))
(handle-event-metro matron::id matron::stage)))
(otherwise
(format t "=> no match? ~A ~A~%" (type-of type) (type-of :event-type-key))
))
(event-data-free ev)))
;;;
;;; metro
;;;
(defun handle-event-metro (id stage)
(format t "metro: id=~D stage=~D~%" id stage))
;;;
;;; hid
;;;
(defun handle-event-hid-add (dev-ptr)
(let ((device (make-instance 'siren::hid-device :dev-ptr dev-ptr)))
(siren::register-device device)
(format t "hid add: id=~D name=~A // ~A~%" (siren::id-of device) (siren::name-of device) siren::*devices*)))
(defun handle-event-hid-remove (dev-id)
(siren::deregister-device dev-id)
(format t "hid remove: ~D // ~A~%" dev-id siren::*devices*))
(defun handle-event-hid-event (id type code value)
(format t "hid event: id=~D type=~D code=0x~X value=~D~%" id type code value))
;;;
;;; midi
;;;
(defun handle-event-midi-add (dev-ptr)
(let ((device (make-instance 'siren::midi-device :dev-ptr dev-ptr)))
(siren::register-device device)
(format t "midi add: id=~D name=~A // ~A~%" (siren::id-of device) (siren::name-of device) siren::*devices*)))
(defun handle-event-midi-remove (dev-id)
(siren::deregister-device dev-id)
(format t "midi remove: ~D // ~A~%" dev-id siren::*devices*))
(defun handle-event-midi-event (dev-id data num-bytes)
(format t "midi event: ~D ~A ~D~%" dev-id data num-bytes))
;;;
;;; grid/arc
;;;
(defun handle-event-monome-add (dev-ptr)
(cffi:with-foreign-slots ((matron::type matron::m) dev-ptr (:struct dev-monome-t))
(case matron::type
(:device-monome-type-arc
(let ((arc (make-instance 'siren::arc-device :dev-ptr dev-ptr)))
(siren::register-device arc)
(format t "monome (arc) add: id=~D name=~A // ~A~%" (siren::id-of arc) (siren::name-of arc) siren::*devices*)))
(:device-monome-type-grid
(let ((grid (make-instance 'siren::grid-device :dev-ptr dev-ptr)))
(siren::register-device grid)
(format t "monome (grid) add: id=~D name=~A // ~A~%" (siren::id-of grid) (siren::name-of grid) siren::*devices*)))
(otherwise
(error "unrecognized device type")))))
(defun handle-event-monome-remove (dev-id)
(siren::deregister-device dev-id)
(format t "monome remove: ~D // ~A~%" dev-id siren::*devices*))
(defun handle-event-grid-key (id x y state)
(format t "grid key: ~D ~D ~D ~D~%" id x y state))
(defun handle-event-arc-encoder-delta (id number delta)
(format t "arc encoder: ~D ~D ~D~%" id number delta))
(defun handle-event-arc-encoder-key (id number state)
(format t "arc key: ~D ~D ~D~%" id number state))
;;;
;;; test
;;;
(defun test-device-init ()
(events-init) ;; must come first
(event-set-handler (cffi:callback demo-handler))
(screen-init)
(metros-init)
(gpio-init) ; for keys
(i2c-init) ; for enc
(dev-list-init)
(dev-monitor-init))
(defun test-device-deinit ()
(dev-monitor-deinit)
(i2c-deinit)
(gpio-deinit)
(screen-deinit))
(defvar *event-loop-mutex* (make-lock "event-loop-mutex"))
(defvar *event-loop-thread* nil)
(defun event-loop-start ()
(flet ((event-loop-body ()
;; insert logging?
(matron:event-loop)
(with-lock-held (*event-loop-mutex*)
(if (eq *event-loop-thread* (current-thread))
(setf *event-loop-thread* nil)))))
(with-lock-held (*event-loop-mutex*)
(if (not *event-loop-thread*)
(progn
(setf matron:*event-loop-quit* nil)
(let ((thread (make-thread #'event-loop-body :name "matron-event-loop")))
(setf *event-loop-thread* thread)))))))
;; NOTE: the matron event loop is fully blocking so the join here
;; won't happen until some event (like a key press happens)
(defun event-loop-stop ()
(let ((thread *event-loop-thread*))
(if thread
(progn
(setf matron:*event-loop-quit* t)
(join-thread thread)))))
| 6,570 | Common Lisp | .lisp | 160 | 37.2 | 117 | 0.662327 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 29358126db2637d65d59ac569cc1a1b0599edf64b5d05e8f2f1130a8f6fdd7cf | 12,071 | [
-1
] |
12,072 | package.lisp | ngwese_siren/monome/package.lisp | (defpackage :monome
(:use :common-lisp :cffi)
(:export
"MONOME-EVENT-TYPE-T"
"MONOME-ROTATE-T"
"MONOME-T"
"MONOME-PTR-T"
"MONOME-EVENT-T"
"MONOME-EVENT-PTR-T"
"MONOME-EVENT-CALLBACK-T"
"MONOME-SET-ROTATION"
"MONOME-GET-ROTATION"
"MONOME-GET-SERIAL"
"MONOME-GET-DEVPATH"
"MONOME-GET-FRIENDLY-NAME"
"MONOME-GET-PROTO"
"MONOME-GET-ROWS"
"MONOME-GET-COLS"
"MONOME-LED-SET"
"MONOME-LED-ON"
"MONOME-LED-OFF"
"MONOME-LED-ALL"
"MONOME-LED-MAP"
"MONOME-LED-COL"
"MONOME-LED-ROW"
"MONOME-LED-INTENSITY"
"MONOME-LED-LEVEL-SET"
"MONOME-LED-LEVEL-ALL"
"MONOME-LED-LEVEL-MAP"
"MONOME-LED-LEVEL-ROW"
"MONOME-LED-LEVEL-COL"
"MONOME-EVENT-GET-GRID"
"MONOME-LED-RING-SET"
"MONOME-LED-RING-ALL"
"MONOME-LED-RING-MAP"
"MONOME-LED-RING-RANGE"
"MONOME-TILT-ENABLE"
"MONOME-TILT-DISABLE"
))
| 886 | Common Lisp | .lisp | 39 | 18.692308 | 29 | 0.667063 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 29951ca4ae9686bd36be1d9b382e0dea070842780a52bbc9e9663a57fee9ffaf | 12,072 | [
-1
] |
12,073 | ffi.lisp | ngwese_siren/monome/ffi.lisp | (in-package :monome)
(defctype size-t :unsigned-int) ; FIXME: check this, would be better to cffi-grovel this
;; typedef enum {
;; MONOME_BUTTON_UP = 0x00,
;; MONOME_BUTTON_DOWN = 0x01,
;; MONOME_ENCODER_DELTA = 0x02,
;; MONOME_ENCODER_KEY_UP = 0x03,
;; MONOME_ENCODER_KEY_DOWN = 0x04,
;; MONOME_TILT = 0x05,
;; /* update this if you add event types */
;; MONOME_EVENT_MAX = 0x06
;; } monome_event_type_t;
(defcenum monome-event-type-t
(:monome-button-up #x00)
(:monome-button-down #x01)
(:monome-encoder-delta #x02)
(:monome-encoder-key-up #x03)
(:monome-encoder-key-down #x04)
(:monome-tilt #x05))
;; /* grid rotation */
;; typedef enum {
;; MONOME_ROTATE_0 = 0,
;; MONOME_ROTATE_90 = 1,
;; MONOME_ROTATE_180 = 2,
;; MONOME_ROTATE_270 = 3
;; } monome_rotate_t;
(defcenum monome-rotate-t
(:monome-rotate-0 0)
(:monome-rotate-90 1)
(:monome-rotate-180 2)
(:monome-rotate-270 3))
;; typedef struct monome monome_t; /* opaque data type */
(defctype monome-ptr-t :pointer)
;; struct monome_event {
;; monome_t *monome;
;; monome_event_type_t event_type;
;; /* __extension__ for anonymous unions in gcc */
;; __extension__ union {
;; struct {
;; unsigned int x;
;; unsigned int y;
;; } grid;
;; struct {
;; unsigned int number;
;; int delta;
;; } encoder;
;; struct {
;; unsigned int sensor;
;; int x;
;; int y;
;; int z;
;; } tilt;
;; };
;; };
(defcstruct monome-event-grid-data-t
(x :unsigned-int)
(y :unsigned-int))
(defcstruct monome-event-encoder-data-t
(number :unsigned-int)
(delta :int))
(defcstruct monome-event-tilt-data-t
(sensor :unsigned-int)
(x :int)
(y :int)
(z :int))
(defcunion monome-event-data-t
(grid (:struct monome-event-grid-data-t))
(encoder (:struct monome-event-encoder-data-t))
(tilt (:struct monome-event-tilt-data-t)))
(defcstruct monome-event-t
(monome monome-ptr-t)
(event-type monome-event-type-t)
(data (:union monome-event-data-t)))
;; typedef struct monome_event monome_event_t;
(defctype monome-event-ptr-t (:pointer monome-event-t))
;; typedef void (*monome_event_callback_t)
;; (const monome_event_t *event, void *data);
(defctype monome-event-callback-t :pointer)
;; monome_t *monome_open(const char *monome_device, ...);
;; void monome_close(monome_t *monome);
;; void monome_set_rotation(monome_t *monome, monome_rotate_t cable);
(defcfun "monome_set_rotation" :void
(monome monome-ptr-t)
(cable monome-rotate-t))
;; monome_rotate_t monome_get_rotation(monome_t *monome);
(defcfun "monome_get_rotation" monome-rotate-t (monome monome-ptr-t))
;; const char *monome_get_serial(monome_t *monome);
(defcfun "monome_get_serial" :string (monome monome-ptr-t))
;; const char *monome_get_devpath(monome_t *monome);
(defcfun "monome_get_devpath" :string (monome monome-ptr-t))
;; const char *monome_get_friendly_name(monome_t *monome);
(defcfun "monome_get_friendly_name" :string (monome monome-ptr-t))
;; const char *monome_get_proto(monome_t *monome);
(defcfun "monome_get_proto" :string (monome monome-ptr-t))
;; int monome_get_rows(monome_t *monome);
(defcfun "monome_get_rows" :int (monome monome-ptr-t))
;; int monome_get_cols(monome_t *monome);
(defcfun "monome_get_cols" :int (monome monome-ptr-t))
;; int monome_register_handler(monome_t *monome, monome_event_type_t event_type,
;; monome_event_callback_t, void *user_data);
;; int monome_unregister_handler(monome_t *monome,
;; monome_event_type_t event_type);
;; int monome_event_next(monome_t *monome, monome_event_t *event_buf);
;; int monome_event_handle_next(monome_t *monome);
;; void monome_event_loop(monome_t *monome);
;; int monome_get_fd(monome_t *monome);
;; /**
;; * led grid commands
;; */
;; int monome_led_set(monome_t *monome, unsigned int x, unsigned int y,
;; unsigned int on);
(defcfun "monome_led_set" :int
(monome monome-ptr-t)
(x :unsigned-int)
(y :unsigned-int)
(on :unsigned-int))
;; int monome_led_on(monome_t *monome, unsigned int x, unsigned int y);
(defcfun "monome_led_on" :int
(monome monome-ptr-t)
(x :unsigned-int)
(y :unsigned-int))
;; int monome_led_off(monome_t *monome, unsigned int x, unsigned int y);
(defcfun "monome_led_off" :int
(monome monome-ptr-t)
(x :unsigned-int)
(y :unsigned-int))
;; int monome_led_all(monome_t *monome, unsigned int status);
(defcfun "monome_led_all" :int
(monome monome-ptr-t)
(status :unsigned-int))
;; int monome_led_map(monome_t *monome, unsigned int x_off, unsigned int y_off,
;; const uint8_t *data);
(defcfun "monome_led_map" :int
(monome monome-ptr-t)
(x-offset :unsigned-int)
(y-offset :unsigned-int)
(data (:pointer :uint8)))
;; int monome_led_col(monome_t *monome, unsigned int x, unsigned int y_off,
;; size_t count, const uint8_t *col_data);
(defcfun "monome_led_col" :int
(monome monome-ptr-t)
(x :unsigned-int)
(y-offset :unsigned-int)
(count size-t)
(column-data (:pointer :uint8)))
;; int monome_led_row(monome_t *monome, unsigned int x_off, unsigned int y,
;; size_t count, const uint8_t *row_data);
(defcfun "monome_led_row" :int
(monome monome-ptr-t)
(x-offset :unsigned-int)
(y :unsigned-int)
(count size-t)
(row-data (:pointer :uint8)))
;; int monome_led_intensity(monome_t *monome, unsigned int brightness);
(defcfun "monome_led_intensity" :int
(monome monome-ptr-t)
(brightness :unsigned-int))
;; int monome_led_level_set(monome_t *monome, unsigned int x, unsigned int y,
;; unsigned int level);
(defcfun "monome_led_level_set" :int
(monome monome-ptr-t)
(x :unsigned-int)
(y :unsigned-int)
(level :unsigned-int))
;; int monome_led_level_all(monome_t *monome, unsigned int level);
(defcfun "monome_led_level_all" :int
(monome monome-ptr-t)
(level :unsigned-int))
;; int monome_led_level_map(monome_t *monome, unsigned int x_off,
;; unsigned int y_off, const uint8_t *data);
(defcfun "monome_led_level_map" :int
(monome monome-ptr-t)
(x-offset :unsigned-int)
(y-offset :unsigned-int)
(data (:pointer :uint8)))
;; int monome_led_level_row(monome_t *monome, unsigned int x_off,
;; unsigned int y, size_t count, const uint8_t *data);
(defcfun "monome_led_level_row" :int
(monome monome-ptr-t)
(x-offset :unsigned-int)
(y :unsigned-int)
(count size-t)
(data (:pointer :uint8)))
;; int monome_led_level_col(monome_t *monome, unsigned int x, unsigned int y_off,
;; size_t count, const uint8_t *data);
(defcfun "monome_led_level_col" :int
(monome monome-ptr-t)
(x :unsigned-int)
(y-offset :unsigned-int)
(count size-t)
(data (:pointer :uint8)))
;; int monome_event_get_grid(const monome_event_t *e,
;; unsigned int *out_x, unsigned int *out_y,
;; monome_t **monome);
(defcfun "monome_event_get_grid" :int
(event monome-event-ptr-t)
(out-x (:pointer :unsigned-int))
(out-y (:pointer :unsigned-int))
(monome (:pointer monome-ptr-t)))
;; /**
;; * led ring commands
;; */
;; int monome_led_ring_set(monome_t *monome, unsigned int ring, unsigned int led,
;; unsigned int level);
(defcfun "monome_led_ring_set" :int
(monome monome-ptr-t)
(ring :unsigned-int)
(led :unsigned-int)
(level :unsigned-int))
;; int monome_led_ring_all(monome_t *monome, unsigned int ring,
;; unsigned int level);
(defcfun "monome_led_ring_all" :int
(monome monome-ptr-t)
(ring :unsigned-int)
(level :unsigned-int))
;; int monome_led_ring_map(monome_t *monome, unsigned int ring,
;; const uint8_t *levels);
(defcfun "monome_led_ring_map" :int
(monome monome-ptr-t)
(ring :unsigned-int)
(levels (:pointer :uint8)))
;; int monome_led_ring_range(monome_t *monome, unsigned int ring,
;; unsigned int start, unsigned int end,
;; unsigned int level);
(defcfun "monome_led_ring_range" :int
(monome monome-ptr-t)
(ring :unsigned-int)
(start :unsigned-int)
(end :unsigned-int)
(level :unsigned-int))
;; int monome_tilt_enable(monome_t *monome, unsigned int sensor);
(defcfun "monome_tilt_enable" :int
(monome monome-ptr-t)
(sensor :unsigned-int))
;; int monome_tilt_disable(monome_t *monome, unsigned int sensor);
(defcfun "monome_tilt_disable" :int
(monome monome-ptr-t)
(sensor :unsigned-int))
| 8,551 | Common Lisp | .lisp | 238 | 33.869748 | 90 | 0.663477 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | c9af169a9154e1bf9d568cba8c5dc0112b84c82422b3c062c218ba0ec97873d7 | 12,073 | [
-1
] |
12,074 | sporth.asd | ngwese_siren/sporth.asd | ;;; -*- mode: common-lisp -*-
(defpackage :sporth.asdf
(:use #:cl #:asdf))
(in-package :sporth.asdf)
(defsystem :sporth
:depends-on (:cffi)
:pathname "sporth"
:serial t
:components
((:file "package")
(:file "ffi")))
| 236 | Common Lisp | .asd | 11 | 18.636364 | 29 | 0.631818 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 54ca7ee459698bebf937e216d81394ef0632f0f5e17a0b945460d3cc96ec2267 | 12,074 | [
-1
] |
12,075 | monome.asd | ngwese_siren/monome.asd | ;;; -*- mode: common-lisp -*-
(defpackage :monome.asdf
(:use #:cl #:asdf))
(in-package :monome.asdf)
(defsystem :monome
:depends-on (:cffi)
:pathname "monome"
:serial t
:components
((:file "package")
(:file "ffi")))
| 236 | Common Lisp | .asd | 11 | 18.636364 | 29 | 0.631818 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | f94a4888798009814761c305cf2c8ffe5c81b5425c3fba52ce4fd2ede47ea5a6 | 12,075 | [
-1
] |
12,076 | matron.asd | ngwese_siren/matron.asd | ;;; -*- mode: lisp -*-
(require 'cffi)
(defpackage :matron.asdf
(:use #:cl #:asdf))
(in-package :matron.asdf)
(defsystem :matron
:description "ffi for mid level matron api"
:version "0.1"
:depends-on (:cffi :monome)
:pathname "matron"
:serial t
:components
((:file "package")
(:file "ffi")
(:file "gpio")
(:file "i2c")
(:file "battery")
(:file "screen")
(:file "stat")
(:file "metro")
(:file "events")
(:file "device")))
| 473 | Common Lisp | .asd | 22 | 18.136364 | 45 | 0.60181 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | f04dd5f0f0e5ecbeb6a83b0df141afc189d3ae4431bc59740da912b9e3bb7065 | 12,076 | [
-1
] |
12,077 | siren.asd | ngwese_siren/siren.asd | ;;; -*- mode: lisp -*-
(defpackage :siren.asdf
(:use #:cl #:asdf))
(in-package :siren.asdf)
(defsystem :siren
:depends-on (:matron :bordeaux-threads)
:pathname "siren"
:serial t
:components
((:file "package")
(:file "matron-device")
(:file "monome-device")
(:file "midi-device")
(:file "hid-device")))
| 331 | Common Lisp | .asd | 14 | 20.571429 | 41 | 0.634615 | ngwese/siren | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 6478a89092c00caed8122e13ee3eb6d6fd07e4c688f1014ea7423a3d0eec5bc5 | 12,077 | [
-1
] |
12,109 | ffprobe.lisp | Ambrevar_fof/ffprobe.lisp | (uiop:define-package fof/ffprobe
(:nicknames #:ffprobe)
(:documentation "FFprobe abstraction.")
(:use #:common-lisp)
(:use #:trivia)
(:import-from #:hu.dwim.defclass-star #:defclass*)
(:import-from #:serapeum #:export-always)
(:import-from #:cl-json))
(in-package fof/ffprobe)
(eval-when (:compile-toplevel :load-toplevel :execute)
(trivial-package-local-nicknames:add-package-local-nickname :alex :alexandria))
(defvar *ffprobe-command* "ffprobe")
;; TODO: Should leave unspecified fields unbound?
(defclass* disposition ()
((default 0)
(dub 0)
(original 0)
(comment 0)
(lyrics 0)
(karaoke 0)
(forced 0)
(hearing-impaired 0)
(visual-impaired 0)
(clean-effects 0)
(attached-pic 0)
(timed-thumbnails 0))
(:accessor-name-transformer (hu.dwim.defclass-star:make-name-transformer name))
(:export-accessor-names-p t)
(:export-class-name-p t))
(defclass* media-stream () ; REVIEW: `stream' is reserved by CL.
((index 0)
(codec-name "")
(codec-long-name "")
(profile "")
(codec-type "")
(width 0)
(height 0)
(coded-width 0)
(coded-height 0)
(closed-captions 0)
(has-b-frames 0)
(pix-fmt "")
(level 0)
(color-range "")
(color-space "")
(color-transfer "")
(color-primaries "")
(chroma-location "")
(field-order "")
(refs 0)
(id "")
(quarter-sample nil
:type boolean)
(divx-packed nil
:type boolean)
(sample-aspect-ratio "")
(display-aspect-ratio "")
(codec-time-base "") ; TODO: Ratio?
(codec-tag-string "")
(codec-tag "") ; TODO: Hex?
(sample-fmt "")
(sample-rate 0)
(channels 2)
(channel-layout "")
(bits-per-sample 0)
(dmix-mode 0)
(ltrt-cmixlev 0.0)
(ltrt-surmixlev 0.0)
(loro-cmixlev 0.0)
(loro-surmixlev 0.0)
(is-avc nil
:type boolean)
(nal-length-size 0)
(r-frame-rate "") ; TODO: Ratio?
(avg-frame-rate "") ; TODO: Ratio?
(time-base "")
(start-pts 0)
(start-time 0.0)
(duration-ts 0.0)
(duration 0.0)
(bit-rate 0)
(bits-per-raw-sample 0)
(nb-frames 0)
(max-bit-rate 0)
(disposition nil
:type (or null disposition))
(side-data-list '())
(tags '()))
(:accessor-name-transformer (hu.dwim.defclass-star:make-name-transformer name))
(:export-accessor-names-p t)
(:export-class-name-p t))
(defclass* media-format () ; REVIEW: `format' is reserved by CL.
((filename "")
(nb-streams 0)
(nb-programs 0)
(format-name "")
(format-long-name "")
(start-time 0.0)
(duration 0.0)
(size 0)
(bit-rate 0)
(probe-score 0)
(tags '()))
(:accessor-name-transformer (hu.dwim.defclass-star:make-name-transformer name))
(:export-accessor-names-p t)
(:export-class-name-p t))
(defun normalize-cl-json-keywords (sym)
"Turn '--' to '-' and remove '+' from keywords."
(if (keywordp sym)
(intern (str:replace-all
"+" ""
(str:replace-all "--" "-" (symbol-name sym)))
"KEYWORD")
sym))
(defun normalize-cl-json-scalar (value)
"Turn non-ratio number string to numbers."
(if (stringp value)
(match value
("true" t)
("false" nil)
(_ (let ((result (ignore-errors (parse-number:parse-number value))))
(if (and result
(not (typep result 'ratio)))
result
value))))
value))
(defun json->media-args (json)
(alex:mappend (lambda-match
((cons key value)
(list (normalize-cl-json-keywords key)
(if (listp value)
(json->media-args value)
(normalize-cl-json-scalar value)))))
json))
(export-always 'ffprobe)
(defun ffprobe (path)
"Return a list of (MEDIA-FORMAT MEDIA-STREAMS...)."
(let* ((json-string
(ignore-errors ; TODO: Report errors instead?
(uiop:run-program (list *ffprobe-command*
"-v" "quiet"
"-print_format" "json"
"-show_format"
"-show_streams"
"--"
path)
:output '(:string :stripped t)))))
(when json-string
(let* ((json (cl-json:decode-json-from-string json-string))
(format-args (json->media-args (alex:assoc-value json :format)))
(format (apply #'make-instance 'media-format format-args)))
(cons format
(mapcar (lambda (s)
(let ((stream-args (json->media-args s)))
(apply #'make-instance 'media-stream stream-args)))
(alex:assoc-value json :streams)))))))
| 5,154 | Common Lisp | .lisp | 156 | 24.198718 | 83 | 0.526959 | Ambrevar/fof | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 6295187889dac6a66b575ab136c500bd26d4016df7c3f2672914a190cae9c903 | 12,109 | [
-1
] |
12,110 | package.lisp | Ambrevar_fof/package.lisp | (uiop:define-package fof/package
(:nicknames fof)
(:documentation "File object finder.
This is the meta package which includes all others.")
(:import-from #:trivial-package-local-nicknames)
(:use-reexport
#:fof/file
#:fof/predicates))
| 249 | Common Lisp | .lisp | 8 | 28.375 | 53 | 0.742739 | Ambrevar/fof | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | d5233715ec70e97af947858f016059149652f96f134432257ad2f22d85fc2a85 | 12,110 | [
-1
] |
12,111 | predicates.lisp | Ambrevar_fof/predicates.lisp | (uiop:define-package fof/predicates ; TODO: Name?
(:nicknames fof/p)
(:documentation "All predicates for the FOF finder.")
(:use #:common-lisp
#:fof/file)
;; (:import-from #:alexandria)
;; (:import-from #:hu.dwim.defclass-star #:defclass*)
(:import-from #:local-time)
;; (:import-from #:magicffi)
(:import-from #:serapeum
#:export-always
#:->)
(:import-from #:str)
(:import-from #:trivia #:match))
(in-package fof/p)
(eval-when (:compile-toplevel :load-toplevel :execute)
(trivial-package-local-nicknames:add-package-local-nickname :sera :serapeum))
(export-always 'date<)
(defun date< (timestamp)
"Return a file predicate that matches on modification time less recent than TIMESTAMP."
(lambda (file)
(local-time:timestamp< (modification-date file) timestamp)))
(export-always 'date>)
(defun date> (timestamp)
"Return a file predicate that matches on modification time more recent than TIMESTAMP."
(lambda (file)
(local-time:timestamp> (modification-date file) timestamp)))
(export-always 'extension=)
(defun extension= (extension &rest more-extensions)
"Return a predicate for files that match one of the provided extensions."
(lambda (file)
(some (sera:equals (extension file))
(cons extension more-extensions))))
(export-always 'kind=)
(-> kind= (file-kind &rest file-kind) function)
(defun kind= (kind &rest more-kinds)
"Return a predicate for files that match one of the provided `file-kind's."
(lambda (file)
(some (sera:eqs (kind file))
(cons kind more-kinds))))
(deftype user-specifier ()
"A `string' identifies the user name, a `fixnum' the user ID."
`(or string fixnum))
(export-always 'user=)
(-> user= (user-specifier &rest user-specifier) function)
(defun user= (user &rest more-users)
"Return a predicate for files that match one of the provided `user-specifier's."
(lambda (file)
(let ((user-name (user file)))
(some (lambda (user)
(typecase user
(string (string= user-name user))
(number (= user (user-id file)))))
(cons user more-users)))))
(deftype group-specifier ()
"A `string' identifies the group name, a `fixnum' the group ID."
`(or string fixnum))
(export-always 'group=)
(-> group= (group-specifier &rest group-specifier) function)
(defun group= (group &rest more-groups)
"Return a predicate for files that match one of the provided `group-specifier's."
(lambda (file)
(let ((group-name (group file)))
(some (lambda (group)
(typecase group
(string (string= group-name group))
(number (= group (group-id file)))))
(cons group more-groups)))))
(export-always 'path~)
(defun path~ (path-element &rest more-path-elements)
"Return a predicate that matches when one of the path elements is contained in
the file path."
(apply #'fof/file::match-path path-element more-path-elements))
(export-always 'path$)
(defun path$ (path-suffix &rest more-path-suffixes)
"Return a predicate that matches when one of the path suffixes matches
the file path."
(apply #'fof/file::match-path-end path-suffix more-path-suffixes))
(export-always 'name~)
(defun name~ (name &rest more-names)
"Return a predicate that matches when one of the names is contained in the
file basename. "
(lambda (file)
(some (lambda (name)
(str:contains? name (basename file)))
(cons name more-names))))
(defun depth< (level &optional (root (file *default-pathname-defaults*)))
"Return a predicate that matches when the argument file is in a subdirectory
of ROOT less deep than LEVEL."
(apply #'fof/file::match-depth< level root))
(export-always 'executable?)
(defun executable? (file)
(intersection
(permissions file)
'(:user-exec :group-exec :other-exec)))
(export-always 'hidden?)
(defun hidden? (file)
(str:starts-with? "." (basename file)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(export-always 'elf-binary?)
(defun elf-binary? (file)
(and (slot-boundp file 'mime-type)
(string= "application/x-executable" (mime-type file))))
(export-always 'elf-library?)
(defun elf-library? (file)
(and (slot-boundp file 'mime-type)
(ppcre:scan "application/x-sharedlib" (first (mime-type file)))))
| 4,378 | Common Lisp | .lisp | 107 | 36.607477 | 89 | 0.671056 | Ambrevar/fof | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | bde7462124d4e2b2250fe5f4caf18ebb680138706215de5b85d6fe5f9a934001 | 12,111 | [
-1
] |
12,112 | mediafile.lisp | Ambrevar_fof/mediafile.lisp | (uiop:define-package fof/mediafile
(:documentation "Mediafile class (audio, video, pictures).")
(:use #:common-lisp)
(:import-from #:hu.dwim.defclass-star #:defclass*)
(:import-from #:serapeum #:export-always)
(:use #:fof)
(:import-from #:fof/ffprobe))
(in-package fof/mediafile)
(eval-when (:compile-toplevel :load-toplevel :execute)
(trivial-package-local-nicknames:add-package-local-nickname :alex :alexandria)
(trivial-package-local-nicknames:add-package-local-nickname :sera :serapeum))
;; TODO: Add reader table + #mf print-object.
(defclass* mediafile (file+mime) ; REVIEW: Include MIME?
((media-format nil
:type (or null fof/ffprobe:media-format))
(media-streams '()
:type (or null
(cons fof/ffprobe:media-stream))))
(:accessor-name-transformer (hu.dwim.defclass-star:make-name-transformer name))
(:export-accessor-names-p t)
(:export-class-name-p t))
(defmethod initialize-instance :after ((file mediafile) &key)
(let ((probe (fof/ffprobe:ffprobe (path file))))
(setf (media-format file) (first probe)
(media-streams file) (rest probe))))
(defmethod print-object ((file mediafile) stream)
(let ((*print-object-reader-macro* "#MF"))
(fof/file::print-file file stream)))
(defun mediafile-reader (stream char1 char2)
(declare (ignore char1 char2))
(when (eq (read-char stream nil :eof) #\f)
(fof/file::read-until stream #\")
(mediafile (fof/file::read-until stream #\"))))
(export-always 'syntax)
(named-readtables:defreadtable fof/mediafile::syntax
(:merge :standard)
;; TODO: Can we merge fof/file::syntax instead of redefining #f?
(:dispatch-macro-char #\# #\f #'fof/file::file-reader)
(:dispatch-macro-char #\# #\m #'mediafile-reader))
(export-always 'mediafile)
(defun mediafile (path)
(make-instance 'mediafile :path path))
(export-always 'mediafinder*)
(defun mediafinder* (&rest args
&key
(root *default-pathname-defaults*)
predicates
recur-predicates)
(declare (ignore root predicates recur-predicates))
(let ((*finder-constructor* #'mediafile))
(apply #'finder* args)))
(export-always 'mediafinder)
(defun mediafinder (&rest predicate-specifiers)
(let ((*finder-constructor* #'mediafile))
(apply #'finder predicate-specifiers)))
(export-always 'width)
(defmethod width ((file mediafile))
(fof/ffprobe:width
(find-if #'plusp (media-streams file)
:key #'fof/ffprobe:width)))
(export-always 'height)
(defmethod height ((file mediafile))
(fof/ffprobe:height
(find-if #'plusp (media-streams file)
:key #'fof/ffprobe:height)))
(export-always 'tags)
(defmethod tags ((file mediafile))
;; TODO: Get tags from streams too?
(fof/ffprobe:tags (media-format file)))
| 2,899 | Common Lisp | .lisp | 69 | 36.347826 | 83 | 0.666785 | Ambrevar/fof | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 949f2a9a69b1da2c7edef683aca318c045d217058b5fbaaa0b2bdd9a770189a1 | 12,112 | [
-1
] |
12,113 | file.lisp | Ambrevar_fof/file.lisp | (uiop:define-package fof/file
(:documentation "File class.")
(:use #:common-lisp)
(:import-from #:alexandria)
(:import-from #:hu.dwim.defclass-star #:defclass*)
(:import-from #:local-time)
(:import-from #:magicffi)
(:import-from #:osicat)
(:import-from #:serapeum #:export-always)
(:import-from #:str)
(:import-from #:trivia #:match))
(in-package fof/file)
(eval-when (:compile-toplevel :load-toplevel :execute)
(trivial-package-local-nicknames:add-package-local-nickname :alex :alexandria)
(trivial-package-local-nicknames:add-package-local-nickname :sera :serapeum))
(defvar *touch-command* "touch") ; TODO: `utime' syscall binding is missing from Osicat.
;; TODO: Use `file-attributes' when
;; https://github.com/Shinmera/file-attributes/issues/1 is fixed.
;; TODO: Add option to follow symlinks or not.
;; TODO: Run multiple disk writes within a transation?
;; Need proper POSIX bindings. Can Osicat do all of them?
;; Could we edit files virtually? Does that even make sense?
;; TODO: Replace magicffi with trivial-mime once we can get MIME encoding
;; (https://github.com/Shinmera/trivial-mimes/issues/8), description, and fix
;; the probe-file issue.
(export-always 'file-kind)
(deftype file-kind ()
`(member :directory
:character-device
:block-device
:regular-file
:symbolic-link
:socket
:pipe))
(defclass* file ()
((path (error "Path required")
:type string
:reader t)
(inode 0
:reader t)
(link-count 0
:reader t)
(kind :regular-file ; "kind" because `type' is reserved by CL.
:type file-kind
:reader t)
(size 0
:reader t)
(disk-usage 0
:reader t)
(user-id 0)
(group-id 0)
;; TODO: Include blocks?
(creation-date (local-time:unix-to-timestamp 0)
:reader t)
(modification-date (local-time:unix-to-timestamp 0))
(access-date (local-time:unix-to-timestamp 0))
(permissions '()
:type (or null
(cons #.(cons 'member (mapcar #'first osicat::+permissions+))))))
(:accessor-name-transformer (hu.dwim.defclass-star:make-name-transformer name))
(:export-slot-names-p t)
(:export-class-name-p t))
(defmethod (setf user-id) (id (file file))
(osicat-posix::chown (path file) id (group-id file))
(setf (slot-value file 'user-id) id))
(defmethod (setf group-id) (id (file file))
(osicat-posix::chown (path file) (user-id file) id)
(setf (slot-value file 'group-id) id))
;; TODO: For now, date setters rely on GNU touch. Find a portable version.
(defmethod (setf modification-date) (timestamp (file file))
"Set both the `modification-date' and the `access-date' of FILE."
(uiop:run-program (list *touch-command*
(format nil "--date=~a" (local-time:format-rfc3339-timestring nil timestamp))
(path file)))
(setf (slot-value file 'modification-date) timestamp)
(setf (slot-value file 'access-date) timestamp))
(defmethod (setf access-date) (timestamp (file file))
(uiop:run-program (list *touch-command*
"-a"
(format nil "--date=~a" (local-time:format-rfc3339-timestring nil timestamp))
(path file)))
(setf (slot-value file 'modification-date) timestamp))
(defmethod (setf permissions) (permissions (file file))
(setf (osicat:file-permissions (path file)) permissions)
(setf (slot-value file 'permissions) permissions))
(defmethod path ((s string))
"Useful so that `path' can be called both on a `file' or a `string'."
s)
(defmethod path ((p pathname))
"Useful so that `path' can be called both on a `file' or a `pathname'."
(namestring p))
(defmethod (setf path) (new-path (file file))
"Set FILE to a NEW-PATH.
This renames the file."
(unless (handler-case (or (ignore-errors (rename-file (path file) new-path))
;; Fallback since `rename-file' does not work cross-device.
(uiop:run-program (list "mv" (path file) new-path)))
(error (c)
(warn "Renaming ~s to ~s failed: ~a" (path file) new-path c)
:error))
(setf (path file) new-path)))
(export-always 'user)
(defmethod user ((file file))
"Return the name of the user owning the file."
(nth-value 0 (alex:assoc-value (osicat:user-info (user-id file)) :name)))
(defun read-/etc/group ()
(let ((content (alex:read-file-into-string "/etc/group")))
(mapcar (alex:curry #'str:split ":") (str:split (string #\newline) content))))
(defun group-id->name (id)
(let ((result (find (write-to-string id) (fof/file::read-/etc/group)
:key #'caddr :test #'string=)))
(when result
(first result))))
(export-always 'group)
(defmethod group ((file file))
"Return the name of the group owning the file."
(group-id->name (group-id file)))
(export-always 'extension)
(defmethod extension ((file file))
"Return the file extension.
If none, return the empty string unlike `pathname-type'."
(or (pathname-type (path file))
""))
(defmethod (setf extension) (new-extension (file file))
"Set the FILE extension to NEW-EXTENSION.
This renames the file."
(setf (path file)
(str:concat (namestring (uiop:pathname-directory-pathname (path file)))
(pathname-name (path file))
"."
new-extension)))
(export-always 'directory?)
(defmethod directory? ((file file))
(eq (kind file) :directory))
(export-always 'file?)
(defmethod file? ((file file))
(eq (kind file) :regular-file))
(export-always 'file=?)
(defun file=? (file1 file2)
"Return true if FILE1 and FILE2 point to the same file.
They might not be the same objects."
(and (typep file1 'file) (typep file2 'file)
(string= (path file1)
(path file2))))
(export-always 'separator)
(defun separator (&optional char?)
(if char?
(uiop:directory-separator-for-host)
(string (uiop:directory-separator-for-host))))
(export-always 'basename)
(defmethod basename ((file file))
"Return the file basename (including the extension).
This returns the directory name for directories."
(let* ((path (path file))
(path (if (str:ends-with? (separator) path)
(subseq path 0 (1- (length path)))
path))
(last-separator (position (separator :char)
path :from-end t)))
(subseq path
(1+ last-separator))))
(export-always 'exists?)
(defmethod exists? ((file file))
(and
(if (directory? file)
(uiop:directory-exists-p (path file))
(uiop:file-exists-p (path file)))
file))
(export-always 'parent)
(defmethod parent ((file file))
"Return the parent directory of FILE."
(file
(if (directory? file)
(uiop:pathname-parent-directory-pathname (path file))
(uiop:pathname-directory-pathname (path file)))))
(export-always 'current-directory)
(defun current-directory ()
(file *default-pathname-defaults*))
(export-always 'with-current-directory)
(defmacro with-current-directory ((&optional file) &body body)
"Call BODY while the POSIX current working directory is set to FILE.
This is just like `uiop:with-current-directory' except that it takes a `file'
object."
`(uiop:call-with-current-directory ,(path file) #'(lambda () ,@body)))
(defmethod disk-usage* ((file file))
"Compute recursive `disk-usage' of FILE if a directory.
Return the new disk-usage."
(if (directory? file)
(if (list-directory file)
(reduce #'+ (mapcar #'disk-usage* (list-directory file)))
(size file))
(slot-value file 'disk-usage)))
(defmethod disk-usage ((file file))
"Return FILE `disk-usage'.
If FILE is a directory and it's disk-usage is 0 (never computed before), set it
with `disk-usage*' and return the new value."
(if (or (file? file)
(/= 0 (slot-value file 'disk-usage)))
(slot-value file 'disk-usage)
(disk-usage* file)))
(defun depth (file parent)
(cond
((file=? file parent)
0)
((file=? file (parent file))
0)
(t
(1+ (depth (parent file) parent)))))
(export-always 'relative-path)
(defmethod relative-path ((file file) &optional (parent-directory (current-directory)))
"Return PATH relative to PARENT-DIRECTORY.
If PARENT-DIRECTORY is not a parent of PATH, return PATH."
(if (str:starts-with? (path parent-directory)
(path file))
(subseq (path file) (length (path parent-directory)))
(path file)))
(defun shorten-home (path)
(let ((home (uiop:getenv "HOME")))
(if (str:starts-with? home path)
(str:replace-first home "~" path)
path)))
(defun shorten-path (path &key (abbreviation-length 1) ; TODO: Is there a library for this?
(abbreviate-home t)
(ellipsis "…"))
(let* ((path (if abbreviate-home
(shorten-home path)
path))
(elements
(str:split (separator) path
:omit-nulls t)))
(if elements
(str:concat (when (str:starts-with? (separator) path)
(separator))
(str:join
(separator)
(append
(mapcar (lambda (dir)
(if (<= (length dir) (+ abbreviation-length (length ellipsis)))
dir
(str:concat
(subseq dir 0 abbreviation-length)
ellipsis)))
(butlast elements))
(list (first (last elements)))))
(when (str:ends-with? (separator) path)
(separator)))
path)))
(defparameter +ls-time-format+
'(:short-month #\space (:day 2 #\ ) #\space (:hour 2) #\: (:min 2)))
(export-always '*print-reader-macro*)
(defvar *print-reader-macro* "#F")
(export-always '*print-relative-path?*)
(defvar *print-relative-path?* nil)
(export-always '*print-abbreviation-length*)
(defvar *print-abbreviation-length* 2
"Set to 0 to stop abbreviating.")
(export-always '*print-size?*)
(defvar *print-size?* nil)
(export-always '*print-date?*)
(defvar *print-date?* nil)
(defun print-file (file stream
&key
(reader-macro *print-reader-macro*)
(relative-path? *print-relative-path?*)
(abbreviation-length *print-abbreviation-length*)
(size? *print-size?*)
(date? *print-date?*))
(let ((path (if relative-path?
(relative-path file)
(path file))))
(format stream "~a\"~a~a~a\""
reader-macro
(if (= 0 abbreviation-length)
path
(shorten-path path :abbreviation-length abbreviation-length))
(if (and (directory? file)
(not (str:ends-with? "/" (path file))))
"/" "")
(str:concat
(when size?
(str:concat " " (sera:format-human-size nil (size file) :space nil)))
(when date?
(str:concat " " (local-time:format-timestring nil (modification-date file)
:format +ls-time-format+)))))))
;; TODO: Support `*print-pretty*'?
;; TODO: `*print-readably*'?
;; TODO: Auto-update file when mtime changes? Wouldn't it be too slow?
(defmethod print-object ((file file) stream)
(print-file file stream))
(export-always 'file)
(defmethod initialize-instance :after ((file file) &key)
(let* ((path (path file))
(native-path (uiop:truename* (if (pathnamep path)
path
(uiop:parse-native-namestring path)))))
(unless (or (uiop:file-exists-p native-path)
(uiop:directory-exists-p native-path))
(error "~s is not a file path" (or native-path path)))
;; TODO: What do we do with non-existent files (e.g. unsaved emacs buffers)? Just return nil?
(setf (slot-value file 'path) (uiop:unix-namestring native-path))
;; Use `lstat' to _not_ follow symlinks, unlike `stat'.
(let ((stat (ignore-errors (osicat-posix:lstat native-path))))
(if stat
;; From Osicat's `file-permissions':
(flet ((stat-permissions (stat)
(let ((mode (osicat-posix:stat-mode stat)))
(loop for (name . value) in osicat::+permissions+
when (plusp (logand mode value))
collect name))))
(setf
(slot-value file 'inode) (osicat-posix:stat-ino stat)
(slot-value file 'link-count) (osicat-posix:stat-nlink stat)
(slot-value file 'kind) (osicat:file-kind native-path) ; TODO: Don't recall `stat'.
(slot-value file 'size) (osicat-posix:stat-size stat)
(slot-value file 'disk-usage) (* 512 (osicat-posix:stat-blocks stat)) ; 512 as per (2)stat.
(slot-value file 'user-id) (osicat-posix:stat-uid stat)
(slot-value file 'group-id) (osicat-posix:stat-gid stat)
(slot-value file 'creation-date) (local-time:unix-to-timestamp (osicat-posix:stat-ctime stat))
(slot-value file 'modification-date) (local-time:unix-to-timestamp (osicat-posix:stat-mtime stat))
(slot-value file 'access-date) (local-time:unix-to-timestamp (osicat-posix:stat-atime stat))
(slot-value file 'permissions) (stat-permissions stat)))
;; Errors may happen in particular for broken symlinks, see
;; https://github.com/osicat/osicat/issues/40
(warn "Failed to retrieve ~s metadata" (slot-value file 'path))))))
(defun file (path)
(make-instance 'file :path path))
(defun read-until (stream delimiter)
"Return the string read until DELIMITER."
(concatenate 'string
(loop :for char = (read-char stream nil :eof)
:while (and (not (eq char :eof))
(not (char= char delimiter)))
:collect char)))
(defun file-reader (stream char1 char2)
(declare (ignore char1 char2))
(read-until stream #\")
(file (read-until stream #\")))
(export-always 'syntax)
(named-readtables:defreadtable fof/file::syntax
(:merge :standard)
(:dispatch-macro-char #\# #\f #'file-reader))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(export-always 'list-directory)
(defun list-directory (&optional (path (current-directory)) sort)
"Return entries in PATH.
By default, directories come first.
If SORT is non nil, sort them alphabetically.
Second value is the list of directories, third value is the non-directories."
;; TODO: Use locale to sort?
(let* ((subdirs (mapcar #'file (uiop:subdirectories (path path))))
(subfiles (mapcar #'file (uiop:directory-files (path path))))
(result (append subdirs subfiles)))
(values
(if sort
(sort result #'string< :key #'path)
result)
subdirs
subfiles)))
(export-always '*finder-include-directories*)
(defvar *finder-include-directories* t ; TODO: Use?
"When non-nil `finder' includes directories.")
(export-always '*finder-constructor*)
(defvar *finder-constructor* #'file
"Function that takes a path and returns a `file'-like object.")
(export-always 'finder*)
(defun finder* (&key
(root (current-directory))
predicates
recur-predicates)
"List FILES (including directories) that satisfy all PREDICATES.
Without PREDICATES, list all files.
Recur in subdirectories when they satisfy all RECUR-PREDICATES.
Without RECUR-PREDICATES, recur in all subdirectories."
(let ((result '()))
(uiop:collect-sub*directories
(uiop:ensure-directory-pathname (path root))
(constantly t)
(lambda (dir)
(every (alex:rcurry #'funcall (file dir)) recur-predicates))
(lambda (subdirectory)
(setf result (nconc result
(let ((subfiles (mapcar *finder-constructor*
(append (uiop:subdirectories subdirectory)
(uiop:directory-files subdirectory)))))
(if predicates
(delete-if (lambda (file)
(notevery (alex:rcurry #'funcall file) predicates))
subfiles)
subfiles))))))
result))
(defun match-path (path-element &rest more-path-elements)
"Return a predicate that matches when one of the path elements is contained in
the file path.
Useful for `finder'."
(lambda (file)
(some (lambda (elem)
(str:contains? elem (path file)))
(cons path-element more-path-elements))))
(defun match-path-end (path-suffix &rest more-path-suffixes)
"Return a predicate that matches when one of the path suffixes matches
the file path.
Useful for `finder'."
(lambda (file)
(some (lambda (suffix)
(str:ends-with? (namestring suffix) (path file)))
(cons path-suffix more-path-suffixes))))
(defun match-depth< (level &optional (root (current-directory)))
"Return a predicate that matches when the argument file is in a subdirectory
of ROOT less deep than LEVEL."
(lambda (file)
(< (depth file root) level)))
(export-always 'finder)
(defun finder (&rest predicate-specifiers) ; TODO: Add convenient regexp support? Case-folding? Maybe str:*ignore-case* is enough.
"List files in current directory that satisfy all PREDICATE-SPECIFIERS
Directories are ignored.
Without PREDICATE-SPECIFIERS, list all files.
A predicate specifier can be:
- a string, in which case it is turned into (match-path STRING);
- a pathname, in which case it is turned into (match-path-end PATHNAME);
- a list of predicates, in which case it is turned into (apply #'alexandria:disjoin PREDICATES);
- a function (a predicate).
For a more tunable finder, see `finder*'."
(labels ((specifier->predicate (specifier)
(match specifier
((and s (type string))
(match-path s))
((and s (type pathname))
(match-path-end s))
((cons pred1 more-preds)
(apply #'alex:disjoin
(mapcar #'specifier->predicate
(cons pred1 more-preds))))
((and pred (type function))
pred)
(other
(error "Unknown predicate specifier: ~a" other)))))
(finder* :root (current-directory)
:predicates (cons (complement #'directory?)
(mapcar #'specifier->predicate
predicate-specifiers)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; `ls -l' proof-of-concept replacement.
(defun permissions->unix (permissions)
(format nil "~a~a~a~a~a~a~a~a~a"
(if (find :user-read permissions) "r" "-")
(if (find :user-write permissions) "w" "-")
(if (find :user-exec permissions) "x" "-")
(if (find :group-read permissions) "r" "-")
(if (find :group-write permissions) "w" "-")
(if (find :group-exec permissions) "x" "-")
(if (find :other-read permissions) "r" "-")
(if (find :other-write permissions) "w" "-")
(if (find :other-exec permissions) "x" "-")))
(defun max-width (files reader &key (key #'write-to-string))
(apply #'max (mapcar #'length
(mapcar (lambda (file)
(funcall key (funcall reader file)))
files))))
(defun ls-l (&key human-readable?)
"Mimicks Unix' `ls -l'."
;; TODO: Add support for file arguments?
(let* ((current-dir-entries (finder* :recur-predicates (list (constantly nil))))
(size-column-width (max-width current-dir-entries #'size)))
(dolist (file current-dir-entries)
(format t (str:concat "~a~a ~a ~a ~a ~" (write-to-string size-column-width) "@a ~a ~a~%")
(if (directory? file) "d" "-")
(permissions->unix (permissions file))
(link-count file)
(user file)
(group file)
(if human-readable?
(serapeum:format-file-size-human-readable nil (size file))
(size file))
(local-time:format-timestring nil (modification-date file)
:format +ls-time-format+)
(relative-path file)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defparameter %magic-cookie-mime nil
"Internal storage for `magic-cookie-mime'.")
(defun magic-cookie-mime ()
"Return internal, persistent MIME cookie for `magicffi' calls.
Benchmark on thousands of files shows that
keeping the same cookie saves about 15% of time. "
(when (or (not %magic-cookie-mime)
(not (magicffi:open-magic-p %magic-cookie-mime)))
(setf %magic-cookie-mime (magicffi:magic-open '(:symlink :mime)))
(magicffi:magic-load %magic-cookie-mime))
%magic-cookie-mime)
(defparameter %magic-cookie-description nil
"Internal storage for `magic-cookie-description'.")
(defun magic-cookie-description ()
"Same as `magic-cooke-mime' but for `file' descriptions.
See `%description'."
(when (or (not %magic-cookie-description)
(not (magicffi:open-magic-p %magic-cookie-description)))
(setf %magic-cookie-description (magicffi:magic-open '(:symlink)))
(magicffi:magic-load %magic-cookie-description))
%magic-cookie-description)
(defun %mime-type+encoding (path)
"Return a pair of MIME type and MIME encoding for PATH."
(str:split "; "
(magicffi:magic-file (magic-cookie-mime) path)))
(defun %description (path)
"Return the PATH description as per the `file' UNIX command."
(magicffi:magic-file (magic-cookie-description) path))
;; TODO: Include the description or do it in another class? Could be slower. Benchmark.
(defclass* file+mime (file)
((mime-type ""
:reader t)
(mime-encoding ""
:reader t)
(description ""
:reader t))
(:accessor-name-transformer (hu.dwim.defclass-star:make-name-transformer name))
(:export-slot-names-p t)
(:export-class-name-p t))
(defmethod initialize-instance :after ((file file+mime) &key)
(let ((mime-type+encoding (%mime-type+encoding (path file))))
(setf (slot-value file 'mime-type) (first mime-type+encoding)
(slot-value file 'mime-encoding) (second mime-type+encoding)
(slot-value file 'description) (%description (path file)))))
(defun file+mime (path)
(make-instance 'file+mime :path path))
(defun finder*+mime (root &rest predicates)
(let ((*finder-constructor* #'file+mime))
(finder* :root root
:predicates predicates)))
(defun finder+mime (&rest predicates)
(let ((*finder-constructor* #'file+mime))
(apply #'finder predicates)))
| 23,619 | Common Lisp | .lisp | 530 | 35.767925 | 131 | 0.601538 | Ambrevar/fof | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | c9f28ef9ebde1c6f2f5d44b76f61412350f7b7084f726fc56f691364da88b6fe | 12,113 | [
-1
] |
12,114 | fof.asd | Ambrevar_fof/fof.asd | #-asdf3.1 (error "`fof' requires ASDF 3.1")
(defsystem "fof"
:version "0.1.0"
:author "Pierre Neidhardt <[email protected]>"
:homepage "https://gitlab.com/ambrevar/fof"
:licence "GPL3+"
:class :package-inferred-system
:depends-on ("fof/package"))
(defsystem "fof/mf"
:class :package-inferred-system
:depends-on ("fof/mediafile"))
| 348 | Common Lisp | .asd | 11 | 29 | 48 | 0.704478 | Ambrevar/fof | 8 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 7e48015ef05734ab59a37543fa0525f2dd1d6c94cc784dd0b02a0702aa85db23 | 12,114 | [
-1
] |
12,135 | simple-neural-network.lisp | glv2_simple-neural-network/simple-neural-network.lisp | ;;; This library implements a simple neural network.
;;; Copyright 2019-2022 Guillaume Le Vaillant
;;; This library is free software released under the GNU GPL-3 license.
(defpackage :simple-neural-network
(:nicknames :snn)
(:use :cl)
(:export #:accuracy
#:copy
#:create-neural-network
#:find-learning-rate
#:find-normalization
#:index-of-max-value
#:mean-absolute-error
#:neural-network-biases
#:neural-network-layers
#:neural-network-weights
#:predict
#:restore
#:same-category-p
#:store
#:train))
(in-package :simple-neural-network)
(deftype double-float-array ()
'(simple-array double-float (*)))
(defstruct neural-network
layers
weights
biases
deltas
weight-gradients
weight-momentums
bias-gradients
bias-momentums)
(defun make-double-float-array (size)
"Make a new array of SIZE double floats."
(make-array size :element-type 'double-float :initial-element 0.0d0))
(defmacro %dotimes ((var count &optional result) &body body)
`(if lparallel:*kernel*
(lparallel:pdotimes (,var ,count ,result)
,@body)
(dotimes (,var ,count ,result)
,@body)))
(defmacro %mapc (function list &rest more-lists)
`(if lparallel:*kernel*
(lparallel:pmapc ,function ,list ,@more-lists)
(mapc ,function ,list ,@more-lists)))
(declaim (inline activation))
(defun activation (x)
"Activation function for the neurons."
(declare (type double-float x))
(* 1.7159d0 (tanh (* 0.66667d0 x))))
(declaim (inline activation-prime))
(defun activation-prime (y)
"Derivative of the activation function."
(declare (type double-float y))
;; Here Y is the result of (ACTIVATION X).
(- 1.1439d0 (* 0.38852d0 y y)))
(defun make-random-weights (input-size output-size)
"Generate a matrix (OUTPUT-SIZE * INPUT-SIZE) of random weights."
(let ((weights (make-double-float-array (* output-size input-size)))
(r (sqrt (/ 6.0d0 (+ input-size output-size)))))
(dotimes (i (* output-size input-size) weights)
(setf (aref weights i) (- (random (* 2.0d0 r)) r)))))
(defun create-neural-network (input-size output-size &rest hidden-layers-sizes)
"Create a neural network having INPUT-SIZE inputs, OUTPUT-SIZE outputs, and
optionally some intermediary layers whose sizes are specified by
HIDDEN-LAYERS-SIZES. The neural network is initialized with random weights and
biases."
(let* ((*random-state* (make-random-state t))
(layer-sizes (append (list input-size)
hidden-layers-sizes
(list output-size)))
(layers (mapcar #'make-double-float-array layer-sizes))
(weights (butlast (maplist (lambda (sizes)
(let ((input-size (first sizes))
(output-size (second sizes)))
(when output-size
(make-random-weights input-size
output-size))))
layer-sizes)))
(biases (mapcar #'make-double-float-array (rest layer-sizes)))
(deltas (mapcar #'make-double-float-array (rest layer-sizes)))
(weight-gradients (mapcar (lambda (weights)
(make-double-float-array (length weights)))
weights))
(weight-momentums (mapcar (lambda (weights)
(make-double-float-array (length weights)))
weights))
(bias-gradients (mapcar (lambda (biases)
(make-double-float-array (length biases)))
biases))
(bias-momentums (mapcar (lambda (biases)
(make-double-float-array (length biases)))
biases)))
(make-neural-network :layers layers
:weights weights
:biases biases
:deltas deltas
:weight-gradients weight-gradients
:weight-momentums weight-momentums
:bias-gradients bias-gradients
:bias-momentums bias-momentums)))
(defun set-input (neural-network input)
"Set the input layer of the NEURAL-NETWORK to INPUT."
(declare (type vector input))
(let ((input-layer (first (neural-network-layers neural-network))))
(declare (type double-float-array input-layer))
(replace input-layer input)
(values)))
(defun get-output (neural-network)
"Return the output layer of the NEURAL-NETWORK."
(first (last (neural-network-layers neural-network))))
(declaim (inline compute-value))
(defun compute-value (input output weights biases index)
"Compute the values of the neuron at INDEX in the OUTPUT layer."
(declare (type double-float-array input output weights biases)
(type fixnum index)
(optimize (speed 3) (safety 0)))
(let* ((input-size (length input))
(aggregation (aref biases index)))
(declare (type fixnum input-size)
(type double-float aggregation))
(do ((j 0 (1+ j))
(k (the fixnum (* index input-size)) (1+ k)))
((>= j input-size))
(declare (type fixnum j k))
(incf aggregation (* (aref input j) (aref weights k))))
(setf (aref output index) (activation aggregation))
(values)))
(defun compute-values (input output weights biases)
"Compute the values of the neurons in the OUTPUT layer."
(declare (type double-float-array input output weights biases)
(optimize (speed 3) (safety 0)))
(let ((output-size (length output)))
(declare (type fixnum output-size))
(%dotimes (i output-size)
(declare (type fixnum i))
(compute-value input output weights biases i))))
(defun propagate (neural-network)
"Propagate the values of the input layer of the NEURAL-NETWORK to the output
layer."
(do ((layers (neural-network-layers neural-network)
(rest layers))
(weights (neural-network-weights neural-network)
(rest weights))
(biases (neural-network-biases neural-network)
(rest biases)))
((endp weights))
(compute-values (first layers)
(second layers)
(first weights)
(first biases)))
(values))
(defun compute-output-delta (neural-network target)
"Compute the error between the output layer of the NEURAL-NETWORK and the
TARGET."
(declare (type vector target))
(let ((output (get-output neural-network))
(delta (first (last (neural-network-deltas neural-network)))))
(declare (type double-float-array output delta))
(dotimes (i (length output))
(let* ((value (aref output i))
(diff (- value (aref target i))))
(declare (type double-float value diff))
(setf (aref delta i) (* (activation-prime value) diff))))))
(declaim (inline compute-single-delta))
(defun compute-single-delta (previous-delta output weights delta index)
"Compute the delta for the neuron at INDEX in the OUTPUT layer."
(declare (type double-float-array previous-delta output weights delta)
(type fixnum index)
(optimize (speed 3) (safety 0)))
(let ((previous-delta-size (length previous-delta))
(delta-size (length delta))
(value 0.0d0))
(declare (type fixnum previous-delta-size delta-size)
(type double-float value))
(dotimes (j previous-delta-size)
(declare (type fixnum j))
(let ((offset (+ (the fixnum (* j delta-size)) index)))
(declare (type fixnum offset))
(incf value (* (aref previous-delta j) (aref weights offset)))))
(setf (aref delta index) (* (activation-prime (aref output index)) value))
(values)))
(defun compute-delta (previous-delta output weights delta)
"Compute the error of the OUTPUT layer based on the error of the next layer."
(declare (type double-float-array previous-delta output weights delta)
(optimize (speed 3) (safety 0)))
(%dotimes (i (length delta) delta)
(declare (type fixnum i))
(compute-single-delta previous-delta output weights delta i)))
(declaim (inline add-weight-gradient))
(defun add-weight-gradient (input gradients delta index)
"Add the gradients computed for an input for the weights of the neuron at
INDEX in a layer to the sum of the gradients for previous inputs."
(declare (type double-float-array input gradients delta)
(type fixnum index)
(optimize (speed 3) (safety 0)))
(let ((input-size (length input))
(gradient (aref delta index)))
(declare (type fixnum input-size)
(type double-float gradient))
(do ((j (the fixnum (* index input-size)) (1+ j))
(k 0 (1+ k)))
((>= k input-size))
(declare (type fixnum j k))
(incf (aref gradients j) (* (aref input k) gradient)))))
(defun add-gradients (input weight-gradients bias-gradients delta)
"Add the gradients computed for an input to sum of the gradients for previous
inputs."
(declare (type double-float-array input weight-gradients bias-gradients delta)
(optimize (speed 3) (safety 0)))
(%dotimes (i (length delta))
(declare (type fixnum i))
(add-weight-gradient input weight-gradients delta i)
(incf (aref bias-gradients i) (aref delta i))))
(declaim (inline average-gradient))
(defun average-gradient (gradient batch-size)
"Compute the average gradients for a layer."
(declare (type double-float-array gradient)
(type double-float batch-size)
(optimize (speed 3) (safety 0)))
(dotimes (i (length gradient))
(declare (type fixnum i))
(setf (aref gradient i) (/ (aref gradient i) batch-size))))
(defun average-gradients (neural-network batch-size)
"Compute the average gradients for the whole NEURAL-NETWORK."
(let ((batch-size (coerce batch-size 'double-float)))
(%mapc (lambda (weight-gradient bias-gradient)
(average-gradient weight-gradient batch-size)
(average-gradient bias-gradient batch-size))
(neural-network-weight-gradients neural-network)
(neural-network-bias-gradients neural-network))
(values)))
(defun backpropagate (neural-network)
"Propagate the error of the output layer of the NEURAL-NETWORK back to the
first layer and compute the gradients."
(do ((layers (rest (reverse (neural-network-layers neural-network)))
(rest layers))
(weights (reverse (neural-network-weights neural-network))
(rest weights))
(weight-gradients (reverse (neural-network-weight-gradients neural-network))
(rest weight-gradients))
(bias-gradients (reverse (neural-network-bias-gradients neural-network))
(rest bias-gradients))
(deltas (reverse (neural-network-deltas neural-network))
(rest deltas)))
((endp deltas))
(unless (endp (rest deltas))
(compute-delta (first deltas)
(first layers)
(first weights)
(second deltas)))
(add-gradients (first layers)
(first weight-gradients)
(first bias-gradients)
(first deltas)))
(values))
(declaim (inline clear-momentum))
(defun clear-momentum (momentum)
"Reset momentum to 0."
(declare (type double-float-array momentum)
(optimize (speed 3) (safety 0)))
(dotimes (i (length momentum))
(declare (type fixnum i))
(setf (aref momentum i) 0.0d0)))
(defun clear-momentums (neural-network)
"Reset all the momentums to 0."
(%mapc (lambda (weight-momentum bias-momentum)
(clear-momentum weight-momentum)
(clear-momentum bias-momentum))
(neural-network-weight-momentums neural-network)
(neural-network-bias-momentums neural-network))
(values))
(defun update-weights (weights gradients momentums gradient-coefficient
momentum-coefficient)
"Update the WEIGHTS and MOMENTUMS of a layer and clear the GRADIENTS."
(declare (type double-float-array weights gradients momentums)
(type double-float gradient-coefficient momentum-coefficient)
(optimize (speed 3) (safety 0)))
(dotimes (i (length weights))
(declare (type fixnum i))
(let ((momentum (+ (* gradient-coefficient (aref gradients i))
(* momentum-coefficient (aref momentums i)))))
(declare (type double-float momentum))
(decf (aref weights i) momentum)
(setf (aref momentums i) momentum)
(setf (aref gradients i) 0.0d0))))
(defun update-weights-and-biases (neural-network learning-rate
momentum-coefficient)
"Update all the weights and biases of the NEURAL-NETWORK."
(let ((gradient-coefficient (* learning-rate (- 1.0d0 momentum-coefficient))))
(%mapc (lambda (weights biases weight-gradients weight-momentums
bias-gradients bias-momentums)
(update-weights weights weight-gradients weight-momentums
gradient-coefficient momentum-coefficient)
(update-weights biases bias-gradients bias-momentums
gradient-coefficient momentum-coefficient))
(neural-network-weights neural-network)
(neural-network-biases neural-network)
(neural-network-weight-gradients neural-network)
(neural-network-weight-momentums neural-network)
(neural-network-bias-gradients neural-network)
(neural-network-bias-momentums neural-network))
(values)))
(defun train (neural-network inputs targets learning-rate
&key (batch-size 1) (momentum-coefficient 0.9))
"Train the NEURAL-NETWORK with the given LEARNING-RATE and
MOMENTUM-COEFFICIENT using some INPUTS and TARGETS. The weights are updated
every BATCH-SIZE inputs."
(let ((learning-rate (coerce learning-rate 'double-float))
(momentum-coefficient (coerce momentum-coefficient 'double-float)))
(clear-momentums neural-network)
(do ((inputs inputs (rest inputs))
(targets targets (rest targets))
(n 0 (1+ n)))
(nil)
(declare (type fixnum n))
(when (or (endp inputs) (= n batch-size))
(when (>= n 2)
(average-gradients neural-network n))
(update-weights-and-biases neural-network
learning-rate
momentum-coefficient)
(setf n 0)
(when (endp inputs)
(return)))
(set-input neural-network (first inputs))
(propagate neural-network)
(compute-output-delta neural-network (first targets))
(backpropagate neural-network))
(values)))
(defun predict (neural-network input &optional output)
"Return the output computed by the NEURAL-NETWORK for a given INPUT. If
OUTPUT is not NIL, the output is written in it, otherwise a new vector is
allocated."
(set-input neural-network input)
(propagate neural-network)
(if output
(replace output (get-output neural-network))
(copy-seq (get-output neural-network))))
(defun store (neural-network place)
"Store the NEURAL-NETWORK to PLACE, which must be a stream or
a pathname-designator."
(let ((layer-sizes (mapcar #'length (neural-network-layers neural-network))))
(cl-store:store (list layer-sizes
(neural-network-weights neural-network)
(neural-network-biases neural-network))
place)
(values)))
(defun restore (place)
"Restore the neural network stored in PLACE, which must be a stream or
a pathname-designator."
(destructuring-bind (layer-sizes weights biases) (cl-store:restore place)
(let ((layers (mapcar #'make-double-float-array layer-sizes))
(deltas (mapcar #'make-double-float-array (rest layer-sizes)))
(weight-gradients (mapcar (lambda (weights)
(make-double-float-array (length weights)))
weights))
(weight-momentums (mapcar (lambda (weights)
(make-double-float-array (length weights)))
weights))
(bias-gradients (mapcar (lambda (biases)
(make-double-float-array (length biases)))
biases))
(bias-momentums (mapcar (lambda (biases)
(make-double-float-array (length biases)))
biases)))
(make-neural-network :layers layers
:weights weights
:biases biases
:deltas deltas
:weight-gradients weight-gradients
:weight-momentums weight-momentums
:bias-gradients bias-gradients
:bias-momentums bias-momentums))))
(defun copy (neural-network)
"Return a copy of the NEURAL-NETWORK."
(let ((layers (neural-network-layers neural-network))
(weights (neural-network-weights neural-network))
(biases (neural-network-biases neural-network))
(deltas (neural-network-deltas neural-network))
(weight-gradients (neural-network-weight-gradients neural-network))
(weight-momentums (neural-network-weight-momentums neural-network))
(bias-gradients (neural-network-bias-gradients neural-network))
(bias-momentums (neural-network-bias-momentums neural-network)))
(make-neural-network :layers (mapcar #'copy-seq layers)
:weights (mapcar #'copy-seq weights)
:biases (mapcar #'copy-seq biases)
:deltas (mapcar #'copy-seq deltas)
:weight-gradients (mapcar #'copy-seq weight-gradients)
:weight-momentums (mapcar #'copy-seq weight-momentums)
:bias-gradients (mapcar #'copy-seq bias-gradients)
:bias-momentums (mapcar #'copy-seq bias-momentums))))
(defun index-of-max-value (values)
"Return the index of the greatest value in VALUES."
(do ((size (length values))
(index 0)
(maximum (aref values 0))
(i 1 (1+ i)))
((>= i size) index)
(when (> (aref values i) maximum)
(setf index i)
(setf maximum (aref values i)))))
(defun same-category-p (output target)
"Return T if calls to INDEX-OF-MAX-VALUE on OUTPUT and TARGET return the same
value, and NIL otherwise."
(= (index-of-max-value output)
(index-of-max-value target)))
(defun accuracy (neural-network inputs targets &key (test #'same-category-p))
"Return the rate of good guesses computed by the NEURAL-NETWORK when testing
it with some INPUTS and TARGETS. TEST must be a function taking an output and
a target returning T if the output is considered to be close enough to the
target, and NIL otherwise. SAME-CATEGORY-P is used by default."
(let ((output (copy-seq (get-output neural-network))))
(do ((inputs inputs (rest inputs))
(targets targets (rest targets))
(good-guesses 0)
(n 0 (1+ n)))
((endp inputs) (/ good-guesses n))
(predict neural-network (first inputs) output)
(when (funcall test output (first targets))
(incf good-guesses)))))
(defun mean-absolute-error (neural-network inputs targets)
"Return the mean absolute error on the outputs computed by the NEURAL-NETWORK
when testing it with some INPUTS and TARGETS."
(let* ((output (copy-seq (get-output neural-network)))
(output-size (length output))
(output-error (copy-seq output)))
(do ((inputs inputs (rest inputs))
(targets targets (rest targets))
(total-error 0)
(n 0 (1+ n)))
((endp inputs) (/ total-error (* n output-size)))
(predict neural-network (first inputs) output)
(map-into output-error #'- output (first targets))
(incf total-error (reduce #'+ output-error :key #'abs)))))
(defun means (inputs)
"Return the means of the variables of the INPUTS."
(let* ((n (length inputs))
(input-size (length (first inputs)))
(results (make-double-float-array input-size)))
(assert (plusp n))
(dolist (input inputs)
(dotimes (i input-size)
(incf (aref results i) (aref input i))))
(dotimes (i input-size results)
(setf (aref results i) (/ (aref results i) n)))))
(defun standard-deviations (inputs means)
"Return the standard deviations of the variables of the INPUTS."
(let* ((n (length inputs))
(input-size (length means))
(results (make-double-float-array input-size)))
(assert (>= n 2))
(dolist (input inputs)
(dotimes (i input-size)
(let ((x (- (aref input i) (aref means i))))
(incf (aref results i) (* x x)))))
(dotimes (i input-size results)
(setf (aref results i) (sqrt (/ (aref results i) (1- n)))))))
(defun normalize (input means standard-deviations)
"Return a normalized variant of the INPUT."
(map 'double-float-array
(lambda (x m a)
(if (zerop a) (- x m) (/ (- x m) a)))
input
means
standard-deviations))
(defun denormalize (input means standard-deviations)
"Return the original input computed from its normalized variant."
(map 'double-float-array
(lambda (x m a)
(if (zerop a) (+ x m) (+ (* x a) m)))
input
means
standard-deviations))
(defun find-normalization (inputs)
"Return four values. The first is a normalization function taking an input
and returning a normalized input. Applying this normalization function to the
inputs gives a data set in which each variable has mean 0 and standard
deviation 1. The second is a denormalization function that can compute the
original input from the normalized one. The third is the code of the
normalization function. The fourth is the code of the denormalization
function."
(let* ((means (means inputs))
(standard-deviations (standard-deviations inputs means))
(normalize-form `(lambda (input)
(normalize input ,means ,standard-deviations)))
(normalize (compile nil normalize-form))
(denormalize-form `(lambda (input)
(denormalize input ,means ,standard-deviations)))
(denormalize (compile nil denormalize-form)))
(values normalize denormalize normalize-form denormalize-form)))
(defun find-learning-rate (neural-network inputs targets
&key (batch-size 1) (momentum-coefficient 0.9)
(epochs 1) (iterations 10) (minimum 0) (maximum 1))
"Return the best learing rate found in ITERATIONS steps of dichotomic search
(between MINIMUM and MAXIMUM). In each step, the NEURAL-NETWORK is trained
EPOCHS times using some INPUTS, TARGETS, BATCH-SIZE and MOMENTUM-COEFFICIENT."
(labels ((cost (learning-rate)
(let ((nn (copy neural-network)))
(dotimes (i epochs)
(train nn inputs targets learning-rate
:batch-size batch-size
:momentum-coefficient momentum-coefficient))
(mean-absolute-error nn inputs targets)))
(middle (x y)
(/ (+ x y) 2.0d0))
(stp (i low a m b high cost-a cost-b best)
(cond
((zerop i)
best)
((> cost-a cost-b)
(let ((d (middle b high)))
(stp (1- i) m b (middle m high) d high cost-b (cost d) b)))
(t
(let ((d (middle low a)))
(stp (1- i) low d (middle low m) a m (cost d) cost-a a))))))
(let ((a (/ (+ minimum minimum maximum) 3))
(m (middle minimum maximum))
(b (/ (+ minimum maximum maximum) 3)))
(stp iterations minimum a m b maximum (cost a) (cost b) nil))))
| 24,426 | Common Lisp | .lisp | 521 | 37.21881 | 83 | 0.622648 | glv2/simple-neural-network | 8 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 57c395f4d772363a9b3c17e398cfb3de208ea465a2e6ab5b62cbbb85fbd70779 | 12,135 | [
-1
] |
12,136 | tests.lisp | glv2_simple-neural-network/tests/tests.lisp | ;;; This library implements a simple neural network.
;;; Copyright 2019-2022 Guillaume Le Vaillant
;;; This library is free software released under the GNU GPL-3 license.
(defpackage :simple-neural-network/test
(:use :cl :fiveam :simple-neural-network)
(:import-from :simple-neural-network
#:neural-network-layers
#:neural-network-weights
#:neural-network-biases
#:neural-network-deltas))
(in-package :simple-neural-network/test)
(def-suite snn-tests
:description "Unit tests for simple neural network.")
(in-suite snn-tests)
(test xor
(labels ((normalize (x)
(if (= x 1.0d0) 1.0d0 -1.0d0))
(denormalize (x)
(if (> x 0.0d0) 1.0d0 0.0d0))
(same-value-p (output target)
(= (denormalize (aref output 0))
(denormalize (aref target 0)))))
(let ((inputs (mapcar (lambda (v)
(map 'vector #'normalize v))
'(#(0.0d0 0.0d0)
#(0.0d0 1.0d0)
#(1.0d0 0.0d0)
#(1.0d0 1.0d0))))
(targets (mapcar (lambda (v)
(map 'vector #'normalize v))
'(#(0.0d0)
#(1.0d0)
#(1.0d0)
#(0.0d0))))
(nn (create-neural-network 2 1 4)))
(dotimes (i 1000)
(train nn inputs targets 0.1))
(is (= 1 (accuracy nn inputs targets :test #'same-value-p))))))
(test cos
(flet ((get-samples (n)
(loop repeat n
for x = (float (- (random (* 2 pi)) pi) 1.0d0)
collect (vector x) into inputs
collect (vector (cos x)) into targets
finally (return (list inputs targets)))))
(destructuring-bind (inputs targets) (get-samples 100000)
(multiple-value-bind (normalize-input denormalize-input)
(find-normalization inputs)
(declare (ignore denormalize-input))
(multiple-value-bind (normalize-target denormalize-target)
(find-normalization targets)
(let* ((inputs (mapcar normalize-input inputs))
(targets (mapcar normalize-target targets))
(nn (create-neural-network 1 1 8 8 8))
(learning-rate (find-learning-rate nn inputs targets
:iterations 20
:epochs 10
:maximum 0.3))
(close-enough-p (lambda (output target)
(let ((x (aref (funcall denormalize-target output) 0))
(y (aref (funcall denormalize-target target) 0)))
(<= (abs (/ (- x y) y)) 0.01)))))
(dotimes (i 100)
(let ((batch-size (max 1 (floor i 10))))
(train nn inputs targets learning-rate :batch-size batch-size)))
(destructuring-bind (inputs targets) (get-samples 100)
(let ((inputs (mapcar normalize-input inputs))
(targets (mapcar normalize-target targets)))
(is (<= 90/100 (accuracy nn inputs targets
:test close-enough-p)))))))))))
(defun mnist-file-path (filename)
(asdf:system-relative-pathname "simple-neural-network"
(concatenate 'string "tests/" filename)))
(defun mnist-read-and-normalize-image (data offset)
(let ((image (make-array (* 28 28)
:element-type 'double-float
:initial-element 0.0d0)))
(dotimes (i (* 28 28) image)
(setf (aref image i) (/ (- (aref data (+ offset i)) 128) 128.0d0)))))
(defun mnist-read-and-normalize-label (data offset)
(let ((target (make-array 10
:element-type 'double-float
:initial-element -1.0d0))
(category (aref data offset)))
(setf (aref target category) 1.0d0)
target))
(defun mnist-load (type)
(destructuring-bind (n-images images-path labels-path)
(if (eql type :train)
(list 60000
(mnist-file-path "train-images-idx3-ubyte.gz")
(mnist-file-path "train-labels-idx1-ubyte.gz"))
(list 10000
(mnist-file-path "t10k-images-idx3-ubyte.gz")
(mnist-file-path "t10k-labels-idx1-ubyte.gz")))
(let ((images (with-open-file (f images-path
:element-type '(unsigned-byte 8))
(let ((images-data (chipz:decompress nil 'chipz:gzip f)))
(loop for i from 0 below n-images
for offset = (+ 16 (* i 28 28))
collect (mnist-read-and-normalize-image images-data
offset)))))
(labels (with-open-file (f labels-path
:element-type '(unsigned-byte 8))
(let ((labels-data (chipz:decompress nil 'chipz:gzip f)))
(loop for i from 0 below n-images
collect (mnist-read-and-normalize-label labels-data
(+ 8 i)))))))
(values images labels))))
(test mnist
(let ((nn (create-neural-network (* 28 28) 10 128)))
(multiple-value-bind (inputs targets) (mnist-load :train)
(train nn inputs targets 0.006d0))
(multiple-value-bind (inputs targets) (mnist-load :test)
(is (<= 85/100 (accuracy nn inputs targets))))))
(test store/restore
(let ((nn1 (create-neural-network 3 2 4))
(input #(0.2d0 0.5d0 0.1d0))
(target #(0.1d0 0.2d0 0.3d0 0.4d0)))
(train nn1 (list input) (list target) 0.6d0)
(uiop:with-temporary-file (:pathname path)
(store nn1 path)
(let ((nn2 (restore path)))
(is (equalp (neural-network-weights nn1)
(neural-network-weights nn2)))
(is (equalp (neural-network-biases nn1)
(neural-network-biases nn2)))
(is (equalp (predict nn1 #(0.6d0 0.5d0 0.4d0))
(predict nn2 #(0.6d0 0.5d0 0.4d0))))))))
(test copy
(let ((nn1 (create-neural-network 3 2 4))
(input #(0.2d0 0.5d0 0.1d0))
(target #(0.1d0 0.2d0 0.3d0 0.4d0)))
(train nn1 (list input) (list target) 0.1d0)
(let ((nn2 (copy nn1)))
(is (equalp (neural-network-weights nn1)
(neural-network-weights nn2)))
(is (equalp (neural-network-biases nn1)
(neural-network-biases nn2)))
(train nn1 (list input) (list target) 0.1d0)
(is-false (equalp (neural-network-weights nn1)
(neural-network-weights nn2)))
(is-false (equalp (neural-network-biases nn1)
(neural-network-biases nn2)))
(train nn2 (list input) (list target) 0.1d0)
(is (equalp (neural-network-weights nn1)
(neural-network-weights nn2)))
(is (equalp (neural-network-biases nn1)
(neural-network-biases nn2))))))
(test normalization/denormalization
(let ((inputs '(#(1.0d0 1.0d0 1.0d0)
#(2.0d0 1.0d1 -1.0d0)
#(3.0d0 1.0d2 2.0d0)
#(4.0d0 1.0d3 -2.0d0)
#(5.0d0 1.0d4 3.0d0))))
(multiple-value-bind (normalize denormalize) (find-normalization inputs)
(let* ((normalized-inputs (mapcar normalize inputs))
(denormalized-inputs (mapcar denormalize normalized-inputs)))
(mapc (lambda (x y) (is (equalp x y)))
inputs
denormalized-inputs)))))
| 7,897 | Common Lisp | .lisp | 161 | 34.093168 | 90 | 0.516321 | glv2/simple-neural-network | 8 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 302f54db88d015eccff148c706f9799328364fcf61c4fce9b1ea7cf768420d2e | 12,136 | [
-1
] |
12,137 | simple-neural-network.asd | glv2_simple-neural-network/simple-neural-network.asd | ;;; This library implements a simple neural network.
;;; Copyright 2019-2020 Guillaume Le Vaillant
;;; This library is free software released under the GNU GPL-3 license.
(defsystem "simple-neural-network"
:name "simple-neural-network"
:description "Simple neural network"
:version "3.1"
:author "Guillaume Le Vaillant"
:license "GPL-3"
:depends-on ("cl-store" "lparallel")
:in-order-to ((test-op (test-op "simple-neural-network/test")))
:components ((:file "simple-neural-network")))
(defsystem "simple-neural-network/test"
:depends-on ("chipz" "fiveam" "simple-neural-network" "uiop")
:version "3.1"
:in-order-to ((test-op (load-op "simple-neural-network/test")))
:perform (test-op (o s)
(let ((tests (uiop:find-symbol* 'snn-tests
:simple-neural-network/test)))
(uiop:symbol-call :fiveam 'run! tests)))
:components ((:module "tests"
:components ((:file "tests")))))
| 985 | Common Lisp | .asd | 22 | 38.454545 | 75 | 0.649324 | glv2/simple-neural-network | 8 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | cc92ab8c92bcd0151525cad716004a57a634c7fb57244143b6e140a6d34a0b43 | 12,137 | [
-1
] |
12,156 | dist-load-flickr.lisp | schani_clickr/dist-load-flickr.lisp | (use-package '(:automatr :flickr :clickr))
(defvar *api-key* "YOUR API KEY")
(defvar *shared-secret* "YOUR SHARED SECRET")
(defvar *my-user-name* "YOUR USER NAME")
(defvar *my-user* nil)
(defun login-and-make-actions ()
(let ((api-info (request-authorization *api-key* *shared-secret*)))
(sleep 10)
(complete-authorization api-info)
(let* ((*me* (user-with-name api-info *my-user-name*))
(actions (audit-actions (all-applicable-actions *me*))))
(htmlize-actions actions)
(setf *my-user* *me*)
actions)))
| 543 | Common Lisp | .lisp | 14 | 35 | 69 | 0.6673 | schani/clickr | 8 | 1 | 1 | GPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 5768ee000566285e4c523929141b1c4d37b728f557ecfd445945a6600c71e844 | 12,156 | [
-1
] |
12,157 | utils.lisp | schani_clickr/utils.lisp | ;; utils.lisp
;; clickr
;; Copyright (C) 2002-2005 Mark Probst
;; 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 2, 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, you can either send email to this
;; program's maintainer or write to: The Free Software Foundation,
;; Inc.; 675 Massachusetts Avenue; Cambridge, MA 02139, USA.
(defpackage :utils
(:use :cl)
(:export
#:map-times #:integers-upto #:mappend #:dcs #:ucs #:make-tmp-name #:partition #:slet* #:random-select))
(in-package :utils)
(defun map-times (n f)
(labels ((perform-map (i)
(if (>= i n)
'()
(cons (funcall f i) (perform-map (1+ i))))))
(perform-map 0)))
(defun integers-upto (n)
(map-times n #'(lambda (i) i)))
(defun mappend (func &rest lists)
(reduce #'append (apply #'mapcar func lists)))
;; down-case-symbol
(defun dcs (x)
(substitute #\d #\. (substitute #\p #\+ (substitute #\_ #\- (string-downcase (symbol-name x))))))
;; up-case-symbol
(defun ucs (x)
(substitute #\d #\. (substitute #\p #\+ (substitute #\_ #\- (string-upcase (symbol-name x))))))
(defvar *tmp-num* 0)
(defun make-tmp-name ()
(let ((name (format nil "tmp_~A" *tmp-num*)))
(incf *tmp-num*)
name))
(defun partition (pred list)
(let ((in nil)
(out nil))
(dolist (item list)
(if (funcall pred item)
(push item in)
(push item out)))
(values (reverse in) (reverse out))))
(defmacro slet* (bindings &body body)
(labels ((destructure (lhs names body)
(if (null lhs)
body
(let ((rest (destructure (cdr lhs) (cdr names) body)))
(if (symbolp (car lhs))
rest
`(destructuring-bind ,(car lhs)
,(car names)
,rest)))))
(expand (bindings)
(if (null bindings)
(cons 'progn body)
(let* ((binding (car bindings))
(lhs (subseq binding 0 (1- (length binding))))
(rhs (car (last binding)))
(rest (expand (cdr bindings)))
(names (mapcar #'(lambda (n)
(if (symbolp n) n (gensym)))
lhs))
(destructured-rest (destructure lhs names rest)))
(case (length lhs)
(0 `(progn ,rhs ,destructured-rest))
(1 `(let ((,(car names) ,rhs))
,destructured-rest))
(t `(multiple-value-bind ,names
,rhs
,destructured-rest)))))))
(expand bindings)))
;; returns a random subset of the elements in list of length (min num
;; (length list))
(defun random-select (num list)
(let* ((length (length list))
(num (min num length)))
(labels ((indexes (num rest)
(if (zerop num)
rest
(let ((n (random length)))
(if (member n rest)
(indexes num rest)
(indexes (1- num) (cons n rest)))))))
(let ((indexes (indexes num nil)))
(mapcar #'(lambda (n) (nth n list)) indexes)))))
| 3,209 | Common Lisp | .lisp | 92 | 30.945652 | 106 | 0.641406 | schani/clickr | 8 | 1 | 1 | GPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 0fb6992f7f401e9900f9c91aacc0fe8f4004fdeea81fb5c6e058fb05274e5d89 | 12,157 | [
-1
] |
12,158 | load-flickr.lisp | schani_clickr/load-flickr.lisp | (use-package '(:automatr :flickr :clickr))
(defvar *api-key* "fe62be41f5e31734214d3efd4312dbb6")
(defvar *shared-secret* "357a7ea29d65120d")
(defvar *my-api-info* nil)
(defvar *my-user-name* "schani")
(defvar *my-user* nil)
(defun login ()
(let ((api-info (request-authorization *api-key* *shared-secret*)))
(sleep 10)
(complete-authorization api-info)
(setf *my-api-info* api-info)
(setf *my-user* (user-with-name api-info *my-user-name*))))
(defun login-and-make-actions ()
(login)
(let* ((actions (audit-actions (all-applicable-actions *me*))))
(htmlize-actions actions)
actions))
| 624 | Common Lisp | .lisp | 17 | 33.352941 | 69 | 0.689884 | schani/clickr | 8 | 1 | 1 | GPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | b8edb1f449452b6a791e14ed0184455b48420f69ee36056c4a80dd299ab7e239 | 12,158 | [
-1
] |
12,159 | automatr.lisp | schani_clickr/automatr.lisp | ;;; automatr.lisp --- Automation of Flickr tasks
;; Copyright (C) 2006 Mark Probst
;; Author: Mark Probst <[email protected]>
;; Maintainer: Mark Probst <[email protected]>
;; Version: 0.1
;; 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 2, 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, you can either send email to this
;; program's maintainer or write to: The Free Software Foundation,
;; Inc.; 675 Massachusetts Avenue; Cambridge, MA 02139, USA.
(defpackage "AUTOMATR"
(:use "CL" "FLICKR" "CLICKR" "UTILS" "LET-MATCH")
(:export #:htmlize-actions #:all-applicable-actions #:audit-actions #:apply-actions #:*me*))
(in-package :automatr)
(defparameter *me* nil)
(proclaim '(special *me*))
(defstruct action
name
action
condition)
(defparameter *actions* nil)
(defun add-action (name action condition)
(let ((actions (remove name *actions* :key #'action-name)))
(setf *actions* (cons (make-action :name name :action action :condition condition)
actions))))
(defun add-state-tag-actions (name tag-name condition)
(add-action (intern (format nil "ADD-~A" name))
`(add-tag ,tag-name)
condition)
(add-action (intern (format nil "REMOVE-~A" name))
`(remove-tag ,tag-name)
`(not ,condition)))
(defstruct entity
name
slots)
(defstruct entity-slot
name
accessor
type)
(defparameter *entities* nil)
(defmacro defentity (name slots)
`(push (make-entity :name ',name
:slots (list ,@(mapcar #'(lambda (slot)
(destructuring-bind (name accessor &optional (type :string))
slot
`(make-entity-slot :name ',name
:accessor ,accessor
:type ',type)))
slots)))
*entities*))
(defun entity-name-p (name)
(member name *entities* :key #'entity-name))
(defun entity-with-name (name)
(find name *entities* :key #'entity-name))
(defstruct automatr-group
name
id
max-posted
max-batch
condition)
(defparameter *automatr-groups* nil)
(defun defgroup (name id &key max-posted max-batch condition)
(push (make-automatr-group :name name
:id id
:max-posted max-posted
:max-batch max-batch
:condition condition)
*automatr-groups*))
(defun automatr-group-with-name (name)
(find name *automatr-groups* :key #'automatr-group-name))
(defun group-for-automatr-group (automatr-group)
(make-group (clickr-base-api-info *me*) (automatr-group-id automatr-group)))
(defun group-for-automatr-group-with-name (name)
(let ((automatr-group (automatr-group-with-name name)))
(group-for-automatr-group automatr-group)))
(defstruct op
name
type
arg-types
func)
(defparameter *ops* nil)
(defmacro defop (name type args &body body)
`(push (make-op :name ',name
:type ',type
:arg-types ',(mapcar #'cadr args)
:func #'(lambda (instance ,@(mapcar #'car args)) ,@body))
*ops*))
(defun op-with-name (name)
(find name *ops* :key #'op-name))
(defop count :integer ((list (:list ?)))
(length list))
(defop / :number ((a :number) (b :number))
(if (zerop b)
0
(/ a b)))
(defop >= :boolean ((a :number) (b :number))
(>= a b))
(defop not :boolean ((x :boolean))
(not x))
(defop and :boolean ((x :boolean) (y :boolean))
(and x y))
(defop or :boolean ((x :boolean) (y :boolean))
(or x y))
(defop eq :boolean ((x ?t) (y ?t))
(eq x y))
(defop in-set :boolean ((id :string))
(let ((set (make-photoset (clickr-base-api-info *me*) id)))
(member instance (photoset-photos set))))
(defun eval-expr (expr instance entity expected-type)
"Evaluates the expression for the given instance of an entity.
Returns the result and the result's type."
(declare (ignore expected-type))
(cond ((eq expr '*me*)
(values *me* 'user))
((eq expr 't)
(values t :boolean))
((symbolp expr)
(let ((slot (find expr (entity-slots entity) :key #'entity-slot-name)))
(assert (not (null slot)))
(values (funcall (entity-slot-accessor slot) instance)
(entity-slot-type slot))))
((integerp expr)
(values expr :integer))
((numberp expr)
(values expr :number))
((stringp expr)
(values expr :string))
((listp expr)
(case (car expr)
(filter
(destructuring-bind (list-expr condition-expr)
(cdr expr)
(multiple-value-bind (list list-type)
(eval-expr list-expr instance entity '(:list ?))
(assert (and (listp list-type) (eq (car list-type) :list)))
(let* ((element-type (cadr list-type))
(is-entity (entity-name-p element-type))
(entity (if is-entity (entity-with-name element-type) entity)))
(remove-if-not #'(lambda (x)
(eval-expr condition-expr
(if is-entity x instance)
entity
:boolean))
list)))))
(t
(let ((op (op-with-name (car expr))))
(assert (not (null op)))
(assert (= (length (cdr expr)) (length (op-arg-types op))))
(let ((args (mapcar #'(lambda (arg-expr arg-type)
(eval-expr arg-expr instance entity arg-type))
(cdr expr) (op-arg-types op))))
(values (apply (op-func op) instance args)
(op-type op)))))))
(t
(error "illegal expression ~A" expr))))
(defun actions-for-instance (instance entity)
"Returns a list of all actions whose conditions are met by the
instance."
(remove-if-not #'(lambda (action)
(eval-expr (action-condition action) instance entity :boolean))
*actions*))
(defun removal-action-for-automatr-group (automatr-group)
(let ((name (automatr-group-name automatr-group)))
(make-action :name (intern (format nil "REMOVE-FROM-~A" name))
:action `(remove-from-group ,name)
:condition 't)))
(defun group-removals-for-photo (photo)
(mappend #'(lambda (automatr-group)
(if (and (not (null (automatr-group-condition automatr-group)))
(member photo (group-photos (group-for-automatr-group automatr-group)))
(not (eval-expr (automatr-group-condition automatr-group)
photo
(entity-with-name 'photo)
:boolean)))
(list (removal-action-for-automatr-group automatr-group))
nil))
*automatr-groups*))
(defun group-condition-satisfied (group photo)
(or (null (automatr-group-condition group))
(eval-expr (automatr-group-condition group)
photo
(entity-with-name 'photo)
:boolean)))
(defun action-applicable-p (action photo)
(case-match (action-action action)
((add-tag ?raw)
(not (has-tag photo raw)))
((remove-tag ?raw)
(has-tag photo raw))
((add-to-set ?id)
(let ((set (make-photoset (clickr-base-api-info *me*) id)))
(not (member photo (photoset-photos set)))))
((add-to-group ?name)
(let* ((automatr-group (automatr-group-with-name name))
(group (group-for-automatr-group automatr-group)))
(and (not (member photo (group-photos group)))
(group-condition-satisfied automatr-group photo))))
((remove-from-group ?name)
(let ((group (group-for-automatr-group-with-name name)))
(member photo (group-photos group))))
(?a
(error "Unknown action ~A" a))))
(defun all-applicable-actions (user)
(remove-if #'null
(mappend #'(lambda (photo)
(let* ((actions (actions-for-instance photo (entity-with-name 'photo)))
(applicable-actions (remove-if-not #'(lambda (action)
(action-applicable-p action photo))
actions))
(group-removals (group-removals-for-photo photo)))
(mapcar #'(lambda (a) (cons photo a))
(append applicable-actions group-removals))))
(user-photos user))
:key #'cdr))
(defun apply-action (action photo)
(case-match (action-action action)
((add-tag ?raw)
(add-tag photo (list raw)))
((remove-tag ?raw)
(remove-tag photo raw))
((add-to-set ?id)
(let ((set (make-photoset (clickr-base-api-info *me*) id)))
(add-photo photo set)))
((add-to-group ?name)
(let ((group (group-for-automatr-group-with-name name)))
(add-photo photo group)))
((remove-from-group ?name)
(let ((group (group-for-automatr-group-with-name name)))
(remove-photo photo group)))
(?a
(error "Unknown action ~A" a))))
(defun audit-actions (actions)
(let* ((add-to-group-actions (remove-if-not #'(lambda (a) (matchp (action-action (cdr a)) (add-to-group ?)))
actions))
(group-names (mapcar #'(lambda (a)
(cadr (action-action (cdr a))))
add-to-group-actions))
(group-names (remove-duplicates group-names)))
(reduce #'(lambda (actions group-name)
(let ((group (automatr-group-with-name group-name)))
(if (null (automatr-group-max-batch group))
actions
(slet* ((group-actions other-actions
(partition #'(lambda (a)
(and (matchp (action-action (cdr a)) (add-to-group ?))
(eql (cadr (action-action (cdr a))) group-name)))
actions))
(audited-group-actions (random-select (automatr-group-max-batch group) group-actions)))
(if (not (null (automatr-group-max-posted group)))
(let* ((clickr-group (group-for-automatr-group group))
(user-group-photos (remove-if-not #'(lambda (p)
(eq *me* (photo-owner p)))
(group-photos clickr-group)))
(num-remove (max (- (+ (length user-group-photos) (length audited-group-actions))
(automatr-group-max-posted group))
0))
(remove-photos (random-select num-remove user-group-photos))
(remove-actions (mapcar #'(lambda (p)
(cons p (removal-action-for-automatr-group group)))
remove-photos)))
(append remove-actions audited-group-actions other-actions))
(append audited-group-actions other-actions))))))
group-names :initial-value actions)))
(defun apply-actions (actions)
(dolist (a actions)
(destructuring-bind (photo . action)
a
(apply-action action photo))))
(defun action-html (action)
(case-match (action-action action)
((add-tag ?raw)
(format nil "Add tag ~A" raw))
((remove-tag ?raw)
(format nil "Remove tag ~A" raw))
((add-to-set ?id)
(let ((set (make-photoset (clickr-base-api-info *me*) id)))
(format nil "Add to set ~A" (photoset-title set))))
((add-to-group ?name)
(let ((group (group-for-automatr-group-with-name name)))
(format nil "Add to group ~A" (group-title group))))
((remove-from-group ?name)
(let ((group (group-for-automatr-group-with-name name)))
(format nil "Remove from group ~A" (group-title group))))
(?a
(format nil "Unknown action ~A" a))))
(defun htmlize-actions (actions)
(with-open-file (out "actions.html" :direction :output :if-exists :supersede)
(format out "<html><body><table>~%")
(dolist (a actions)
(destructuring-bind (photo . action)
a
(format out "<tr><td><a href=\"~A\"><img src=\"http://static.flickr.com/~A/~A_~A_t.jpg\"></a><td>~A<td>~A~%"
(photo-photopage-url photo)
(photo-server photo)
(photo-id photo)
(photo-secret photo)
(action-name action)
(action-html action))))
(format out "</table></body></html>~%")))
(defentity photo
((isfavorite #'photo-isfavorite :boolean)
(license #'photo-license)
(ispublic #'photo-ispublic :boolean)
(isfriend #'photo-isfriend :boolean)
(isfamily #'photo-isfamily :boolean)
(owner #'photo-owner user)
(notes #'photo-notes (:list note))
(tags #'photo-tags (:list tag))
(sets #'photo-sets (:list set))
(groups #'photo-groups (:list group))
(sizes #'photo-sizes (:list size))
(num-views #'photo-num-views :integer)
(faves #'(lambda (photo)
(integers-upto (photo-num-faves photo)))
(:list fave))
(comments #'photo-comments (:list comment))))
(defentity user
((username #'user-username)
(realname #'user-realname)
(location #'user-location)
(photos #'user-photos (:list photo))
(sets #'user-photosets (:list set))
(groups #'user-groups (:list group))
(contacts #'user-contacts (:list user))
(faves #'user-favorites (:list photo))))
(defentity set
((title #'photoset-title)
(photos #'photoset-photos (:list photo))))
(defentity group
((title #'group-title)
(photos #'group-photos (:list photo))))
(defentity note
())
(defentity tag
((raw #'tag-raw)
(text #'tag-text)))
(defentity comment
((author #'comment-author)))
(defgroup '1000views
"83435940@N00")
(defgroup 'fav/view>=5%
"39907031@N00"
:max-batch 1)
(defgroup '100v+10f
"72576714@N00"
:max-batch 3)
(defgroup '1000v+100f
"79664037@N00"
:max-batch 1)
(defgroup '1000v+40f
"47981347@N00"
:max-batch 1)
(defgroup '3000v+120f
"95324234@N00"
:max-batch 1)
(defgroup 'centurian
"38475367@N00"
:max-batch 3)
(defgroup '200v
"23348528@N00"
:max-batch 3)
(defgroup '500v+50f
"49764889@N00"
:max-batch 1)
(defgroup '500v+20f
"42378300@N00"
:max-batch 1)
(defgroup '2000v
"74001424@N00"
:max-batch 1)
(defgroup 'fave30times
"22944948@N00"
:max-batch 1)
(defgroup '50faves
"41075027@N00"
:max-batch 1)
(defgroup '100faves
"28795624@N00"
:max-batch 1)
(defgroup '100club
"11512103@N00"
:max-batch 1)
(defgroup 'top-v
"56022122@N00"
:max-batch 1
:max-posted 11)
(defgroup 'top-f
"23561440@N00"
:max-batch 1)
(defgroup 'showcase
"62795763@N00"
:max-batch 1
:max-posted 5)
(defgroup 'noteworthy-notes
"19704745@N00"
:max-batch 1)
(defgroup 'iflickr
"30845071@N00"
:max-batch 1
:max-posted 5)
(defgroup 'flickr-addicts
"76535076@N00"
:max-batch 1
:max-posted 5)
(defgroup 'flickr-central
"34427469792@N01"
:max-batch 1
:max-posted 5)
(defgroup '1-to-5-favorites
"71394080@N00"
:max-batch 1
:max-posted 10
:condition '(and (>= (count faves) 1) (>= 5 (count faves))))
(defgroup '5-to-10-favorites
"28531369@N00"
:max-batch 1
:max-posted 10
:condition '(and (>= (count faves) 5) (>= 10 (count faves))))
(defgroup '10-to-25-favorites
"39445275@N00"
:max-batch 1
:max-posted 10
:condition '(and (>= (count faves) 10) (>= 25 (count faves))))
(dolist (group '((11 1111 "10021501@N00")
(22 2222 "51639810@N00")
(33 3333 "93348988@N00")
(44 4444 "13466285@N00")
(55 5555 "63242381@N00")
(77 7777 "66069685@N00")
(88 8888 "82243602@N00")
(99 9999 "63114470@N00")))
nil)
(dolist (num '(111 333 555 777 999 1111 2222 3333 4444 5555 6666 7777 8888 9999))
(add-action (intern (format nil "TOP-V~A" num))
`(add-tag ,(format nil "top-v~A" num))
`(>= num-views ,num)))
(add-action 'top-v
'(add-to-group top-v)
'(>= num-views 111))
(add-action 'top-f
'(add-to-group top-f)
'(>= (count faves) 25))
(dolist (num '(25 50 75 100 150 200 250 300 350 400 450 500))
(add-action (intern (format nil "TOP-F~A" num))
`(add-tag ,(format nil "top-f~A" num))
`(>= (count faves) ,num)))
(dolist (vals '((25 50) (51 75) (76 100) (101 150) (151 200) (201 250) (251 300)))
(destructuring-bind (bound num)
vals
(add-action (intern (format nil "TOP-C~A" num))
`(add-tag ,(format nil "top-c~A" num))
`(>= (count (filter comments (not (eq author *me*)))) ,bound))))
(add-action 'most-faved
'(add-to-set "487122")
'(>= (count faves) 30))
(add-action '1000views
'(add-to-group 1000views)
'(>= num-views 1000))
(add-action 'fav/view>=5%
'(add-to-group fav/view>=5%)
'(and (>= (count faves) 5) (>= (/ (count faves) num-views) 0.05)))
(add-action '100v+10f
'(add-to-group 100v+10f)
'(and (>= num-views 100) (>= (count faves) 10)))
(add-action '1000v+40f
'(add-to-group 1000v+40f)
'(and (and (>= num-views 1000) (>= 1500 num-views)) (>= (count faves) 40)))
(add-action '1000v+40f-tag
'(add-tag "1000v40f")
'(and (and (>= num-views 1000) (>= 1500 num-views)) (>= (count faves) 40)))
(add-action '1000v+100f
'(add-to-group 1000v+100f)
'(and (>= num-views 1000) (>= (count faves) 100)))
(add-action '3000v+120f
'(add-to-group 3000v+120f)
'(and (>= num-views 3000) (>= (count faves) 120)))
(add-action 'centurian
'(add-to-group centurian)
'(and (>= num-views 100) (>= 190 num-views)))
(add-action '200v
'(add-to-group 200v)
'(>= num-views 200))
(add-action '500v+50f
'(add-to-group 500v+50f)
'(and (>= num-views 500) (>= (count faves) 50)))
(add-action '500v+20f
'(add-to-group 500v+20f)
'(and (and (>= num-views 500) (>= 1000 num-views))
(>= (count faves) 20)))
(add-action '500v+20f-tag
'(add-tag "500v20f")
'(and (and (>= num-views 500) (>= 1000 num-views))
(>= (count faves) 20)))
(add-action '2000v
'(add-to-group 2000v)
'(>= num-views 2000))
(add-action 'fave30times
'(add-to-group fave30times)
'(>= (count faves) 30))
(add-action '50faves
'(add-to-group 50faves)
'(>= (count faves) 50))
(add-action '100faves
'(add-to-group 100faves)
'(>= (count faves) 100))
(add-action '100club
'(add-to-group 100club)
'(>= (count faves) 100))
(add-action '1-to-5-favorites
'(add-to-group 1-to-5-favorites)
't)
(add-action '5-to-10-favorites
'(add-to-group 5-to-10-favorites)
't)
(add-action '10-to-25-favorites
'(add-to-group 10-to-25-favorites)
't)
(add-action 'showcase
'(add-to-group showcase)
'(in-set "292480"))
(add-action 'noteworthy-notes
'(add-to-group noteworthy-notes)
'(>= (count notes) 1))
(add-state-tag-actions '1-5-fav
"1-5-fav"
'(and (>= (count faves) 1) (>= 5 (count faves))))
(add-state-tag-actions '5-10-fav
"5-10-fav"
'(and (>= (count faves) 5) (>= 10 (count faves))))
(add-state-tag-actions '10-25-fav
"10-25-fav"
'(and (>= (count faves) 10) (>= 25 (count faves))))
;(add-action 'iflickr
; '(add-to-group iflickr)
; '(or (in-set "292480") (>= (count faves) 10)))
;(add-action 'flickr-addicts
; '(add-to-group flickr-addicts)
; '(or (in-set "292480") (>= (count faves) 10)))
;(add-action 'flickr-central
; '(add-to-group flickr-central)
; '(or (in-set "292480") (>= (count faves) 10)))
| 18,632 | Common Lisp | .lisp | 548 | 29.436131 | 110 | 0.640102 | schani/clickr | 8 | 1 | 1 | GPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | b33b2a713b15ea6ffd671a6ee5a2d6d43ea5efaac440d7424e893556511dc516 | 12,159 | [
-1
] |
12,160 | clickr.lisp | schani_clickr/clickr.lisp | ;;; clickr.lisp --- High-level Flickr interface
;; Copyright (C) 2006 Mark Probst
;; Author: Mark Probst <[email protected]>
;; Maintainer: Mark Probst <[email protected]>
;; Version: 0.2
;; 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 2, 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, you can either send email to this
;; program's maintainer or write to: The Free Software Foundation,
;; Inc.; 675 Massachusetts Avenue; Cambridge, MA 02139, USA.
(defpackage "CLICKR"
(:use "CL" "TRIVIAL-HTTP" "FLICKR" "UTILS")
(:export #:user-with-name #:user-photopage-url #:photo-photopage-url #:group-url #:reset-clickr
#:add-tag #:remove-tag #:has-tag #:add-photo #:remove-photo #:clickr-base-api-info #:contact-info
#:make-photo))
(in-package :clickr)
(defvar *views-scanner* (cl-ppcre:create-scanner "Viewed <b>((\\d+)</b> times|once</b>)"))
(defvar *faves-scanner* (cl-ppcre:create-scanner "fave_count = (\\d+);</script>"))
(defclass clickr-base ()
((api-info :accessor clickr-base-api-info :initarg :api-info)))
(defmacro defapiclass (name &key key sources fetchers custom-fetchers extra-slots)
(when (null key)
(error "CLickr API Class ~A has no key" name))
(labels ((accessor-method (class-name slot-name fetcher-name)
(let ((accessor-name (intern (format nil "~A-~A" class-name slot-name))))
`(progn
(defmethod ,accessor-name ((instance ,class-name))
,(if (null fetcher-name)
'()
`(unless (slot-boundp instance ',slot-name)
(,fetcher-name instance)))
(slot-value instance ',slot-name))
(export ',accessor-name))))
(taker-name (struct-name)
(intern (format nil "TAKE-VALUES-FROM-~A" struct-name)))
(source-with-struct-name (struct-name)
(assoc struct-name sources))
(source-slots (source)
(destructuring-bind (struct-name slots &key custom)
source
(declare (ignore struct-name))
(apply #'append slots (mapcar #'car custom))))
(fetcher-name (struct-name)
(intern (format nil "FETCH-FROM-~A" struct-name)))
(fetcher-name-for-slot (slot-name)
(labels ((find-fetcher (fetchers)
(if (null fetchers)
nil
(let* ((struct-name (caar fetchers))
(slots (source-slots (source-with-struct-name struct-name))))
(if (member slot-name slots)
(fetcher-name struct-name)
(find-fetcher (cdr fetchers)))))))
(find-fetcher fetchers))))
(let* ((non-key-slots (reduce #'union (append (mapcar #'cadr sources)
(mapcar #'source-slots sources)
(mapcar #'car custom-fetchers))))
(slots (cons key non-key-slots))
(hash-table-name (intern (format nil "*~A-HASH-TABLE*" name)))
(constructor-name (intern (format nil "MAKE-~A" name)))
(key-accessor-name (intern (format nil "~A-~A" name key))))
`(progn
(defvar ,hash-table-name (make-hash-table :test #'equal)) ;the hash table
(defclass ,name (clickr-base) ;the class
((,key :accessor ,key-accessor-name)
,@non-key-slots ,@extra-slots))
(export ',key-accessor-name)
(defun ,constructor-name (api-info ,key) ; the constructor
(let ((instance (gethash ,key ,hash-table-name)))
(when (null instance)
(setf instance (make-instance ',name))
(setf (slot-value instance 'api-info) api-info)
(setf (slot-value instance ',key) ,key)
(setf (gethash ,key ,hash-table-name) instance))
instance))
(export ',constructor-name)
,@(mappend #'(lambda (source)
(destructuring-bind (struct-name source-slots &key custom)
source
`((defmethod ,(taker-name struct-name) ((instance ,name) struct) ;the takers
(with-slots ,source-slots instance
,@(mapcar #'(lambda (slot) ;automatic slots
(let ((struct-slot-name (intern (format nil "~A-~A"
struct-name slot)
(find-package 'flickr))))
`(setf ,slot (,struct-slot-name struct))))
source-slots)
,@(mapcar #'(lambda (custom-item) ;custom slots
`(funcall ,(cadr custom-item) instance struct))
custom)))
(defun ,(intern (format nil "MAKE-~A-FROM-~A" name struct-name)) (api-info struct) ;the makers
(let ((instance (,constructor-name api-info (,(intern (format nil "~A-~A"
struct-name key))
struct))))
(,(taker-name struct-name) instance struct)
instance)))))
sources)
,@(mapcar #'(lambda (fetcher) ;the fetchers
(destructuring-bind (struct-name fetch)
fetcher
(let ((fetcher-name (fetcher-name struct-name)))
`(defmethod ,fetcher-name ((instance ,name))
(with-slots ,slots instance
(,(taker-name struct-name) instance ,fetch))))))
fetchers)
,@(mapcar #'(lambda (fetch-slot) ;the accessors
(let ((fetcher-name (fetcher-name-for-slot fetch-slot)))
(accessor-method name fetch-slot fetcher-name)))
non-key-slots)
,@(mappend #'(lambda (fetcher) ; the custom fetcher accessors
(destructuring-bind (fetch-slots fetcher-name)
fetcher
(mapcar #'(lambda (fetch-slot)
(accessor-method name fetch-slot fetcher-name))
fetch-slots)))
custom-fetchers)))))
(defapiclass user
:key id
:sources ((flickr-person
(username realname mbox-sha1sum location ispro))
(flickr-user
(username))
(flickr-contact
(username realname))
(flickr-public-contact
(username)))
:fetchers ((flickr-person
(people-get-info (clickr-base-api-info instance) id)))
:custom-fetchers (((photos)
fetch-user-photos)
((photosets)
fetch-user-photosets)
((groups)
fetch-user-groups)
((contacts)
fetch-user-contacts)
((favorites)
fetch-user-favorites))
:extra-slots (contact-list))
(defun user-with-name (api-info name)
(let* ((flickr-user (people-find-by-username api-info name))
(user (make-user api-info (flickr-user-id flickr-user))))
(take-values-from-flickr-user user flickr-user)
user))
(defmethod user-photopage-url ((user user))
(format nil "http://www.flickr.com/photos/~A" (user-id user)))
(defapiclass note ;FIXME: add photo slot
:key id
:sources ((flickr-note
(x y w h text)
:custom (((author)
#'(lambda (instance flickr-note)
(setf (slot-value instance 'author)
(make-user (clickr-base-api-info instance) (flickr-note-author flickr-note)))))))))
(defapiclass tag ;FIXME: add photo slot
:key id
:sources ((flickr-tag
(raw text)
:custom (((author)
#'(lambda (instance flickr-tag)
(setf (slot-value instance 'author)
(make-user (clickr-base-api-info instance) (flickr-tag-author flickr-tag)))))))))
(defapiclass comment ;FIXME: add photo slot
:key id
:sources ((flickr-comment
(date-create permalink text)
:custom (((author)
#'(lambda (instance flickr-comment)
(setf (slot-value instance 'author)
(make-user (clickr-base-api-info instance) (flickr-comment-author flickr-comment)))))))))
(defapiclass photo
:key id
:sources ((flickr-full-photo
(secret server isfavorite license rotation
title description
ispublic isfriend isfamily
posted taken takengranularity lastupdate
permcomment permaddmeta
cancomment canaddmeta
urls)
:custom (((owner notes tags)
#'(lambda (instance full-photo)
(setf (slot-value instance 'owner)
(make-user (clickr-base-api-info instance) (flickr-full-photo-owner full-photo)))
(let ((notes (mapcar #'(lambda (x) (make-note-from-flickr-note (clickr-base-api-info instance) x))
(flickr-full-photo-notes full-photo)))
(tags (mapcar #'(lambda (x) (make-tag-from-flickr-tag (clickr-base-api-info instance) x))
(flickr-full-photo-tags full-photo))))
(setf (slot-value instance 'notes) notes)
(setf (slot-value instance 'tags) tags))))))
(flickr-search-photo
(secret server title
ispublic isfriend isfamily)
:custom (((owner)
#'(lambda (instance search-photo)
(setf (slot-value instance 'owner)
(make-user (clickr-base-api-info instance) (flickr-search-photo-owner search-photo)))))))
(flickr-photoset-photo
(secret server title))
(flickr-favorite
(secret server title
ispublic isfriend isfamily)
:custom (((owner)
#'(lambda (instance favorite)
(setf (slot-value instance 'owner)
(make-user (clickr-base-api-info instance) (flickr-favorite-owner favorite))))))))
:fetchers ((flickr-full-photo
(photos-get-info (clickr-base-api-info instance) id))) ;FIXME: pass secret if available
:custom-fetchers (((sets groups)
fetch-photo-contexts)
((sizes)
fetch-photo-sizes)
((comments)
fetch-photo-comments)
((num-views num-faves)
fetch-non-api-photo-stuff)))
(defapiclass photoset
:key id
:sources ((flickr-photoset
(primary secret server title description))
(flickr-photoset-info
(primary title description)
:custom (((owner)
#'(lambda (instance photoset-info)
(setf (slot-value instance 'owner)
(make-user (clickr-base-api-info instance) (flickr-photoset-info-owner photoset-info)))))))
(flickr-context-set
(title)))
:fetchers ((flickr-photoset-info
(photosets-get-info (clickr-base-api-info instance) id)))
:custom-fetchers (((photos)
fetch-photoset-photos)))
(defapiclass group
:key id
:sources ((flickr-group
(title description privacy))
(flickr-list-group
(title))
(flickr-context-pool
(title)))
:fetchers ((flickr-group
(groups-get-info (clickr-base-api-info instance) id)))
:custom-fetchers (((photos)
fetch-group-photos)))
(defmethod fetch-group-photos ((group group))
(let ((photos (collect-pages #'(lambda (per-page page)
(groups-pools-get-photos (clickr-base-api-info group) (group-id group)
:per-page per-page :page page)))))
(setf (slot-value group 'photos)
(mapcar #'(lambda (x) (make-photo-from-flickr-search-photo (clickr-base-api-info group) x))
photos))))
(defmethod fetch-user-photos ((user user))
(let ((photos (collect-pages #'(lambda (per-page page)
(photos-search (clickr-base-api-info user) :user-id (user-id user)
:per-page per-page :page page)))))
(setf (slot-value user 'photos)
(mapcar #'(lambda (x) (make-photo-from-flickr-search-photo (clickr-base-api-info user) x))
photos))))
(defmethod fetch-user-photosets ((user user))
(let ((photosets (photosets-get-list (clickr-base-api-info user) (user-id user))))
(setf (slot-value user 'photosets)
(mapcar #'(lambda (x) (make-photoset-from-flickr-photoset (clickr-base-api-info user) x))
photosets))))
(defmethod fetch-user-groups ((user user))
(let ((groups (people-get-public-groups (clickr-base-api-info user) (user-id user))))
(setf (slot-value user 'groups)
(mapcar #'(lambda (x) (make-group-from-flickr-list-group (clickr-base-api-info user) x))
groups))))
(defmethod fetch-photoset-photos ((photoset photoset))
(let ((photos (photosets-get-photos (clickr-base-api-info photoset) (photoset-id photoset))))
(setf (slot-value photoset 'photos)
(mapcar #'(lambda (x) (make-photo-from-flickr-photoset-photo (clickr-base-api-info photoset) x))
photos))))
(defmethod fetch-photo-contexts ((photo photo))
(let ((contexts (photos-get-all-contexts (clickr-base-api-info photo) (photo-id photo))))
(setf (slot-value photo 'sets)
(mapcar #'(lambda (context-set)
(let ((set (make-photoset (clickr-base-api-info photo) (flickr-context-set-id context-set))))
(take-values-from-flickr-context-set set context-set)
set))
(remove-if-not #'flickr-context-set-p contexts)))
(setf (slot-value photo 'groups)
(mapcar #'(lambda (context-pool)
(let ((group (make-group (clickr-base-api-info photo) (flickr-context-pool-id context-pool))))
(take-values-from-flickr-context-pool group context-pool)
group))
(remove-if-not #'flickr-context-pool-p contexts)))))
(defmethod fetch-user-contacts ((user user))
(let ((contacts (contacts-get-public-list (clickr-base-api-info user) (user-id user))))
(setf (slot-value user 'contacts)
(mapcar #'(lambda (contact)
(let ((contact-user (make-user (clickr-base-api-info user) (flickr-public-contact-id contact))))
(take-values-from-flickr-public-contact contact-user contact)
contact-user))
contacts))))
(defmethod fetch-user-favorites ((user user))
(let ((favorites (collect-pages #'(lambda (per-page page)
(favorites-get-public-list (clickr-base-api-info user) (user-id user)
:per-page per-page :page page)))))
(setf (slot-value user 'favorites)
(mapcar #'(lambda (favorite)
(let ((photo (make-photo (clickr-base-api-info user) (flickr-favorite-id favorite))))
(take-values-from-flickr-favorite photo favorite)
photo))
favorites))))
(defmethod fetch-photo-sizes ((photo photo))
(setf (slot-value photo 'sizes) (photos-get-sizes (clickr-base-api-info photo) (photo-id photo))))
(defmethod fetch-photo-comments ((photo photo))
(let ((comments (photos-comments-get-list (clickr-base-api-info photo) (photo-id photo))))
(setf (slot-value photo 'comments)
(mapcar #'(lambda (x) (make-comment-from-flickr-comment (clickr-base-api-info photo) x)) comments))))
(defmethod photo-photopage-url ((photo photo))
(let ((urls (photo-urls photo)))
(flickr-url-url (find-if #'(lambda (url) (string-equal "photopage" (flickr-url-type url))) urls))))
(defmethod group-url ((group group))
(format nil "http://www.flickr.com/groups/~A" (group-id group)))
(defun read-url-response (url)
(destructuring-bind (code headers stream)
(http-get url)
(declare (ignore code headers))
(let ((lines nil))
(do ((line (read-line stream nil nil) (read-line stream nil nil)))
((null line))
(push line lines))
(close stream)
(apply #'concatenate 'string (reverse lines)))))
;; Returns number of views and number of faves.
(defmethod read-photo-counts ((photo photo))
(let* ((url (photo-photopage-url photo))
(html (read-url-response url))
(num-views (multiple-value-bind (match regs)
(cl-ppcre:scan-to-strings *views-scanner* html)
(declare (ignore match))
(cond ((null regs)
0)
((null (aref regs 1))
1)
(t
(parse-integer (aref regs 1))))))
(num-faves (multiple-value-bind (match regs)
(cl-ppcre:scan-to-strings *faves-scanner* html)
(declare (ignore match))
(if (null regs)
0
(parse-integer (aref regs 0))))))
(values num-views
num-faves)))
(defmethod fetch-non-api-photo-stuff ((photo photo))
(multiple-value-bind (num-views num-faves comments)
(read-photo-counts photo)
(setf (slot-value photo 'num-views) num-views)
(setf (slot-value photo 'num-faves) num-faves)
(setf (slot-value photo 'comments) comments)))
(defun reset-clickr ()
(setf *user-hash-table* (make-hash-table :test #'equal))
(setf *note-hash-table* (make-hash-table :test #'equal))
(setf *tag-hash-table* (make-hash-table :test #'equal))
(setf *photo-hash-table* (make-hash-table :test #'equal))
(setf *photoset-hash-table* (make-hash-table :test #'equal))
(setf *group-hash-table* (make-hash-table :test #'equal)))
(defun text-for-raw-tag (raw)
(string-downcase (remove-if #'(lambda (c) (find c " _-")) raw)))
(defmethod add-tag ((photo photo) tags)
(photos-add-tags (clickr-base-api-info photo) (photo-id photo) tags)
(slot-makunbound photo 'tags))
(defmethod remove-tag ((photo photo) (tag tag))
(assert (member tag (photo-tags photo)))
(photos-remove-tag (clickr-base-api-info photo) (tag-id tag))
(slot-makunbound photo 'tags))
(defmethod remove-tag ((photo photo) (raw string))
(let* ((text (text-for-raw-tag raw))
(tag (find text (photo-tags photo) :key #'tag-text :test #'string-equal)))
(if (null tag)
(error "Photo has no tag ~A" raw)
(remove-tag photo tag))))
(defmethod has-tag ((photo photo) (raw string))
(let ((text (text-for-raw-tag raw)))
(member text (photo-tags photo) :key #'tag-text :test #'string-equal)))
(defmethod add-photo ((photo photo) (set photoset))
(photosets-add-photo (clickr-base-api-info photo) (photoset-id set) (photo-id photo))
(slot-makunbound photo 'sets)
(slot-makunbound set 'photos))
(defmethod add-photo ((photo photo) (group group))
(ignore-errors (groups-pools-add (clickr-base-api-info photo) (photo-id photo) (group-id group)))
(slot-makunbound photo 'groups)
(slot-makunbound group 'photos))
(defmethod remove-photo ((photo photo) (group group))
(ignore-errors (groups-pools-remove (clickr-base-api-info photo) (photo-id photo) (group-id group)))
(slot-makunbound photo 'groups)
(slot-makunbound group 'photos))
(defmethod contact-info ((user user) (contact user))
(unless (string= (user-id user) (flickr-user-id (flickr-api-info-user (clickr-base-api-info user))))
(error "Cannot get contact info for user ~A" (user-id user)))
(unless (slot-boundp user 'contact-list)
(setf (slot-value user 'contact-list) (contacts-get-list (clickr-base-api-info user))))
(let ((flickr-contact (find (user-id contact) (slot-value user 'contact-list) :key #'flickr-contact-id :test #'string=)))
(unless flickr-contact
(error "Have no contact ~A" (user-id contact)))
(append (if (flickr-contact-isfriend flickr-contact) '(:isfriend) nil)
(if (flickr-contact-isfamily flickr-contact) '(:isfamily) nil)
(if (flickr-contact-ignored flickr-contact) '(:ignored) nil))))
| 18,337 | Common Lisp | .lisp | 408 | 39.27451 | 123 | 0.665306 | schani/clickr | 8 | 1 | 1 | GPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 32b4a1d3adff9edbde3f5f9031ddef5a31eee07695638f42bf7af6f02333258c | 12,160 | [
-1
] |
12,161 | let-match.lisp | schani_clickr/let-match.lisp | ;; let-match.lisp
;; MathMap
;; Copyright (C) 1999-2002 Mark Probst
;; 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 2, 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, you can either send email to this
;; program's maintainer or write to: The Free Software Foundation,
;; Inc.; 675 Massachusetts Avenue; Cambridge, MA 02139, USA.
(defpackage :let-match
(:use :cl)
(:export
#:let-match #:case-match #:matchp))
(in-package :let-match)
(defun var-symbol-p (sym)
(and (symbolp sym)
(> (length (symbol-name sym)) 1)
(eq (elt (symbol-name sym) 0) #\?)))
(defun symbol-for-var-symbol (sym)
(intern (subseq (symbol-name sym) 1)))
(defun dont-care-symbol-p (sym)
(and (symbolp sym)
(string-equal (symbol-name sym) "?")))
(defun quoted-p (val)
(and (consp val) (eq (car val) 'quote)))
(defun compile-let-match (pattern val succ-cont fail-cont bound-vars)
(cond ((null pattern)
(if (quoted-p val)
(if (null (cadr val))
(funcall succ-cont bound-vars)
(funcall fail-cont))
`(if (null ,val)
,(funcall succ-cont bound-vars)
,(funcall fail-cont))))
((dont-care-symbol-p pattern)
(funcall succ-cont bound-vars))
((var-symbol-p pattern)
(let ((bound (assoc pattern bound-vars)))
(if bound
(let ((static (second bound))
(value (third bound)))
(if static
(if (quoted-p val)
(if (equal value val)
(funcall succ-cont bound-vars)
(funcall fail-cont))
`(if (equal ,value ,val)
,(funcall succ-cont bound-vars)
,(funcall fail-cont)))
`(if (equal ,value ,val)
,(funcall succ-cont bound-vars)
,(funcall fail-cont))))
(funcall succ-cont (cons (list pattern (quoted-p val) val) bound-vars)))))
((consp pattern)
(if (quoted-p val)
(let ((val (cadr val)))
(if (consp val)
(compile-let-match (car pattern) `(quote ,(car val))
#'(lambda (bound-vars)
(compile-let-match (cdr pattern) `(quote ,(cdr val))
#'(lambda (bound-vars)
(funcall succ-cont bound-vars))
#'(lambda ()
(funcall fail-cont))
bound-vars))
#'(lambda ()
(funcall fail-cont))
bound-vars)
(funcall fail-cont)))
`(if (consp ,val)
,(let ((val-car (gensym))
(val-cdr (gensym)))
`(let ((,val-car (car ,val))
(,val-cdr (cdr ,val)))
,(compile-let-match (car pattern) val-car
#'(lambda (bound-vars)
(compile-let-match (cdr pattern) val-cdr
#'(lambda (bound-vars)
(funcall succ-cont bound-vars))
#'(lambda ()
(funcall fail-cont))
bound-vars))
#'(lambda ()
(funcall fail-cont))
bound-vars)))
,(funcall fail-cont))))
(t
(if (quoted-p val)
(if (equal pattern (cadr val))
(funcall succ-cont bound-vars)
(funcall fail-cont))
`(if (equal ',pattern ,val)
,(funcall succ-cont bound-vars)
,(funcall fail-cont))))))
(defmacro let-match (bindings body &optional (fail nil))
(labels ((compiler (bindings fail-expr bound-vars)
(if (null bindings)
(if (null bound-vars)
body
`(let ,(mapcar #'(lambda (binding)
(list (symbol-for-var-symbol (first binding)) (third binding)))
bound-vars)
,body))
(compile-let-match (caar bindings) (cadar bindings)
#'(lambda (bound-vars)
(compiler (cdr bindings) fail-expr bound-vars))
#'(lambda ()
fail-expr)
bound-vars))))
(let* ((fail-name (if (null fail) nil (gensym)))
(fail-expr (if (null fail) nil `(,fail-name)))
(matcher (compiler bindings fail-expr nil)))
(if (null fail)
matcher
`(flet ((,fail-name () ,fail))
,matcher)))))
(defmacro case-match (value &rest cases)
(let ((value-name (gensym))
(cases (mapcar #'(lambda (case) (cons (gensym) case)) cases)))
(labels ((compiler (cases)
(if (null cases)
nil
(let* ((case (car cases))
(label-name (car case))
(pattern (cadr case))
(body-forms (cddr case)))
`((,label-name ()
,@(if (member pattern '(t otherwise))
body-forms
(list (compile-let-match pattern value-name
#'(lambda (bound-vars)
`(let ,(mapcar #'(lambda (binding)
(list (symbol-for-var-symbol (first binding)) (third binding)))
bound-vars)
,@body-forms))
#'(lambda ()
(if (null (cdr cases))
'nil
`(,(caadr cases))))
nil))))
,@(compiler (cdr cases)))))))
`(let ((,value-name ,value))
(labels ,(compiler cases)
,(if (caar cases)
`(,(caar cases))
nil))))))
(defmacro matchp (value pattern)
`(case-match ,value
(,pattern t)
(? nil)))
| 5,340 | Common Lisp | .lisp | 156 | 27.673077 | 80 | 0.592184 | schani/clickr | 8 | 1 | 1 | GPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | ed9014402d44f3d471c44ff8466830307fa64ab281dda780ea771c5968a0bea6 | 12,161 | [
-1
] |
12,162 | clickr.asd | schani_clickr/clickr.asd | ;;;; -*- indent-tabs-mode: nil; mode: lisp -*-
(defsystem clickr
:name "clickr"
:author "Mark Probst"
:licence "GPL"
:description "High-level Flickr interface"
:depends-on (:trivial-http :md5 :s-xml :s-xml-rpc
:cl-ppcre)
:serial t
:components ((:file "utils")
(:file "let-match")
(:file "flickr")
(:file "clickr")
(:file "automatr")
))
| 526 | Common Lisp | .asd | 15 | 21.4 | 57 | 0.435294 | schani/clickr | 8 | 1 | 1 | GPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 725bba1df3dea1f657d53e6c116c9f120882eb48ab26c11772553d7e765d6ace | 12,162 | [
-1
] |
12,185 | api.lisp | DanielKeogh_hashtrie/api.lisp | ;;;; api.lisp
(in-package #:hashtrie)
(defun add (hashtrie key val)
(declare (optimize (speed 3) (safety 3)))
"Create a new map with the given key-value pair"
(map-assoc hashtrie key val))
(defun remove (hashtrie key)
(declare (optimize (speed 3) (safety 3)))
"Remove the pair from the hash trie"
(map-without hashtrie key))
(defun value (hashtrie key &optional not-found)
(declare (optimize (speed 3) (safety 3)))
"Get the value for a given key"
(map-val-at hashtrie key not-found))
(defun has-key (hashtrie key)
(declare (optimize (speed 3) (safety 3)))
"Test if the key is in the hash trie"
(let ((missing (gensym)))
(not (equal missing (map-val-at hashtrie key missing)))))
(defun map (hashtrie fn)
(declare (optimize (speed 3) (safety 3)))
"Apply a (lambda (x y)) to each key-value pair and collect the results into a list"
(map-map hashtrie fn))
(defun reduce (hashtrie fn &optional start-val)
(declare (optimize (speed 3) (safety 3)))
"Apply (lambda (start key val)) to aggregate all pairs of a persistent hash map"
(map-reduce hashtrie fn start-val))
(defun length (hashtrie)
(declare (optimize (speed 3) (safety 3)))
"The number of pairs in the hash trie"
(map-count hashtrie))
(defmacro with-transient ((name map) &body body)
(declare (optimize (speed 3) (safety 3)))
"Within the body of this macro modify a temporary, transient copy of the hash trie. e.g. (with-transient (name (make-has-trie)) <body>). The transient copy will not be thread safe.
Returns a new persistent hash trie"
`(let ((,name (hashtrie::phm-as-transient ,map)))
(progn ,@body)
(hashtrie::thm-persistent ,name)))
| 1,713 | Common Lisp | .lisp | 38 | 40.973684 | 183 | 0.689801 | DanielKeogh/hashtrie | 8 | 0 | 1 | EPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 09cdfecdc20362363dddf8d1b33ca2da1048c3cfbced65a95dc0fd62dd3b2ebd | 12,185 | [
-1
] |
12,186 | package.lisp | DanielKeogh_hashtrie/package.lisp | ;;;; package.lisp
(defpackage #:hashtrie
(:documentation "Persistent/Immutable Hash Trie datastructure based upon Clojure")
(:use #:cl)
(:shadow
#:length
#:map
#:reduce
#:remove)
(:export
;; Important functions
#:make-hashtrie
#:with-transient
#:add
#:remove
#:value
#:has-key
#:map
#:reduce
#:length
;; Types
#:hashtrie
#:hashtrie-p
#:persistent-hashtrie
#:persistent-hashtrie-p
#:transient-hashtrie
#:transient-hashtrie-p))
| 500 | Common Lisp | .lisp | 27 | 14.814815 | 85 | 0.653928 | DanielKeogh/hashtrie | 8 | 0 | 1 | EPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 1ff4360ae37bd6ed83f54d8f4a2f4f212858600bc991f2c112ec6fc6ce055abc | 12,186 | [
-1
] |
12,187 | hashtrie.lisp | DanielKeogh_hashtrie/hashtrie.lisp | ;;;; hashtrie.lisp
(in-package #:hashtrie)
(defstruct (hashtrie (:constructor nil)))
(defstruct (persistent-hashtrie (:conc-name phm-)
(:include hashtrie))
(meta nil :type (or null hashtrie))
(count nil :type uint :read-only t)
(root nil :type (or null hash-map-node) :read-only t)
(has-null nil :type boolean :read-only t)
(null-value nil :read-only t))
(defstruct (transient-hashtrie (:conc-name thm-)
(:include hashtrie))
(edit nil :read-only t)
(count nil :type uint)
(root nil :type (or null hash-map-node))
(has-null nil :type boolean)
(null-value nil)
(leaf-flag (make-box) :read-only t))
(defstruct hash-map-node)
(defstruct (hash-map-bitmap-node (:conc-name hmn-)
(:include hash-map-node))
(edit nil)
(bitmap nil :type uint)
(array nil :type (simple-array t (*))))
(defstruct (hash-map-array-node (:conc-name hman-)
(:include hash-map-node))
(edit nil)
(count nil :type uint)
(array nil :type (simple-array t (*))))
(defstruct (hash-map-collision-node (:conc-name hmcn-)
(:include hash-map-node))
(edit nil)
(hash nil :type uint :read-only t)
(count nil :type uint)
(array nil :type (simple-array t (*))))
(defgeneric map-make-iterator (hash-map))
(defgeneric map-val-at (hash-map key &optional not-found))
(defgeneric map-without (hash-map key))
(defgeneric map-count (hash-map))
(defgeneric node-make-iterator (node))
(defgeneric node-find (node shift hash key not-found))
(defgeneric node-without (node shift hash key))
(defgeneric node-without-edit (node edit shift hash key removed-leaf))
(defvar *empty-hash-iterator* (lambda () (values nil nil nil)))
(declaim (type hash-map-bitmap-node *empty-hash-map-node*))
(defvar *empty-hash-map-node* (make-hash-map-bitmap-node :bitmap 0 :array (make-array 0)))
(declaim (type persistent-hashtrie *empty-hash-map*))
(defvar *empty-hash-map* (make-persistent-hashtrie :count 0 :root nil :has-null nil :null-value nil))
(defvar *not-found* (gensym))
(declaim (inline hmn-index))
(defun hmn-index (node bit)
(declare (optimize (speed 3) (safety 0))
(type uint bit))
(logandcount (hmn-bitmap node) (1- bit)))
(declaim (inline mask))
(defun mask (hash shift)
(declare (type uint hash)
(type fixnum shift)
(optimize (speed 3) (safety 0)))
(the uint (logand (ash hash (the fixnum (- shift))) +mask+)))
(declaim (inline bitpos))
(defun bitpos (hash shift)
(declare (type uint hash)
(type fixnum shift)
(optimize (speed 3) (safety 0)))
(the uint (ash 1 (the uint (mask hash shift)))))
(declaim (inline clone-and-set1))
(defun clone-and-set1 (array i new-val)
(declare (type (simple-array t (*)) array)
(optimize (speed 3) (safety 0)))
(let ((new-array (copy-seq array)))
(declare (type (simple-array t (*)) new-array))
(setf (aref new-array i) new-val)
new-array))
(defun clone-and-set2 (array i new-val j new-val2)
(declare (type (simple-array t (*)) array)
(optimize (speed 3) (safety 0)))
(let ((new-array (copy-seq array)))
(declare (type (simple-array t (*)) new-array))
(setf (aref new-array i) new-val)
(setf (aref new-array j) new-val2)
new-array))
(declaim (inline node-assoc-edit))
(defun node-assoc-edit (node edit shift hash key val added-leaf)
(declare (optimize (speed 3) (safety 0)))
(typecase node
(hash-map-array-node (node-assoc-edit-array-node node edit shift hash key val added-leaf))
(hash-map-bitmap-node (node-assoc-edit-bitmap-node node edit shift hash key val added-leaf))
(hash-map-collision-node (node-assoc-edit-collision-node node edit shift hash key val added-leaf))))
(declaim (inline node-assoc))
(defun node-assoc (node shift hash key val added-leaf)
(declare (optimize (speed 3) (safety 0)))
(typecase node
(hash-map-array-node (node-assoc-array-node node shift hash key val added-leaf))
(hash-map-bitmap-node (node-assoc-bitmap-node node shift hash key val added-leaf))
(hash-map-collision-node (node-assoc-collision-node node shift hash key val added-leaf))))
(defun create-node (shift key1 val1 key2hash key2 val2)
(declare (optimize (speed 3) (safety 0))
(type uint key2hash))
(let ((key1hash (the uint (hash key1))))
(if (= key1hash key2hash)
(make-hash-map-collision-node :edit nil :hash key1hash :count 2 :array (make-array 4 :initial-contents (list key1 val1 key2 val2)))
(let* ((added-leaf (make-box))
(edit (make-atomic-reference))
(n1 (node-assoc-edit-bitmap-node *empty-hash-map-node* edit shift key1hash key1 val1 added-leaf)))
(node-assoc-edit n1 edit shift key2hash key2 val2 added-leaf)))))
(defun create-edit-node (edit shift key1 val1 key2hash key2 val2)
(declare (optimize (speed 3) (safety 0))
(type uint key2hash))
(let ((key1hash (hash key1)))
(if (= key1hash key2hash)
(make-hash-map-collision-node :edit nil :hash key1hash :count 2 :array (make-array 0 :initial-contents (list key1 val1 key2 val2)))
(let* ((added-leaf (make-box))
(n1 (node-assoc-edit-bitmap-node *empty-hash-map-node* edit shift key1hash key1 val1 added-leaf)))
(node-assoc-edit n1 edit shift key2hash key2 val2 added-leaf)))))
;;; Persisent hash map impl
(defun phm-as-transient (map)
(declare (optimize (speed 3) (safety 0)))
(make-transient-hashtrie
:edit (make-atomic-reference :val t)
:count (phm-count map)
:root (phm-root map)
:has-null (phm-has-null map)
:null-value (phm-null-value map)))
(defun persistent-map-assoc (map key val)
(declare (optimize (speed 3) (safety 0))
(type persistent-hashtrie map))
(with-accessors ((has-null phm-has-null)
(null-value phm-null-value)
(count phm-count)
(root phm-root)
(meta phm-meta))
map
(if (not key)
(if (and has-null (eq val null-value))
map
(make-persistent-hashtrie :meta meta
:count (if has-null count (1+ count))
:root root
:has-null t
:null-value val))
(let* ((added-leaf (make-box))
(new-root (node-assoc (if (null root) *empty-hash-map-node* root)
0 (hash key) key val added-leaf)))
(if (eq new-root root)
map
(make-persistent-hashtrie :meta meta
:count (if (box-val added-leaf)
(1+ count)
count)
:root new-root
:has-null has-null
:null-value null-value))))))
(defmethod map-val-at ((map persistent-hashtrie) key &optional not-found)
(declare (optimize (speed 3) (safety 0)))
(with-accessors ((root phm-root)
(has-null phm-has-null)
(null-value phm-null-value))
map
(if (not key)
(if has-null null-value not-found)
(if root (node-find root 0 (hash key) key not-found) not-found))))
(defmethod map-make-iterator ((map persistent-hashtrie))
(declare (optimize (speed 3) (safety 0)))
(with-accessors ((root phm-root)
(has-null phm-has-null)
(null-value phm-null-value))
map
(let ((itr (if root (node-make-iterator root)
*empty-hash-iterator*)))
(declare (type (function ()) itr))
(if has-null
(let (returned-nil)
(lambda ()
(if returned-nil
(funcall itr)
(progn
(setf returned-nil t)
(values t nil null-value)))))
itr))))
(defmethod map-without ((map persistent-hashtrie) key)
(declare (optimize (speed 3) (safety 0)))
(with-accessors ((meta phm-meta)
(count phm-count)
(root phm-root)
(has-null phm-has-null))
map
(cond ((null key) (if (phm-has-null map)
(make-persistent-hashtrie :meta meta
:count (the uint (1- count))
:root root
:has-null nil
:null-value nil)))
((null root) map)
(t (let ((new-root (node-without root 0 (hash key) key)))
(if (eq root new-root)
map
(make-persistent-hashtrie :meta meta
:count (the uint (1- count))
:root new-root
:has-null has-null
:null-value nil)))))))
(defmethod map-count ((map persistent-hashtrie))
(declare (optimize (speed 3) (safety 0)))
(phm-count map))
;;; transient-hashtrie impl
(defun thm-do-assoc (map key val)
(declare (optimize (speed 3) (safety 0)))
(with-accessors ((has-null thm-has-null)
(null-value thm-null-value)
(count thm-count)
(leaf-flag thm-leaf-flag)
(edit thm-edit)
(root thm-root))
map
(if (not key)
(progn (setf null-value val)
(unless has-null
(incf count)
(setf has-null t)))
;; else
(progn
(setf (box-val leaf-flag) nil)
(let ((n (node-assoc-edit (or root *empty-hash-map-node*)
edit
0 (hash key) key val leaf-flag)))
(unless (equal n root)
(setf root n))
(when (eq (box-val leaf-flag) leaf-flag) (incf count))))))
map)
(defun thm-do-without (map key)
(declare (optimize (speed 3) (safety 0)))
(with-accessors ((has-null thm-has-null)
(null-value thm-null-value)
(count thm-count)
(leaf-flag thm-leaf-flag)
(root thm-root)
(edit thm-edit))
map
(if (not key)
(when has-null
(setf has-null nil)
(setf null-value nil)
(decf count))
(when root
(setf (box-val leaf-flag) nil)
(let ((n (node-without-edit root edit 0 (hash key) key leaf-flag)))
(unless (eq n root) (setf root n))
(when (eq (box-val leaf-flag) leaf-flag) (decf count))))))
map)
(defun thm-do-val-at (map key not-found)
(declare (optimize (speed 3) (safety 0)))
(with-accessors ((root thm-root)
(null-value thm-null-value)
(has-null thm-has-null))
map
(cond ((null key)
(if has-null
null-value
not-found))
((null root) not-found)
(t (node-find root 0 (hash key) key not-found)))))
(defun thm-ensure-editable (map)
(declare (optimize (speed 3) (safety 0)))
(unless (atomic-reference-val (thm-edit map))
(error "Transient used after persistent call")))
(defun thm-do-persistent (map)
(declare (optimize (speed 3) (safety 0)))
(with-accessors ((count thm-count)
(root thm-root)
(has-null thm-has-null)
(null-value thm-null-value)
(edit thm-edit))
map
(setf (atomic-reference-val edit) nil)
(make-persistent-hashtrie :count count :root root
:has-null has-null :null-value null-value)))
(defun thm-persistent (map)
(declare (optimize (speed 3) (safety 0)))
(thm-ensure-editable map)
(thm-do-persistent map))
(defun transient-map-assoc (map key value)
(declare (optimize (speed 3) (safety 0))
(type transient-hashtrie map))
(thm-ensure-editable map)
(thm-do-assoc map key value))
(defmethod map-without ((map transient-hashtrie) key)
(declare (optimize (speed 3) (safety 0)))
(thm-ensure-editable map)
(thm-do-without map key))
(defmethod map-val-at ((map transient-hashtrie) key &optional not-found)
(declare (optimize (speed 3) (safety 0)))
(thm-ensure-editable map)
(thm-do-val-at map key not-found))
(defmethod map-make-iterator ((map transient-hashtrie))
(declare (optimize (speed 3) (safety 0)))
(with-accessors ((root thm-root)
(has-null thm-has-null)
(null-value thm-null-value))
map
(let ((itr (if root (node-make-iterator root)
*empty-hash-iterator*)))
(declare (type (function ()) itr))
(if has-null
(let (returned-nil)
(lambda ()
(if returned-nil
(progn (setf returned-nil t)
(values t nil null-value))
(funcall itr))))
itr))))
(defmethod map-count ((map transient-hashtrie))
(declare (optimize (speed 3) (safety 0)))
(thm-count map))
;;; hash-map-array-node
(defun node-assoc-array-node (this shift hash key val added-leaf)
(declare (type fixnum shift)
(type uint hash)
(type hash-map-array-node this)
(optimize (speed 3) (safety 0)))
(with-accessors ((array hman-array)
(count hman-count))
this
(let* ((idx (mask hash shift))
(node (aref array idx)))
(declare (type uint idx)
(type (or null hash-map-node) node))
(if (null node)
(let ((new-node (node-assoc-bitmap-node *empty-hash-map-node*
(shift-right shift) hash key val added-leaf)))
(make-hash-map-array-node
:edit nil
:count (1+ count)
:array (clone-and-set1 array idx new-node)))
(let ((n (node-assoc node (shift-right shift) hash key val added-leaf)))
(if (eq n node)
this
(make-hash-map-array-node
:edit nil
:count count
:array (clone-and-set1 array idx n))))))))
(declaim (inline hman-ensure-editable))
(defun hman-ensure-editable (node edit)
(declare (optimize (speed 3) (safety 0)))
(if (eq (hman-edit node) edit)
node
(make-hash-map-array-node :edit edit
:count (hman-count node)
:array (copy-simple-array (hman-array node)))))
(declaim (inline hman-edit-and-set))
(defun hman-edit-and-set (node edit i n)
(declare (optimize (speed 3) (safety 0)))
(let ((editable (hman-ensure-editable node edit)))
(setf (aref (hman-array editable) i) n)
editable))
(defun node-assoc-edit-array-node (this edit shift hash key val added-leaf)
(declare (optimize (speed 3) (safety 0))
(type fixnum shift)
(type hash-map-array-node this))
(let* ((array (hman-array this))
(idx (mask hash shift))
(node (aref array idx)))
(declare (type uint idx)
(type (or null hash-map-node) node))
(if (null node)
(let* ((n (node-assoc-edit-bitmap-node *empty-hash-map-node* edit (shift-right shift) hash key val added-leaf))
(editable (hman-edit-and-set this edit idx n)))
(incf (hman-count editable))
editable)
(let ((n (node-assoc-edit node edit (shift-right shift) hash key val added-leaf)))
(declare (type hash-map-node n))
(if (eq n node)
this
(hman-edit-and-set this edit idx n))))))
(defun hman-pack (node edit idx)
(declare (optimize (speed 3) (safety 0))
(type uint idx))
(with-accessors ((count hman-count)
(array hman-array))
node
(let ((new-array (make-array (* 2 (1- count)) :initial-element nil))
(j 1)
(bitmap 0))
(declare (type uint bitmap))
(dotimes (i idx)
(declare (type uint i))
(when (aref array i)
(setf (aref new-array j) (aref array i))
(setf bitmap (logior bitmap (the uint (ash 1 i))))
(incf j 2)))
(loop for i from (1+ idx) below (cl:length array)
for v = (aref array i)
when v do
(setf (aref new-array j) v)
(setf bitmap (logior bitmap (the uint (ash 1 i))))
(incf j 2))
(make-hash-map-bitmap-node :edit edit :bitmap bitmap :array new-array))))
(defmethod node-without-edit ((this hash-map-array-node) edit shift hash key removed-leaf)
(declare (optimize (speed 3) (safety 0))
(type fixnum shift)
(type uint hash))
(with-accessors ((array hman-array)
(count hman-count))
this
(let* ((idx (mask hash shift))
(node (aref array idx)))
(if (null node)
this
(let ((n (node-without-edit node edit (shift-right shift) hash key removed-leaf)))
(if (eq n node)
this
(if (null n)
(if (<= count 8)
(hman-pack this edit idx)
(let ((editable (hman-edit-and-set this edit idx n)))
(decf (hman-count editable))
editable))
(hman-edit-and-set this edit idx n))))))))
(defmethod node-without ((this hash-map-array-node) shift hash key)
(declare (optimize (speed 3) (safety 0))
(type fixnum shift))
(with-accessors ((array hman-array)
(count hman-count))
this
(let* ((idx (mask hash shift))
(node (aref array idx)))
(if (null node)
this
(let ((n (node-without node (shift-right shift) hash key)))
(cond ((eq n node) this)
((null n)
(if (<= count 8)
(hman-pack this nil idx)
(make-hash-map-array-node
:edit nil
:count (1- count)
:array (clone-and-set1 array idx n))))
(t (make-hash-map-array-node
:edit nil
:count count
:array (clone-and-set1 array idx n)))))))))
(defmethod node-find ((this hash-map-array-node) shift hash key not-found)
(declare (optimize (speed 3) (safety 0))
(type fixnum shift))
(let* ((idx (mask hash shift))
(node (aref (hman-array this) idx)))
(if (null node)
not-found
(node-find node (shift-right shift) hash key not-found))))
(defmethod node-make-iterator ((node hash-map-array-node))
(declare (optimize (speed 3) (safety 0)))
(with-accessors ((array hman-array))
node
(let ((i 0)
nested-itr)
(declare (type uint i))
(lambda ()
(loop while t do
(cond (nested-itr
(multiple-value-bind (has-val key val)
(funcall (the (function ()) nested-itr))
(if has-val
(return (values has-val key val))
(progn (setf nested-itr nil)
(incf i)))))
((< i (cl:length array))
(let ((n (aref array i)))
(if n
(setf nested-itr (node-make-iterator n))
(incf i))))
(t (return (values nil nil nil)))))))))
;;; hash-map-bitmap-node
(defun hmn-ensure-editable (node edit)
(declare (optimize (speed 3) (safety 0)))
(with-accessors ((this-edit hmn-edit)
(bitmap hmn-bitmap)
(array hmn-array))
node
(if (eq edit this-edit)
node
(let* ((n (logcount bitmap))
(new-array (make-array (if (>= n 0) (* 2 (1+ n)) 4) :initial-element nil)))
(array-copy array 0 new-array 0 (* 2 n))
(make-hash-map-bitmap-node :edit edit :bitmap bitmap :array new-array)))))
(defun hmn-edit-and-set (node edit i a &optional j b)
(declare (optimize (speed 3) (safety 0)))
(let ((editable (hmn-ensure-editable node edit)))
(setf (aref (hmn-array editable) i) a)
(when j (setf (aref (hmn-array editable) j) b))
editable))
(defun hmn-edit-and-remove-pair (node edit bit i)
(declare (optimize (speed 3) (safety 0))
(type uint bit i))
(with-accessors ((bitmap hmn-bitmap))
node
(when (/= (the uint bitmap) bit)
(let* ((editable (hmn-ensure-editable node edit))
(array (hmn-array editable))
(array-len (cl:length array)))
(setf (hmn-bitmap editable) (logxor (hmn-bitmap editable) bit))
(let* ((new-len (* 2 (the uint (1+ i))))
(i2 (* 2 i))
(remaining (- array-len new-len)))
(declare (type uint i2 remaining new-len))
(array-copy array new-len array i2 remaining))
(setf (aref array (- array-len 2)) nil)
(setf (aref array (- array-len 1)) nil)
editable))))
(defun node-assoc-edit-bitmap-node (node edit shift hash key val added-leaf)
(declare (optimize (speed 3) (safety 0))
(type fixnum shift)
(type hash-map-bitmap-node node))
(let* ((bitmap (hmn-bitmap node))
(array (hmn-array node))
(bit (bitpos hash shift))
(2idx (* 2 (hmn-index node bit))))
(declare (type uint bit 2idx))
(if (/= 0 (logand bitmap bit))
(let ((key-or-null (aref array 2idx))
(value-or-node (aref array (1+ 2idx))))
(cond
((null key-or-null)
(let ((n (node-assoc-edit value-or-node edit (shift-right shift) hash key val added-leaf)))
(if (equal n value-or-node)
node
(hmn-edit-and-set node edit (shift-right shift) n))))
((equiv key key-or-null)
(if (equal val value-or-node)
node
(hmn-edit-and-set node edit (shift-right shift) val)))
(t
(setf (box-val added-leaf) added-leaf)
(hmn-edit-and-set node edit
2idx nil
(the fixnum (1+ 2idx))
(create-edit-node edit (shift-right shift) key-or-null value-or-node hash key val)))))
;; else
(let ((n (logcount bitmap)))
(cond
((< (* 2 n) (cl:length array))
(setf (box-val added-leaf) added-leaf)
(let* ((editable (hmn-ensure-editable node edit))
(array (hmn-array editable)))
(declare (type uint 2idx))
(array-copy array 2idx array
(the uint (+ 2 2idx))
(the uint (- (* 2 n) 2idx)))
(setf (aref array 2idx) key)
(setf (aref array (1+ 2idx)) val)
(setf (hmn-bitmap editable) (logior bit (hmn-bitmap editable)))
editable))
((>= n 16)
(let* ((nodes (make-array +size+ :initial-element nil))
(jdx (mask hash shift))
(j 0))
(setf (aref nodes jdx) (node-assoc-edit-bitmap-node *empty-hash-map-node* edit (shift-right shift) hash key val added-leaf))
(for-true-bits32 (mask bitmap)
(let ((i (mask32->position mask)))
(if (null (aref array j))
(setf (aref nodes i) (aref array (1+ j)))
(setf (aref nodes i) (node-assoc-edit-bitmap-node *empty-hash-map-node* edit (shift-right shift)
(hash (aref array j)) (aref array j) (aref array (1+ j)) added-leaf)))
(incf j 2)))
(make-hash-map-array-node :edit edit :count (1+ n) :array nodes)))
(t
(let ((new-array (make-array (* 2 (1+ n)) :initial-element nil)))
(array-copy array 0 new-array 0 2idx)
(setf (aref new-array 2idx) key)
(setf (box-val added-leaf) added-leaf)
(setf (aref new-array (1+ 2idx)) val)
(array-copy array 2idx new-array (the uint (+ 2 2idx)) (the uint (- (* 2 n) 2idx)))
(if (eq edit (hmn-edit node))
(progn
(setf (hmn-array node) new-array)
(setf (hmn-bitmap node) (logior (hmn-bitmap node) bit))
node)
(make-hash-map-bitmap-node :edit edit :bitmap bit :array new-array)))))))))
(defun node-assoc-bitmap-node (node shift hash key val added-leaf)
(declare (optimize (speed 3) (safety 0))
(type uint hash)
(type fixnum shift)
(type hash-map-bitmap-node node))
(let* ((bit (bitpos hash shift))
(idx (hmn-index node bit))
(bitmap (hmn-bitmap node))
(array (hmn-array node)))
(declare (type uint idx bit bitmap))
(if (/= 0 (logand bitmap bit))
(let ((key-or-null (aref array (the uint (* 2 idx))))
(value-or-node (aref array (the uint (1+ (* 2 idx))))))
(cond
((null key-or-null)
(let ((n (node-assoc value-or-node (shift-right shift) hash key val added-leaf)))
(if (equal n value-or-node)
node
(make-hash-map-bitmap-node :bitmap bitmap
:array (clone-and-set1 array (the uint (1+ (* 2 idx))) n)))))
((equiv key key-or-null)
(if (equal val value-or-node)
node
(make-hash-map-bitmap-node :bitmap bitmap
:array (clone-and-set1 array (the uint (1+ (* 2 idx))) val))))
(t
(setf (box-val added-leaf) added-leaf)
(make-hash-map-bitmap-node :bitmap bitmap
:array (clone-and-set2 array
(the uint (* 2 idx)) nil
(the uint (1+ (* 2 idx)))
(create-node (shift-right shift) key-or-null value-or-node hash key val))))))
;; else
(let ((n (logcount bitmap)))
(declare (type fixnum n))
(if (>= n 16)
(let* ((nodes (make-array +size+ :initial-element nil))
(jdx (mask hash shift))
(j 0))
(declare (type uint j jdx))
(setf (aref nodes jdx) (node-assoc-bitmap-node *empty-hash-map-node* (shift-right shift) hash key val added-leaf))
(for-true-bits32 (bit bitmap)
(let ((i (mask32->position bit)))
(if (null (aref array j))
(setf (aref nodes i) (aref array (1+ j)))
(setf (aref nodes i) (node-assoc-bitmap-node *empty-hash-map-node* (shift-right shift) (hash (aref array j)) (aref array j) (aref array (1+ j)) added-leaf)))
(incf j 2)))
(make-hash-map-array-node :count (1+ n) :array nodes))
;; else
(let ((new-array (make-array (* 2 (1+ n)) :initial-element nil)))
(array-copy array 0 new-array 0 (the uint (* 2 idx)))
(setf (aref new-array (* 2 idx)) key)
(setf (box-val added-leaf) added-leaf)
(setf (aref new-array (1+ (* 2 idx))) val)
(array-copy array (the uint (* 2 idx)) new-array (the uint (* 2 (1+ idx))) (the uint (* 2 (- n idx))))
(make-hash-map-bitmap-node :bitmap (logior bitmap bit) :array new-array)))))))
(defmethod node-find ((node hash-map-bitmap-node) shift hash key not-found)
(declare (optimize (speed 3) (safety 0))
(type fixnum shift))
(with-accessors ((bitmap hmn-bitmap)
(array hmn-array))
node
(let ((bit (bitpos hash shift)))
(declare (type uint bit))
(if (= (logand bitmap bit) 0)
not-found
(let* ((idx (hmn-index node bit))
(2idx (* 2 idx))
(key-or-null (aref array 2idx))
(val-or-node (aref array (1+ 2idx))))
(declare (type uint idx 2idx))
(cond ((not key-or-null) (node-find val-or-node (shift-right shift) hash key not-found))
((equiv key key-or-null) val-or-node)
(t not-found)))))))
(defmethod node-without-edit ((this hash-map-bitmap-node) edit shift hash key removed-leaf)
(declare (optimize (speed 3) (safety 0))
(type fixnum shift))
(with-accessors ((bitmap hmn-bitmap)
(array hmn-array))
this
(let ((bit (bitpos hash shift)))
(declare (type uint bit))
(if (= 0 (logand bitmap bit))
this
(let* ((idx (hmn-index this bit))
(2idx (* 2 idx))
(key-or-null (aref array 2idx))
(val-or-node (aref array (1+ 2idx))))
(declare (type uint idx 2idx)
(type hash-map-node val-or-node))
(cond
((null key-or-null)
(let ((n (node-without-edit val-or-node edit (shift-right shift) hash key removed-leaf)))
(cond
((eql n val-or-node) this)
(n (hmn-edit-and-set this edit (1+ 2idx) n))
((= bitmap bit) nil)
(t (hmn-edit-and-remove-pair this edit bit idx)))))
((equiv key key-or-null)
(setf (box-val removed-leaf) removed-leaf)
(hmn-edit-and-remove-pair this edit bit idx))
(t this)))))))
(defmethod node-without ((node hash-map-bitmap-node) shift hash key)
(declare (optimize (speed 3) (safety 0))
(type fixnum shift))
(with-accessors ((bitmap hmn-bitmap)
(array hmn-array))
node
(let ((bit (bitpos hash shift)))
(declare (type uint bit))
(if (= 0 (logand bitmap bit))
node
(let* ((idx (hmn-index node bit))
(2idx (* 2 idx))
(key-or-null (aref array 2idx))
(val-or-node (aref array (1+ 2idx))))
(declare (type uint idx 2idx))
(cond ((null key-or-null)
(let ((n (node-without val-or-node (shift-right shift) hash key)))
(cond ((eq n val-or-node) node)
(n (make-hash-map-bitmap-node
:edit nil
:bitmap bitmap
:array (clone-and-set1 array (1+ 2idx) n)))
((= bitmap bit) nil)
(t (make-hash-map-bitmap-node
:edit nil
:bitmap (logxor bitmap bit)
:array (remove-pair array idx))))))
((equiv key key-or-null)
(if (= bitmap bit) nil
(make-hash-map-bitmap-node
:edit nil
:bitmap (logxor bitmap bit)
:array (remove-pair array idx))))
(t node)))))))
(defun node-make-array-iterator (array)
(declare (optimize (speed 3) (safety 0))
(type (simple-array t (*)) array))
(let ((i 0)
nested-itr)
(declare (type uint i))
(lambda ()
(loop while t do
(cond (nested-itr
(multiple-value-bind (has-val key val)
(funcall (the (function ()) nested-itr))
(if has-val
(return (values has-val key val))
(setf nested-itr nil))))
((< i (cl:length array))
(let ((key (aref array i))
(val (aref array (1+ i))))
(incf i 2)
(cond (key (return (values t key val)))
(val (setf nested-itr (node-make-iterator val))))))
(t (return (values nil nil nil))))))))
(defmethod node-make-iterator ((node hash-map-bitmap-node))
(declare (optimize (speed 3) (safety 0)))
(node-make-array-iterator (hmn-array node)))
;; hash-collision-node
(defun hmcn-find-index (node key)
(declare (optimize (speed 3) (safety 0)))
(loop for i from 0 by 2
repeat (hmcn-count node)
when (equiv key (aref (hmcn-array node) i))
do (return-from hmcn-find-index i))
-1)
(defun node-assoc-collision-node (node shift hash key val added-leaf)
(declare (optimize (speed 3) (safety 0))
(type uint hash)
(type hash-map-collision-node node))
(with-accessors ((this-hash hmcn-hash)
(array hmcn-array)
(count hmcn-count)
(edit hmcn-edit))
node
(if (= hash this-hash)
(let ((idx (hmcn-find-index node key)))
(declare (type fixnum idx))
(if (/= idx -1)
(if (equal val (aref array (1+ idx)))
node
(make-hash-map-collision-node :edit nil :hash hash :count count
:array (clone-and-set1 array (1+ idx) val)))
(let ((new-array (make-array (* 2 (1+ count)) :initial-element nil)))
(array-copy array 0 new-array 0 (the uint (* 2 count)))
(setf (aref new-array (* 2 count)) key)
(setf (aref new-array (1+ (* 2 count))) val)
(setf (box-val added-leaf) added-leaf)
(make-hash-map-collision-node :edit edit :hash hash :count (1+ count) :array new-array))))
(node-assoc (make-hash-map-bitmap-node :bitmap (bitpos this-hash shift) :array (make-array 2 :initial-contents (list nil node)))
shift hash key val added-leaf))))
(defmethod node-without ((node hash-map-collision-node) shift hash key)
(declare (optimize (speed 3) (safety 0))
(type uint hash))
(let ((idx (hmcn-find-index node key)))
(declare (type fixnum idx))
(cond ((= idx -1) node)
((= (hmcn-count node) 1) nil)
(t (make-hash-map-collision-node :edit nil
:hash hash
:count (1- (hmcn-count node))
:array (remove-pair (hmcn-array node) (floor idx 2)))))))
(defun hmcn-ensure-editable (node edit)
(declare (optimize (speed 3) (safety 0)))
(with-accessors ((this-edit hmcn-edit)
(count hmcn-count)
(array hmcn-array)
(hash hmcn-hash))
node
(if (eq edit this-edit)
node
(let ((new-array (make-array (* 2 (1+ count)) :initial-element nil)))
(array-copy array 0 new-array 0 (the uint (* 2 count)))
(make-hash-map-collision-node :edit edit
:hash hash
:count count
:array new-array)))))
(defun hmcn-edit-and-set (node edit i a &optional j b)
(declare (optimize (speed 3) (safety 0)))
(let ((editable (hmcn-ensure-editable node edit)))
(setf (aref (hmcn-array editable) i) a)
(when j (setf (aref (hmcn-array editable) j) b))
editable))
(defun node-assoc-edit-collision-node (node edit shift hash key val added-leaf)
(declare (optimize (speed 3) (safety 0))
(type uint hash)
(type hash-map-collision-node node))
(with-accessors ((this-hash hmcn-hash)
(array hmcn-array)
(count hmcn-count))
node
(if (= hash this-hash)
(let ((idx (hmcn-find-index node key)))
(declare (type fixnum idx))
(cond ((/= idx -1)
(if (equal val (aref array (1+ idx)))
node
(hmcn-edit-and-set node edit (1+ idx) val)))
((> (cl:length array) (* 2 count))
(setf (box-val added-leaf) added-leaf)
(let* ((2count (* 2 count))
(editable (hmcn-edit-and-set node edit
2count key
(the uint (1+ 2count)) val)))
(declare (type uint 2count))
(incf (hmcn-count editable))
editable))))
(node-assoc-edit
(make-hash-map-bitmap-node :edit edit :bitmap (bitpos this-hash shift)
:array (make-array 4 :initial-contents (list nil node nil nil)))
edit shift hash key val added-leaf))))
(defmethod node-without-edit ((node hash-map-collision-node) edit shift hash key removed-leaf)
(declare (optimize (speed 3) (safety 0))
(type fixnum shift))
(let ((idx (hmcn-find-index node key))
(count (hmcn-count node)))
(declare (type uint count)
(type fixnum idx))
(if (= idx -1)
node
(progn
(setf (box-val removed-leaf) removed-leaf)
(unless (= 1 count)
(let* ((editable (hmcn-ensure-editable node edit))
(array (hmcn-array editable))
(2count (* 2 count))
(2idx (* 2 idx)))
(declare (type uint 2count))
(setf (aref array idx) (aref array (- 2count 2)))
(setf (aref array (1+ idx)) (aref array (1- 2count)))
(setf (aref array (- 2idx 2)) nil)
(setf (aref array (1- 2idx)) nil)
(decf (hmcn-count editable))
editable))))))
(defmethod node-find ((node hash-map-collision-node) shift hash key not-found)
(declare (optimize (speed 3) (safety 0))
(type fixnum shift))
(let ((idx (hmcn-find-index node key)))
(declare (type fixnum idx))
(if (< idx 0)
not-found
(aref (hmcn-array node) (1+ idx)))))
(defmethod node-make-iterator ((node hash-map-collision-node))
(node-make-array-iterator (hmcn-array node)))
;; Print
(defmethod print-object ((map persistent-hashtrie) stream)
(declare (optimize (speed 3) (safety 0))
(type stream stream))
(with-accessors ((count phm-count))
map
(write-char #\{ stream)
(loop with print-length = (and (not *print-readably*) *print-length*)
with itr of-type (function ()) = (map-make-iterator map)
for (remaining key val) = (multiple-value-list (funcall itr))
then (list nremaining nkey nval)
for (nremaining nkey nval) = (if remaining
(multiple-value-list (funcall itr))
(list nil nil nil))
then (multiple-value-list (funcall itr))
for cnt from 0
while remaining
when (and (numberp print-length) (>= cnt print-length))
do
(princ "..." stream)
(return)
end
do (prin1 key stream)
(write-char #\ stream)
(prin1 val stream)
(when nremaining (princ ", " stream)))
(write-char #\} stream)))
(defun map-assoc (map key value)
(declare (optimize (speed 3) (safety 0))
(type hashtrie map))
(typecase map
(persistent-hashtrie (persistent-map-assoc map key value))
(transient-hashtrie (transient-map-assoc map key value))))
(defun make-hashtrie (&rest args)
(declare (optimize (speed 3) (safety 0)))
(let ((r (phm-as-transient *empty-hash-map*)))
(loop for (key val) on args by #'cddr
do (setf r (map-assoc r key val)))
(thm-persistent r)))
(defun map-map (map fn)
(declare (optimize (speed 3) (safety 0))
(type hashtrie map)
(type function fn))
(loop with itr of-type (function ()) = (map-make-iterator map)
for (remaining key val) = (multiple-value-list (funcall itr))
while remaining collect (funcall fn key val)))
(defun map-reduce (map fn &optional start-val)
(declare (optimize (speed 3) (safety 0))
(type function fn)
(type hashtrie map))
(loop with itr of-type (function ()) = (map-make-iterator map)
for (remaining key val) = (multiple-value-list (funcall itr))
while remaining
for result = (funcall fn start-val key val)
then (funcall fn result key val)
finally (return result)))
| 34,172 | Common Lisp | .lisp | 919 | 32.232862 | 160 | 0.637608 | DanielKeogh/hashtrie | 8 | 0 | 1 | EPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 1c3886acf012865c47a62a4d461b8cfe27ca8ae65a4933873a9eadab68430196 | 12,187 | [
-1
] |
12,188 | utils.lisp | DanielKeogh_hashtrie/utils.lisp | ;;;; utils.lisp
(in-package #:hashtrie)
(eval-when (:compile-toplevel :load-toplevel :execute)
(deftype uint () '(unsigned-byte 32))
(declaim (type fixnum +bits+ +size+ +mask+))
(defconstant +bits+ 5)
(defconstant +size+ (expt 2 +bits+))
(defconstant +mask+ (1- +size+)))
(declaim (inline make-box))
(defun make-box ()
(declare (optimize (speed 3) (safety 0)))
(cons nil nil))
(defmacro box-val (b) `(car ,b))
(defmacro shift-right (i)
`(the fixnum (+ +bits+ ,i)))
(defstruct atomic-reference (val nil))
(declaim (inline hash))
(defun hash (x)
(declare (optimize (speed 3) (safety 0)))
(the uint (mod (sxhash x) 4294967296)))
(defmacro logandcount (n1 n2)
`(logcount (logand ,n1 ,n2)))
(declaim (inline equiv))
(defun equiv (v1 v2)
(declare (optimize (speed 3) (safety 0)))
(equal v1 v2))
(declaim (inline copy-simple-array))
(defun copy-simple-array (arr)
(declare (optimize (speed 3) (safety 0))
(type (simple-array t (*)) arr))
(copy-seq arr))
(defun array-copy (src src-pos dest dest-start length)
(declare (optimize (speed 3) (safety 0))
(type (simple-array t (*)) src dest)
(type fixnum src-pos dest-start length))
(loop for cnt fixnum from 0 below length
for src-index fixnum from src-pos
for dest-index fixnum from dest-start
do (setf (aref dest dest-index) (aref src src-index))))
(defun remove-pair (array i)
(declare (optimize (speed 3) (safety 0))
(type (simple-array t (*)) array)
(type fixnum i))
(let ((new-array (make-array (- (cl:length array) 2))))
(array-copy array 0 new-array 0 (the fixnum (* 2 i)))
(array-copy array (the fixnum (* 2 (1+ i))) new-array
(the fixnum (* 2 i))
(the fixnum (- (cl:length new-array) (* 2 i))))
new-array))
(defmacro for-true-bits32 ((mask-var int) &body body)
(let ((x (gensym)))
`(loop for ,x of-type (unsigned-byte 32) = ,int then (logand ,x (- ,x 1))
for ,mask-var = (logand ,x (- ,x))
while (> ,mask-var 0)
do (progn ,@body))))
(declaim (type (simple-array (integer 0 67) 1) *mask32->position-lookup*))
(defparameter *mask32->position-lookup*
(loop with lookup = (make-array 67 :element-type '(integer 0 67) :initial-element 0)
for m from 0 below 64
for i = 1 then (ash i 1)
do (setf (aref lookup (mod i 67)) m)
finally (return lookup)))
(declaim (inline mask32->position))
(defun mask32->position (mask)
(declare (optimize (speed 3) (safety 0))
(type (unsigned-byte 32) mask)
(type (simple-array (integer 0 67) 1) *mask32->position-lookup*))
(aref *mask32->position-lookup* (mod mask 67)))
| 2,656 | Common Lisp | .lisp | 68 | 34.955882 | 87 | 0.644253 | DanielKeogh/hashtrie | 8 | 0 | 1 | EPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 5074e02ceff54d8d9d19263c48b864deef7d71f0ab4e86a1920d214a71b34abc | 12,188 | [
-1
] |
12,189 | package.lisp | DanielKeogh_hashtrie/tests/package.lisp | ;;;; tests/package.lisp
(defpackage #:hashtrie-tests
(:use #:cl #:fiveam)
(:local-nicknames (#:htr #:hashtrie))
(:export #:run!
#:all-tests))
| 160 | Common Lisp | .lisp | 6 | 22.666667 | 40 | 0.605263 | DanielKeogh/hashtrie | 8 | 0 | 1 | EPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 258861052eba3563a60ab3f8b18bb25ea5bec47e23a2513d7e55f8a5adfc10ff | 12,189 | [
-1
] |
12,190 | main.lisp | DanielKeogh_hashtrie/tests/main.lisp | ;;;; tests/main.lisp
(in-package #:hashtrie-tests)
(def-suite all-tests
:description "Main test suite for hashtrie")
(in-suite all-tests)
(defun test-hashtrie ()
(run! 'all-tests))
(test make-hashtrie
(is (htr:hashtrie-p (htr:make-hashtrie)))
(is (htr:hashtrie-p (htr:make-hashtrie 1 1)))
(is (htr:hashtrie-p (htr:make-hashtrie "one" "one")))
(is (htr:hashtrie-p (htr:make-hashtrie nil "one"))))
(test value
(is (= 1 (htr:value (htr:make-hashtrie nil 1) nil)))
(is (= 1 (htr:value (htr:make-hashtrie 1 1) 1)))
(is (= 1 (htr:value (htr:make-hashtrie "boo" 1) "boo")))
(is (null (htr:value (htr:make-hashtrie "noo" 1) "boo"))))
(test add
(is (= 1 (htr:length (htr:add (htr:make-hashtrie) 1 1))))
(is (= 2 (htr:length (htr:add (htr:make-hashtrie 1 2) 2 2))))
(is (= 1 (htr:length (htr:add (htr:make-hashtrie 1 1) 1 2))))
(is (= 1 (htr:length (htr:add (htr:make-hashtrie 1 1) 1 2))))
(is (= 1 (htr:length (htr:add (htr:make-hashtrie) nil 2))))
(is (= 1000 (htr:length (loop with map = (htr:make-hashtrie)
for i from 1 to 1000
do (setf map (htr:add map i i))
finally (return map))))))
(test remove
(is (= 0 (htr:length (htr:remove (htr:make-hashtrie nil 1) nil))))
(is (= 0 (htr:length (htr:remove (htr:make-hashtrie 1 1) 1))))
(is (= 1 (htr:length (htr:remove (htr:make-hashtrie nil 1) 1)))))
(test has-key
(let ((map (htr:make-hashtrie)))
(dotimes (i 1000)
(setf map (htr:add map i i)))
(is (loop for i from 0 below 1000
always (htr:has-key map i)))))
(test has-key-not
(let ((map (htr:make-hashtrie)))
(dotimes (i 1000)
(setf map (htr:add map i i)))
(is (loop for i from 0 below 1000
always (= i (htr:value map i))))))
(test value
(let ((map (htr:make-hashtrie)))
(dotimes (i 1000)
(setf map (htr:add map i i)))
(is (loop for i from 0 below 1000
always (= i (htr:value map i))
do (setf map (htr:remove map i))
never (htr:value map i)))))
(test persistent
(let* ((map1 (htr:make-hashtrie 1 1 2 2 3 3))
(map2 (htr:remove map1 3))
(map3 (htr:add map1 4 4)))
(is (htr:has-key map1 1))
(is (htr:has-key map2 1))
(is (htr:has-key map3 1))
(is (htr:has-key map1 2))
(is (htr:has-key map2 2))
(is (htr:has-key map3 2))
(is (htr:has-key map1 3))
(is (null (htr:has-key map2 3)))
(is (htr:has-key map3 3))
(is (null (htr:has-key map1 4)))
(is (null (htr:has-key map2 4)))
(is (htr:has-key map3 4))))
(test add-remove-1000
(let ((map (htr:make-hashtrie)))
(dotimes (i 1000)
(setf map (htr:add map i i)))
(is (= 1000 (htr:length map)))
(dotimes (i 1000)
(setf map (htr:remove map i)))
(is (= 0 (htr:length map)))))
(test map
(let ((map (htr:make-hashtrie)))
(dotimes (i 1000)
(setf map (htr:add map i i)))))
(test with-transient-10
(let ((map (htr:with-transient (trans (htr:make-hashtrie))
(dotimes (i 10)
(htr:add trans i i)))))
(is (= 10 (htr:length map)))
(let ((map2 (htr:with-transient (trans map)
(dotimes (i 10)
(htr:remove trans i)))))
(is (= 10 (htr:length map)))
(is (= 0 (htr:length map2))))))
(test with-transient-1000
(let ((map (htr:with-transient (trans (htr:make-hashtrie))
(dotimes (i 1000)
(htr:add trans i i)))))
(is (= 1000 (htr:length map)))
(let ((map2 (htr:with-transient (trans map)
(dotimes (i 1000)
(htr:remove trans i)))))
(is (= 1000 (htr:length map)))
(is (= 0 (htr:length map2))))))
(test map-10
(let ((map (htr:with-transient (trans (htr:make-hashtrie))
(dotimes (i 10)
(htr:add trans i i)))))
(is (= (loop for i from 0 below 10 sum i)
(reduce (lambda (x y) (+ x y))
(htr:map map (lambda (key val) (declare (ignore key)) val)))))
(is (= (loop for i from 0 below 10 sum i)
(reduce (lambda (x y) (+ x y))
(htr:map map (lambda (key val) (declare (ignore val)) key)))))))
(test map-10-transient
(htr:with-transient (map (htr:make-hashtrie))
(dotimes (i 10)
(htr:add map i i))
(is (= (loop for i from 0 below 10 sum i)
(reduce (lambda (x y) (+ x y))
(htr:map map (lambda (key val) (declare (ignore key)) val)))))
(is (= (loop for i from 0 below 10 sum i)
(reduce (lambda (x y) (+ x y))
(htr:map map (lambda (key val) (declare (ignore val)) key)))))))
| 4,535 | Common Lisp | .lisp | 119 | 32.310924 | 70 | 0.576306 | DanielKeogh/hashtrie | 8 | 0 | 1 | EPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | ca5f22073d4479874d9cdd88dfb9b729d6dc3dcc43d36f95eb53f9e73cecf981 | 12,190 | [
-1
] |
12,191 | hashtrie.asd | DanielKeogh_hashtrie/hashtrie.asd | ;;;; hashtrie.asd
(asdf:defsystem #:hashtrie
:description "Persistent/Immutable Hash Trie datastructure based upon Clojure"
:author "Daniel Keogh"
:license "Eclipse 2.0"
:version "1.0.0"
:serial t
:components ((:file "package")
(:file "utils")
(:file "hashtrie")
(:file "api")))
| 324 | Common Lisp | .asd | 11 | 24.454545 | 80 | 0.634615 | DanielKeogh/hashtrie | 8 | 0 | 1 | EPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | d87e5ece37c351fa998efc47e467ba13a3826d23eec6f02ccf832741d9a21feb | 12,191 | [
-1
] |
12,192 | hashtrie-tests.asd | DanielKeogh_hashtrie/hashtrie-tests.asd | ;;;; hashtrie-tests.asd
(asdf:defsystem #:hashtrie-tests
:description "Tests for hashtrie"
:author "Daniel Keogh"
:license "Eclipse 2.0"
:depends-on (:hashtrie :fiveam)
:components ((:module "tests"
:serial t
:components ((:file "package")
(:file "main")))))
| 294 | Common Lisp | .asd | 10 | 25 | 36 | 0.64539 | DanielKeogh/hashtrie | 8 | 0 | 1 | EPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 0b2bda1def3878c2a4ad1e6dbbd6e5f74ac961502e1339d5a70aebc61e51bc34 | 12,192 | [
-1
] |
12,214 | sequence-iterator.lisp | alessiostalla_doplus/sequence-iterator.lisp | (in-package :doplus)
;;;;The following code is adapted from ABCL which in turn adapted it from SBCL.
;;;;Credit goes to the original authors!
;;;; iterator protocol
;;; The general protocol
(defgeneric make-sequence-iterator (sequence &key from-end start end)
(:method ((s sequence) &key from-end (start 0) end)
(multiple-value-bind (iterator limit from-end)
(make-simple-sequence-iterator
s :from-end from-end :start start :end end)
(values iterator limit from-end
#'iterator-step #'iterator-endp
#'iterator-element #'(setf iterator-element)
#'iterator-index #'iterator-copy)))
(:method ((s t) &key from-end start end)
(declare (ignore from-end start end))
(error 'type-error
:datum s
:expected-type 'sequence)))
;;; the simple protocol: the simple iterator returns three values,
;;; STATE, LIMIT and FROM-END.
;;; magic termination value for list :from-end t
(defvar *exhausted* (cons nil nil))
(defgeneric make-simple-sequence-iterator
(sequence &key from-end start end)
(:method ((s list) &key from-end (start 0) end)
(if from-end
(let* ((termination (if (= start 0) *exhausted* (nthcdr (1- start) s)))
(init (if (<= (or end (length s)) start)
termination
(if end (last s (- (length s) (1- end))) (last s)))))
(values init termination t))
(cond
((not end) (values (nthcdr start s) nil nil))
(t (let ((st (nthcdr start s)))
(values st (nthcdr (- end start) st) nil))))))
(:method ((s vector) &key from-end (start 0) end)
(let ((end (or end (length s))))
(if from-end
(values (1- end) (1- start) t)
(values start end nil))))
(:method ((s sequence) &key from-end (start 0) end)
(let ((end (or end (length s))))
(if from-end
(values (1- end) (1- start) from-end)
(values start end nil)))))
(defgeneric iterator-step (sequence iterator from-end)
(:method ((s list) iterator from-end)
(if from-end
(if (eq iterator s)
*exhausted*
(do* ((xs s (cdr xs)))
((eq (cdr xs) iterator) xs)))
(cdr iterator)))
(:method ((s vector) iterator from-end)
(if from-end
(1- iterator)
(1+ iterator)))
(:method ((s sequence) iterator from-end)
(if from-end
(1- iterator)
(1+ iterator))))
(defgeneric iterator-endp (sequence iterator limit from-end)
(:method ((s list) iterator limit from-end)
(eq iterator limit))
(:method ((s vector) iterator limit from-end)
(= iterator limit))
(:method ((s sequence) iterator limit from-end)
(= iterator limit)))
(defgeneric iterator-element (sequence iterator)
(:method ((s list) iterator)
(car iterator))
(:method ((s vector) iterator)
(aref s iterator))
(:method ((s sequence) iterator)
(elt s iterator)))
(defgeneric (setf iterator-element) (new-value sequence iterator)
(:method (o (s list) iterator)
(setf (car iterator) o))
(:method (o (s vector) iterator)
(setf (aref s iterator) o))
(:method (o (s sequence) iterator)
(setf (elt s iterator) o)))
(defgeneric iterator-index (sequence iterator)
(:method ((s list) iterator)
;; FIXME: this sucks. (In my defence, it is the equivalent of the
;; Apple implementation in Dylan...)
(loop for l on s for i from 0 when (eq l iterator) return i))
(:method ((s vector) iterator) iterator)
(:method ((s sequence) iterator) iterator))
(defgeneric iterator-copy (sequence iterator)
(:method ((s list) iterator) iterator)
(:method ((s vector) iterator) iterator)
(:method ((s sequence) iterator) iterator))
(defmacro with-sequence-iterator
((&rest vars) (s &rest args &key from-end start end) &body body)
(declare (ignore from-end start end))
`(multiple-value-bind (,@vars) (make-sequence-iterator ,s ,@args)
(declare (type function ,@(nthcdr 3 vars)))
,@body))
(defmacro with-sequence-iterator-functions
((step endp elt setf index copy)
(s &rest args &key from-end start end)
&body body)
(declare (ignore from-end start end))
(let ((nstate (gensym "STATE")) (nlimit (gensym "LIMIT"))
(nfrom-end (gensym "FROM-END-")) (nstep (gensym "STEP"))
(nendp (gensym "ENDP")) (nelt (gensym "ELT"))
(nsetf (gensym "SETF")) (nindex (gensym "INDEX"))
(ncopy (gensym "COPY")))
`(with-sequence-iterator
(,nstate ,nlimit ,nfrom-end ,nstep ,nendp ,nelt ,nsetf ,nindex ,ncopy)
(,s ,@args)
(flet ((,step () (setq ,nstate (funcall ,nstep ,s ,nstate ,nfrom-end)))
(,endp () (funcall ,nendp ,s ,nstate ,nlimit ,nfrom-end))
(,elt () (funcall ,nelt ,s ,nstate))
(,setf (new-value) (funcall ,nsetf new-value ,s ,nstate))
(,index () (funcall ,nindex ,s ,nstate))
(,copy () (funcall ,ncopy ,s ,nstate)))
(declare (truly-dynamic-extent #',step #',endp #',elt
#',setf #',index #',copy))
,@body))))
| 5,147 | Common Lisp | .lisp | 122 | 35.303279 | 79 | 0.606587 | alessiostalla/doplus | 8 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 105079464a966278701c836ffec15ceb6db2f532b636abc64405efb150815a95 | 12,214 | [
-1
] |
12,215 | tests.lisp | alessiostalla_doplus/tests.lisp | ;;; Copyright (C) 2011-2012 Alessio Stalla
;;;
;;; 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/>.
(defpackage :doplus-tests
(:use :cl :doplus :fiveam)
(:shadowing-import-from :doplus #:skip)
(:shadow #:run-all-tests)
(:export #:run-all-tests))
(in-package :doplus-tests)
(def-suite doplus-suite)
(in-suite doplus-suite)
(test test-collect
(is (equal '(5 15 25)
(do+ (for x (from 0 :to 30 :by 5))
(when (oddp x)
(collect x))))))
(test test-destructuring
(is (equal '(1 a 2 b 3 c) (do+ (for (x . y) (in '((1 . a) (2 . b) (3 . c))))
(collect x)
(collect y))))
(is (equal '((1 a nil nil k2 k3) (2 y nil nil k2 k3) (3 c (:k1 a :kk b :k2 c) a c b))
(do+ (for (x &optional (y 'y) &rest z &key k1 (k2 'k2) ((:kk k3) 'k3))
(in '((1 a) (2) (3 c :k1 a :kk b :k2 c))))
(collect (list x y z k1 k2 k3))))))
(test test-in-list
(is (null (do+ (for x (in-list ())) (collect x))))
(is (equal '(1 2 3) (do+ (for x (in-list '(1 2 3))) (collect x))))
(is (equal '(1 2 3) (do+ (for x (in-list '(1 a 2 b 3 c) :by #'cddr)) (collect x))))
(is (equal '((1 2 3) (2 3) (3)) (do+ (for _ (in-list '(1 2 3) :rest x)) (collect x))))
(is (equal '(1 a 2 b 3 c) (do+ (for (x . y) (in-list '((1 . a) (2 . b) (3 . c))))
(collect x)
(collect y)))))
(test test-in-vector
;;across expands to in-vector
(is (null (do+ (for x (across #())) (collect x))))
(is (equal '(1 2 3) (do+ (for x (across #(1 2 3))) (collect x))))
(is (null (do+ (for x (across #(3 2 1) :start 2 :end 0)) (collect x))))
(is (equal '(1 2 3) (do+ (for x (across #(3 2 1) :start 2 :end 0 :by -1)) (collect x))))
(is (equal '(1 2 3)
(do+ (for x (across #(0 1 a 2 b 3 c) :by 2 :start 1))
(collect x))))
(is (equal '(1 2 3)
(do+ (for x (across #(0 1 a 2 b 3 c 4) :by 2 :start 1 :end 6))
(collect x))))
(is (equal '(1 2 3 4)
(do+ (for x (across #(0 1 a 2 b 3 c 4) :by 2 :start 1 :end 7))
(collect x)))))
(test test-list-tails
(is (equal '(1 2 3 4) (do+ (for x (list-tails '(1 a 2 b 3 c 4 d) :by #'cddr))
(collect (car x))))))
(test test-hash-entries
(let ((ht (make-hash-table)))
(setf (gethash 'a ht) 'b)
(setf (gethash 3 ht) 4)
(is (equal '((a . b) (3 . 4))
(sort
(do+ (for (k v) (hash-entries-of ht))
(collect (cons k v)))
(lambda (x1 x2)
(declare (ignore x2))
(symbolp (car x1))))))))
(test test-summing
(is (equal '(12 7)
(do+ (for x (from 0 :to 10))
(summing-to total)
(finding max (maximizing x))
(returning (list total max))
(stop-when (eql x 8))
(when (evenp x)
(sum x :to total))))))
(test test-previous
(is (equal '((1 nil nil) (2 1 nil) (3 2 1) (4 3 2))
(do+ (for x (in '(1 2 3 4)))
(for y (previous x))
(for z (previous y))
(collect (list x y z)))))
(is (equal '((1 nil nil) (2 1 nil) (3 2 1) (4 3 2))
(do+ (for x (in '(1 2 3 4)))
(for z (previous y))
(for y (previous x))
(collect (list x y z))))))
(test test-nesting
"Tests nesting and accumulator sharing"
(is (equal
'((1 A) (1 B) (2 A) (2 B) (3 A) (3 B) (1 A) (1 B) (2 A) (2 B) (3 A) (3 B))
(do+ (accumulating-to foo)
(stop-when (> (length foo) 10))
(returning foo)
(do+ (for x (in '(1 2 3)))
(do+ (for y (in '(a b)))
(collect (list x y) :into foo))))))
(is (equal
'((0) (0 1) (0 1 2))
(do+ (generating x (from 0 :to 3))
(collect (do+ (for y (to x))
(collect y)
(when (= x y)
(update x))))))))
(test test-terminate
(is (equal 1 (do+ (returning 1) (terminate))))
(is (equal 1 (do+ (with (x 1)) (terminate nil x)))))
(test test-named-loop
"Tests nested named loops"
;;Test old-style name
(is (equal
3
(do+ outer-loop
(do+ inner-loop
(do+ (terminate outer-loop 3))))))
;;Test options :name
(is (equal
3
(do+ (options :name outer-loop)
(do+ (options :name inner-loop)
(do+ (terminate outer-loop 3)))))))
(test test-atomic-updates
(is (equal
(do+ (for x (across #(1 2 3 4) :index index))
(for k (in '(a b c d e)))
(returning (list x k :index index)))
(do+ (for k (in '(a b c d e)))
(for x (across #(1 2 3 4) :index index))
(returning (list x k :index index)))))
(is (not (equal
(do+ (options :atomic-updates nil)
(for x (across #(1 2 3 4) :index index))
(for k (in '(a b c d e)))
(returning (list x k :index index)))
(do+ (options :atomic-updates nil)
(for k (in '(a b c d e)))
(for x (across #(1 2 3 4) :index index))
(returning (list x k :index index)))))))
(test monster-test
(let ((*standard-output* (make-broadcast-stream)))
(is (equal '(X 7 Y 42 Z NIL K 7 M 15 W (1 3 5) P -9 LOOPS 3 MAX-LENGTH 3 LONGEST-LIST (4 5 6))
(do+ (for x (in '(1 3 5 7 9)))
(for k (from 10 :to 0))
(initially (format t "initially k = ~S~%" k))
(for m (to 100 :by 5))
(initially (format t "another init form~%"))
(with (y 42) z)
(stop-when (eql x 7))
(counting loops)
(finally (format t "finally k = ~S~%" k))
(accumulating-to w)
(accumulating-to p :initially 0 :by #'+ :finally #'-)
(returning (list 'x x 'y y 'z z 'k k 'm m 'w w 'p p
'loops loops 'max-length max-length 'longest-list longest-list))
(finally (format t "another final form~%"))
(finding max-x (maximizing x))
(for list (in '((1 2) (3) (4 5 6) (7 8) (9))))
(finding max-length (maximizing (length list) :saving list :in longest-list))
(let ((foo "look ma, body is nested!"))
(declare (ignore foo))
(format t "~%loop no. ~A~%" loops)
(format t "before collect, x ~A y ~A z ~A k ~A m ~A w ~A ~% list ~A max-length ~A longest-list ~A ~%"
x y z k m w list max-length longest-list)
(collect x :into w)
(collect x :into p)
(format t "after collect, x ~A y ~A z ~A k ~A m ~A w ~A ~% list ~A max-length ~A longest-list ~A ~%"
x y z k m w list max-length longest-list)))))))
(test test-generators-1
(is (equal '((0 0) (1 0) (2 1) (3 1))
(do+ (for x (from 0))
(generating y (across #(0 1)))
(collect (list x y))
(when (oddp x)
(is (= (update y) y)))))))
(test test-generators-2
(is (equal '((0 0) (1 0) (2 1) (3 1) (4 1) (5 1))
(do+ (for x (to 5))
(generating y (in #(0 1)))
(collect (list x y))
(when (oddp x)
(is (eql (try-update y) y)))))))
(test test-generators-3
(let (error)
(is (equal '((0 0) (1 0) (2 1) (3 1) (4 1) (5 1))
(do+ (for x (to 5))
(generating y (in #(0 1)))
(collect (list x y))
(when (oddp x)
(is (eql (try-update y :on-error (lambda (value cond) (setf error cond) value)) y)))
(when error
(multiple-value-bind (value success?) (try-update y)
(is (eql value y))
(is (null success?)))))))
(is (not (null error)))))
(test test-skip
(is (null (do+ (for x (from 0 :to 3)) (skip) (collect x)))))
(test test-macrolet
(is (equal '(1 2 3 4)
(macrolet ((among (&rest args) `(in ,@args))
(pick (it) `(collect ,it :into foo)))
(do+ (for x (among '(1 2 3 4)))
(accumulating-to-and-returning foo)
(pick x))))))
(test test-in
(is (equal '(3 . B)
(do+ (for y (in #(A B C D) :from-end t))
(for x (in '(1 2 3)))
(returning (cons x y)))))
(is (equal '((2 . 1) (4 . 3))
(do+ (for (a b) (in '((1 2) (3 4))))
(collect (cons b a)))))
(is (equal '((2 . 1) (4 . 3))
(do+ (for (a b) (in #((1 2) (3 4))))
(collect (cons b a))))))
(test test-package-iterator
(is (equal 'absolutely-truly-the-symbol-with-the-longest-name-in-this-package-even-longer-than-symbols-generated-by-the-test-framework
(do+ (for s (symbols-in :doplus-tests :internal))
(for l (maximizing (length (symbol-name s))
:saving s :in symbol-with-longest-name))
(returning symbol-with-longest-name)))))
(test test-being
(is (equal '(2 4 8 16 32 64)
(do+ (for x (being 2 :then (* x 2)))
(stop-when (> x 100))
(collect x)))))
(test test-multiple-accumulations
(is (equal '(1 2 2 4)
(do+ (for x (in '(1 2)))
(for y (collecting-into-and-returning list))
(collect x :into list)
(collect (* 2 x) :into list)))))
(test test-multiple-returns
(is (equal '(1 2 3 4 5 6 7)
(multiple-value-list
(do+ (returning 1) (returning 2 3)
(returning (values 4 5) 6) (returning 7)
(terminate))))))
(defun run-all-tests ()
(run! 'doplus-suite))
| 10,897 | Common Lisp | .lisp | 244 | 32.659836 | 136 | 0.462965 | alessiostalla/doplus | 8 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 782b853fe40a7f9955163d293ac8ab8f32fac38d9c7759bf3ce81123b55c72e8 | 12,215 | [
-1
] |
12,216 | fset.lisp | alessiostalla_doplus/fset.lisp | ;;; Copyright (C) 2011 Alessio Stalla
;;;
;;; 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/>.
(in-package :doplus)
(defstruct (fset-iterator (:constructor %make-fset-iterator)
(:conc-name #.(string '#:%fset-iterator-)))
function index element endp)
(defun make-fset-iterator (iterator-function)
(multiple-value-bind (elt not-done)
(funcall iterator-function :get)
(%make-fset-iterator :function iterator-function :index 0
:element elt :endp (not not-done))))
(defun fset-iterator-step (seq iter from-end)
(declare (ignore seq from-end))
(multiple-value-bind (elt not-done)
(funcall (%fset-iterator-function iter) :get)
(setf (%fset-iterator-element iter) elt
(%fset-iterator-endp iter) (not not-done))
(incf (%fset-iterator-index iter)))
iter)
(defun fset-iterator-endp (seq iter limit from-end)
(declare (ignore seq limit from-end))
(%fset-iterator-endp iter))
(defun fset-iterator-element (seq iter)
(declare (ignore seq))
(%fset-iterator-element iter))
(defun fset-iterator-index (seq iter)
(declare (ignore seq))
(%fset-iterator-index iter))
(defun (setf fset-iterator-element) (new-value seq iter)
(declare (ignore new-value seq iter))
(error "FSet collections are immutable"))
(defun fset-iterator-copy (seq iter)
(declare (ignore seq iter))
(error "FSet iterators cannot be copied"))
(defmethod make-sequence-iterator ((sequence fset:seq) &key from-end start end)
(when (or from-end start end)
(error "Not implemented"))
(let ((iterator (make-fset-iterator (fset:iterator sequence))))
(values iterator nil nil ;;limit from-end
#'fset-iterator-step #'fset-iterator-endp
#'fset-iterator-element #'(setf fset-iterator-element)
#'fset-iterator-index #'fset-iterator-copy))) | 2,461 | Common Lisp | .lisp | 54 | 41.277778 | 79 | 0.704337 | alessiostalla/doplus | 8 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 26a17cdb840046eb6807ac1db236164412a2fd430a94f6a1d5f3a09f721b4e9f | 12,216 | [
-1
] |
12,217 | doplus.lisp | alessiostalla_doplus/doplus.lisp | ;;; Copyright (C) 2011-2014 Alessio Stalla
;;;
;;; 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/>.
(in-package :doplus)
(defstruct generator name clauses)
(defstruct termination condition)
(defstruct result form)
(defstruct (binding (:constructor %make-binding)) var default default-provided?)
(defstruct declaration form)
(defstruct initialization form)
(defstruct step form)
(defstruct finalization form)
(defstruct accumulator var function)
(defstruct prologue form)
(defstruct epilogue form)
(defstruct wrapper function)
(defstruct options map)
(defun make-binding (var &key (default nil default-provided?))
(%make-binding :var var :default default :default-provided? default-provided?))
(defvar *iteration-variable*)
(defun make-iteration (&key bindings initializations steps preconditions postconditions)
"General iteration clause generator."
`(,@(mapcar (lambda (binding) `(with ,binding)) bindings)
,@(mapcar (lambda (precondition)
(make-initialization :form `(unless ,precondition (terminate))))
preconditions)
,@(mapcar (lambda (initialization)
(make-initialization :form initialization))
initializations)
,@(mapcar (lambda (postcondition)
(make-initialization :form `(unless ,postcondition (terminate))))
postconditions)
,@(mapcar (lambda (precondition)
(make-step :form `(unless ,precondition (terminate))))
preconditions)
,@(mapcar (lambda (step)
(make-step :form step))
steps)
,@(mapcar (lambda (postcondition)
(make-step :form `(unless ,postcondition (terminate))))
postconditions)))
(defun make-simple-iteration (&key (var *iteration-variable*) init (step nil step-p)
precondition postcondition)
"Specialized iteration clause generator, where the iteration clause refers to a single variable, possibly with an initial value, step form, precondition, or postcondition."
(unless var
(error "var is required"))
(make-iteration :bindings (list var) :initializations (when init `((setf ,var ,init)))
:steps (when step-p `((setf ,var ,step)))
:preconditions (when precondition (list precondition))
:postconditions (when postcondition (list postcondition))))
(defvar *clauses* nil "A list of known symbols that name clause macros, useful for introspection and documentation purposes.")
(defmacro defclause (name arglist &body body)
"Same as cl:defmacro, but additionally records <name> in *clauses* as a known clause macro."
`(progn
(defmacro ,name ,arglist ,@body)
(pushnew ',name *clauses*)))
(defclause declaring (thing)
"Causes the emission of a (declare <thing>) form in the declaration section of the loop."
(make-declaration :form thing))
(defclause for (var-or-vars iteration &environment env)
"General iteration clause. Its actual behaviour is controlled by ITERATION, a macro form that FOR expands with *ITERATION-VARIABLE* bound to VAR. Example: in (for x (in '(1 2 3))), IN is a macro that expands into clauses that make use of *ITERATION-VARIABLE*, which is bound to the symbol X in the example. For certain iteration macros, VAR can be a lambda-list as well, in which case destructuring is applied. Example: (for (x &optional y) (in-list '((1 2) (3))))."
(let ((*iteration-variable* var-or-vars))
(macroexpand iteration env)))
(defclause generating (var iteration)
"Lazy version of FOR. The user must call UPDATE or TRY-UPDATE in the body of the DO+ form in order to compute new values for the variable(s). Initialization, instead, is *always* performed eagerly."
(make-generator :name (if (symbolp var) var (extract-variables var))
:clauses `(for ,var ,iteration)))
(defclause finding (var condition)
"Same as FOR, but perhaps nicer to read when used in conjunction with macros like MAXIMIZING."
`(for ,var ,condition))
(defclause being (form &key (then form))
"Assigns to the iteration variable a value computed by evaluating FORM on each iteration, including the first. Optionally, the variable can be updated evaluating a differen form (the value of the `then' parameter). Examples: (for x (being (random))), (for y (being 'quiet :then (if (> x 0.5) 'angry 'quiet)))."
(make-simple-iteration :init form :step then))
(eval-when (:load-toplevel :compile-toplevel :execute)
(defun ensure-list (obj)
"(if (listp obj) obj (list obj))"
(if (listp obj) obj (list obj)))
(defun expand-with-simple-destructuring (form env)
"Expand `form' in `env' as an iteration form that assigns to `*iteration-variable*' destructuring as by `destructuring-bind'."
(let* ((lambda-list *iteration-variable*)
(variables (extract-variables lambda-list))
(*iteration-variable* (gensym "VAR"))
(assignment-form `(with-atomic-updates* ,variables
,(make-destructuring-form lambda-list *iteration-variable*))))
(list*
(macroexpand form env)
(make-initialization :form assignment-form)
(make-step :form assignment-form)
(mapcar (lambda (var) (make-binding var)) variables)))))
(defclause in (&whole form seq &rest args &key &allow-other-keys &environment env)
"Iterates over a sequence. IN must be used in combination with FOR, GENERATING and similar macros (those that bind *ITERATION-VARIABLE*). In implementations with extensible sequences (currently ABCL and SBCL), native sequence iterators are used, and all sequence types are supported, not just lists and vectors. In other implementations, an iterator specialized for lists or vectors is used depending on the type of sequence. All `args` are passed down to make-sequence-iterator (see the extensible sequences API paper for details [Rhodes2007]). IN can perform destructuring."
(if (symbolp *iteration-variable*)
(let ((state (gensym "STATE")) (limit (gensym "LIMIT"))
(from-end (gensym "FROM-END")) (step (gensym "STEP"))
(endp (gensym "ENDP")) (elt (gensym "ELT"))
(sequence (gensym "SEQUENCE")))
`((with (,sequence ,seq) ,state ,limit ,from-end ,step ,endp ,elt)
(initially (multiple-value-setq (,state ,limit ,from-end ,step ,endp ,elt)
(make-sequence-iterator ,sequence ,@args)))
,(make-step :form `(setf ,state (funcall ,step ,sequence ,state ,from-end)))
,(make-simple-iteration
:precondition `(not (funcall ,endp ,sequence ,state ,limit ,from-end))
:init `(funcall ,elt ,sequence ,state)
:step `(funcall ,elt ,sequence ,state))))
(expand-with-simple-destructuring form env)))
(defclause in-list
(&whole form list &key (by '(function cdr)) (rest (gensym "REST")) &environment env)
"Like IN, but specialized for lists. Successive lists are obtained by calling the function BY (which by default is #'CDR) on the previous list. REST, if specified, is the variable holding the remaining elements to be processed; REST initially is bound to the entire list, then to successive lists obtained by funcalling BY."
(if (symbolp *iteration-variable*)
(list
(make-simple-iteration :var rest :init list :step `(funcall ,by ,rest))
(make-simple-iteration :init `(car ,rest) :step `(car ,rest)
:precondition `(not (null ,rest))))
(expand-with-simple-destructuring form env)))
(defclause list-tails
(&whole form list &key (by '(function cdr)) &environment env)
"Loops over the successive tails of a list, checking for the end of the list as if by ATOM. Can perform destructuring."
(if (symbolp *iteration-variable*)
(let ((g (gensym)))
(list
(make-simple-iteration :var *iteration-variable* :init list :step `(funcall ,by ,*iteration-variable*))
(make-simple-iteration :var g :init nil :step nil
:precondition `(not (atom ,*iteration-variable*)))))
(expand-with-simple-destructuring form env)))
(defclause in-vector (vector &key (index (gensym "INDEX")) (start 0) end (by +1))
"Loops across a vector. INDEX is bound to the index of the current element in the vector. The vector is traversed starting from index START (0 by default) to index END (the end of the vector if not specified); the index is incremented by BY (1 by default) on each iteration."
;;From a contribution by Tamas Papp
(let ((tmp-var (gensym "VECTOR")))
`((with (,tmp-var ,vector) (,index 0))
(declaring (type (integer 0 ,(1- array-total-size-limit)) ,index))
(for ,index (from ,start :to ,(or end `(1- (length ,tmp-var))) :by ,by))
(for ,*iteration-variable* (being (aref ,tmp-var ,index))))))
(defclause across (vector &rest args &key index start end by)
"Synonym for in-vector."
(declare (ignore index start end by))
`(in-vector ,vector ,@args))
(defclause hash-entries-of (hash-table)
"Iterates over the entries of a hash table. The iteration variables must be specified as (key value), for example: (for (lemma definitions) (hash-entries-of the-english-vocabulary))."
(unless (and (listp *iteration-variable*) (= 2 (length *iteration-variable*)))
(error "Invalid variable specification for hash-entry, expected (key value) but got ~S" *iteration-variable*))
(let ((iterator (gensym "HASH-TABLE-ITERATOR")) (test (gensym "TEST"))
(key (car *iteration-variable*)) (value (cadr *iteration-variable*)))
`(,(make-wrapper :function (lambda (body)
`(with-hash-table-iterator (,iterator ,hash-table) ,body)))
,(make-iteration
:bindings (list test key value)
:initializations `((setf (values ,test ,key ,value) (,iterator)))
:steps `((setf (values ,test ,key ,value) (,iterator)))
:postconditions `((not (null ,test)))))))
(defclause symbols-in (package-or-packages &rest symbol-types)
"Iterates over the symbols in one or more packages. Symbol-types follows the specification of cl:with-package-iterator."
(let ((variables (ensure-list *iteration-variable*))
(package-list (ensure-list package-or-packages))
(symbol-types (or symbol-types '(:external)))
(iterator (gensym "PACKAGE-ITERATOR")) (test (gensym "TEST")))
(unless (<= 1 (length variables) 3)
(error "Invalid variable specification for package entry, expected (symbol &optional accessibility package) but got ~S" *iteration-variable*))
`(,(make-wrapper
:function
(lambda (body)
`(with-package-iterator (,iterator (list ,@package-list) ,@symbol-types)
,body)))
,(make-iteration
:bindings `(,test ,@variables)
:initializations `((setf (values ,test ,@variables) (,iterator)))
:steps `((setf (values ,test ,@variables) (,iterator)))
:postconditions `((not (null ,test)))))))
(defclause from (initial-value &key to by while (using ''+))
"Iterates from a given initial value to an optional maximum. Every iteration increments/decrements the value applying the <using> function (by default +) to the previous value and <by> (by default 1 or -1, depending on whether to >= from or not). Similarly, the <while> function is used to determine if <to> has been reached or surpassed. <while> is a function of two arguments, the current value and the value of <to>, and as soon as it returns false, the loop is terminated. <while> defaults to a function that returns true only if <to> has been specified and, letting cur be the current value, (<= (min to from) cur (max to from))."
(let* ((diff (gensym "FROM-DIFF")) (to-evaled (gensym "FROM-TO"))
(initial-evaled (gensym "FROM-FROM"))
(while (or while
(when to
`(lambda (cur to &aux (from ,initial-evaled))
(let ((max (max to from)) (min (min to from)))
(<= min cur max)))))))
(list
(make-simple-iteration :var to-evaled :init to)
(make-simple-iteration :var initial-evaled :init initial-value)
(make-simple-iteration
:var diff
:init (if by by
`(if ,to-evaled
(let ((signum (signum (- ,to-evaled ,initial-evaled))))
(if (zerop signum) +1 signum))
+1)))
(make-initialization
:form `(when (and ,to-evaled (not (zerop (- ,to-evaled ,initial-evaled)))
(not (= (signum (- ,to-evaled ,initial-evaled))
(signum ,diff))))
(terminate)))
(make-simple-iteration
:init initial-evaled
:step `(funcall ,using ,*iteration-variable* ,diff)
:postcondition (when while
`(funcall ,while ,*iteration-variable* ,to-evaled))))))
(defclause to (final-value &key (from 0) by while using)
"Variation over from."
`(from ,from :to ,final-value :by ,by
,@(when while `(:while ,while))
,@(when using `(:using ,using))))
(defclause previous (expr)
"On every iteration, the for-variable is set to the value <expr> had at the end of the previous iteration (initially NIL)."
(let ((tmp (gensym (format nil "~A-~A" '#:previous expr))))
(list
(make-simple-iteration :step tmp)
(make-simple-iteration :var tmp)
(make-epilogue :form `(setf ,tmp ,expr)))))
(defclause with (&rest bindings)
"Establishes bindings which are in effect for the whole loop."
(mapcar (lambda (binding)
(if (listp binding)
(make-binding (car binding) :default (cadr binding))
(make-binding binding)))
bindings))
(defclause until (condition)
"Specifies a termination clause for the loop. When, at the beginning of an iteration, the clause evaluates to true, the loop stops."
(make-termination :condition condition))
(defclause while (condition)
"Same as (until (not <condition>))."
(make-termination :condition `(not ,condition)))
(defclause stop-when (condition)
"Synonym for until."
`(until ,condition))
(defclause returning (&rest forms)
"Returns each form in <forms> as the value of the do+ form when the loop ends. If multiple forms are specified, by one or more RETURNING clauses, multiple values are returned, in the order the corresponding forms appear lexically. If one of the <forms> is (cl:values ...), then each value will be returned as if the values were spelled as direct arguments of the RETURNING form."
(let (result-clauses)
(dolist (form forms)
(if (and (listp form) (eq 'values (car form)))
(dolist (form (cdr form))
(push (make-result :form form) result-clauses))
(push (make-result :form form) result-clauses)))
(nreverse result-clauses)))
(defclause initially (&rest forms)
"Evaluates <form> before the first iteration."
(mapcar (lambda (form) (make-initialization :form form)) forms))
(defclause finally (&rest forms)
"Evaluates <form> after the last iteration, before returning a value."
(mapcar (lambda (form) (make-finalization :form form)) forms))
(defclause accumulating-to (vars &key initially by finally)
"Specifies an accumulation clause. Refer to the manual for details."
(labels ((make-finally-form (var function)
`(setf ,var (funcall ,function ,var)))
(make-one-accumulation (var)
(cons (make-simple-iteration :var var :init initially)
(if by
(list*
(make-accumulator :var var :function by)
(when finally
(list (make-finalization :form (make-finally-form var finally)))))
(list
(make-accumulator :var var :function '(function cons))
(make-finalization
:form (make-finally-form var (or finally '(function nreverse)))))))))
(mapcan #'make-one-accumulation (ensure-list vars))))
(defclause collecting-into (vars &rest args &key initially by finally)
"Synonym for accumulating-to."
(declare (ignore initially by finally))
`(accumulating-to ,vars ,@args))
;;TODO maybe retain keys but different defaults?
(defclause summing-to (vars &optional result-processor)
"Specifies an accumulation strategy with 0 as the default value and + as the accumulator function."
`(accumulating-to ,vars :initially 0 :by #'+ :finally ,result-processor))
(defclause collecting-into-and-returning (vars &rest args &key initially by finally)
"Same as collecting-into, but also returns the value of each <vars> at the end of the loop."
(declare (ignore initially by finally))
`((collecting-into ,vars ,@args)
,@(mapcar (lambda (var) `(returning ,var)) (ensure-list vars))))
(defclause accumulating-to-and-returning (vars &rest args &key initially by finally)
"Same as accumulating-into, but also returns the value of each <vars> at the end of the loop."
(declare (ignore initially by finally))
`((accumulating-to ,vars ,@args)
,@(mapcar (lambda (var) `(returning ,var)) (ensure-list vars))))
(defclause summing-to-and-returning (vars &optional result-processor)
"Same as summing-to, but also returns the value of each <vars> at the end of the loop."
`((summing-to ,vars ,result-processor)
,@(mapcar (lambda (var) `(returning ,var)) (ensure-list vars))))
(defclause counting (var)
"Counts the number of iterations, starting from 0."
(make-simple-iteration :var var :init 0 :step `(1+ ,var)))
(defclause maximizing (form &key (test ''>) saving in)
"Synonym for optimizing."
`(optimizing ,form :test ,test :saving ,saving :in ,in))
(defclause minimizing (form &key (test ''<) saving in)
"Same as optimizing but with < as the default test."
`(optimizing ,form :test ,test :saving ,saving :in ,in))
(defclause optimizing (form &key (test ''>) saving in)
"Finds the optimum value of an expression across the iteration. Refer to the manual for details."
(let* ((candidate (gensym "CANDIDATE-MAX"))
(test-form `(funcall ,test ,candidate ,*iteration-variable*))
(saving (ensure-list saving))
(in (ensure-list in)))
(when (not (= (length saving) (length in)))
(error ":saving and :in have different lengths!"))
(list*
(make-simple-iteration :init form)
(make-epilogue :form `(let ((,candidate ,form))
(when ,test-form
(setf ,*iteration-variable* ,candidate
,@(loop
:for x :in saving :for y :in in
:collect y :collect x)))))
(loop
:for x :in saving :for y :in in
:collect (make-simple-iteration :var y :init x)))))
(defclause options (&rest args &key name atomic-updates)
(declare (ignore name atomic-updates))
(make-options :map args))
(defmacro with-atomic-updates* ((&rest variables) binding-form &body body)
(let ((temps (mapcar (lambda (var) (list (gensym (symbol-name var)) var)) variables)))
`(let ,temps
(,@binding-form
,@body
,@(mapcar (lambda (mapping) `(setf ,@mapping)) temps))
,@(mapcar (lambda (mapping) `(setf ,(cadr mapping) ,(car mapping))) temps))))
(defmacro with-atomic-updates ((&rest variables) &body body)
;;Self-binding is necessary to avoid losing the previous value
`(with-atomic-updates* ,variables (let ,(mapcar (lambda (var) (list var var)) variables)) ,@body))
(defmacro without-atomic-updates ((&rest variables) &body body)
(declare (ignore variables))
`(progn ,@body))
(defstruct doplus-env
loop-name skip-label terminate-label default-collect-var
accumulators generators parent)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun find-loop-in-env (name env)
(when env
(if (eq name (doplus-env-loop-name env))
env
(find-loop-in-env name (doplus-env-parent env))))))
(defun find-generator (name env)
(loop
:for loop := env :then (doplus-env-parent loop)
:while loop
:do (let ((gen (assoc name (doplus-env-generators loop))))
(when gen (return (cons loop gen))))))
(defmacro with-doplus-body (env &body body)
(let ((no-return-value (gensym)))
`(macrolet ((collect (value &key (into ',(doplus-env-default-collect-var env)))
(let ((accumulator
(loop
:for loop := ,env :then (doplus-env-parent loop)
:while loop
:do (let ((acc (cdr (assoc into (doplus-env-accumulators loop)))))
(when acc (return acc))))))
(if accumulator
`(setf ,into (funcall ,accumulator ,value ,into))
(error "~A is not a known accumulator" into))))
(update (name)
(let ((generator (find-generator name ,env)))
(if generator
(if (eql (car generator) ,env)
`(progn ,@(cdr generator) ,name)
`(with-doplus-body ,(car generator)
,@(cdr generator) ,name))
(error "~S is not a known generator" name))))
(try-update (name &key (on-error (lambda (obj condition) (declare (ignore condition)) (values obj nil))))
(let ((generator (find-generator name ,env))
(block-name (gensym "TRY-UPDATE-BLOCK"))
(error-fn (gensym "ON-ERROR")))
(if generator
;;The following binding is to fix try-update on ECL (tested on 12.12.1).
;;Using ,on-error directly in the funcall form below results in
;;wrong values for captured variables in compiled code.
`(let ((,error-fn ,on-error))
(block ,block-name
(handler-bind ((error (lambda (cond)
(return-from ,block-name
(funcall ,error-fn ,name cond)))))
(with-doplus-body ,(car generator)
(macrolet ((terminate (&rest args)
(declare (ignore args))
`(return-from ,',block-name (values ,',name nil))))
,@(cdr generator) (values ,name t))))))
(error "~S is not a known generator" name))))
(skip (&optional (loop-name ',(doplus-env-loop-name env)))
(let ((the-loop (find-loop-in-env loop-name ,env)))
(if the-loop
`(go ,(doplus-env-skip-label the-loop))
(error "~S is not the name of a do+ loop in scope" loop-name))))
(terminate (&optional loop-name (return-value ',no-return-value))
(when (null loop-name)
(setf loop-name ',(doplus-env-loop-name env)))
(let ((the-loop (find-loop-in-env loop-name ,env)))
(if the-loop
(if (eq return-value ',no-return-value)
`(go ,(doplus-env-terminate-label the-loop))
`(return-from ,loop-name ,return-value))
(error "~S is not the name of a do+ loop in scope" loop-name))))
(do+ (&body body)
`(do+/internal ,,env ,@body)))
,@body)))
(defmacro do+ (&body body)
"High-level, extensible iteration construct. Refer to the manual for syntax and semantics."
`(do+/internal nil ,@body))
(defmacro do+/internal (doplus-env &body body &environment env)
(let (bindings declarations iterations termination-conditions result-forms generators
initializations finalizations accumulators (default-collect-var (gensym "COLLECT"))
prologue epilogue (wrapper #'identity) loop-name
(loop-label (gensym "LOOP")) (return-label (gensym "RETURN"))
(update-label (gensym "UPDATE")) (with-atomic-updates 'with-atomic-updates)
actual-body)
(if (and (car body) (symbolp (car body)))
(setf loop-name (car body) body (cdr body))
(setf loop-name (gensym "DOPLUS")))
(labels ((process-form (raw-form &optional iterations)
(let ((form (ignore-errors (macroexpand raw-form env)))) ;;TODO
(cond
((and (listp form) (not (symbolp (car form))))
(dolist (x form)
(setf iterations (process-form x iterations))))
((options-p form)
(when (cadr (member :name (options-map form)))
(setf loop-name (cadr (member :name (options-map form)))))
(when (member :atomic-updates (options-map form))
(unless (cadr (member :atomic-updates (options-map form)))
(setf with-atomic-updates 'without-atomic-updates))))
((generator-p form)
(let ((generator (process-form (generator-clauses form))))
(dolist (name (ensure-list (generator-name form)))
(push (cons name (reverse generator)) generators))))
((binding-p form)
(let ((existing-binding (find (binding-var form) bindings :key #'binding-var)))
(if existing-binding
(if (binding-default-provided? existing-binding)
;;It is an error to replace a binding with a default with a binding with a different default,
;;though it is not an error to redeclare an existing binding without respecifying its default.
(unless (or (not (binding-default-provided? form))
(eql (binding-default form) (binding-default existing-binding)))
(error "There is already a binding for ~S with default ~S"
(binding-var form) (binding-default existing-binding)))
(setf bindings (substitute form existing-binding bindings)))
(push form bindings))))
((declaration-p form) (push `(declare ,(declaration-form form)) declarations))
((termination-p form) (push (termination-condition form) termination-conditions))
((result-p form) (push (result-form form) result-forms))
((step-p form) (push (step-form form) iterations))
((initialization-p form) (push (initialization-form form) initializations))
((finalization-p form) (push (finalization-form form) finalizations))
((accumulator-p form)
(push (cons (accumulator-var form) (accumulator-function form)) accumulators))
((prologue-p form) (push (prologue-form form) prologue))
((epilogue-p form) (push (epilogue-form form) epilogue))
((wrapper-p form)
(let ((old-wrapper wrapper))
(setf wrapper
(lambda (body)
(funcall (wrapper-function form) (funcall old-wrapper body))))))
(t (push raw-form actual-body))))
iterations))
(setf iterations (process-form (cons `(accumulating-to ,default-collect-var) body)))
(when (null result-forms)
(setf iterations (process-form `(returning ,default-collect-var) iterations))))
(setf bindings (nreverse (mapcar (lambda (binding) (list (binding-var binding) (binding-default binding)))
bindings)))
(setf doplus-env (make-doplus-env
:loop-name loop-name :parent doplus-env :accumulators accumulators
:generators generators :default-collect-var default-collect-var
:skip-label update-label :terminate-label return-label)
actual-body (nreverse actual-body))
(multiple-value-bind (body decls)
(tcr.parse-declarations-1.0::parse-body actual-body :documentation nil)
`(let ,bindings
,@(nreverse declarations)
,@decls
,(funcall
wrapper
`(with-doplus-body ,doplus-env
(block ,loop-name
(tagbody
(,with-atomic-updates ,(mapcar #'car bindings)
,@(nreverse initializations))
,loop-label
,(when termination-conditions
`(when (or ,@(nreverse termination-conditions))
(go ,return-label)))
,@(nreverse prologue)
,@body
,@(nreverse epilogue)
,update-label
(,with-atomic-updates ,(mapcar #'car bindings)
,@(nreverse iterations))
(go ,loop-label)
,return-label
,@(nreverse finalizations)
;;result-forms is never nil
(return-from ,loop-name (values ,@(nreverse result-forms)))))))))))
;;Top-level macros to aid autocompletion and store documentation
(defmacro sum (value &key (to (error "sum requires a target accumulator (:to key)")))
"Syntactic sugar for collect, intended to be used when the accumulator computes a sum."
`(collect ,value :into ,to))
(defmacro collect (value &key into)
"Collects a value into an accumulator. If no accumulator is provided, the default one for the current do+ loop is used."
(declare (ignore value into))
(error "collect can only be called inside the body of a do+"))
(defmacro skip (&optional loop-name)
"Skips the current iteration. Refers to the current loop or, if loop-name is specified, to the closest surrounding loop with that name."
(declare (ignore loop-name))
(error "skip can only be called inside the body of a do+"))
(defmacro terminate (&optional loop-name return-value)
"Immediately terminates the loop. Refers to the current loop or, if loop-name is specified and non-NIL, to the closest surrounding loop with that name. Can optionally specify a return value for the loop, which, if provided, will override the loop's ordinary return value."
(declare (ignore loop-name return-value))
(error "terminate can only be called inside the body of a do+"))
(defmacro update (var)
"Updates the generator named <var>, calculating new value(s) for its variable(s) and evaluating its pre and post conditions, terminating the loop if they fail.
If successful, the update returns the value of <var>."
(declare (ignore var))
(error "update can only be called inside the body of a do+"))
(defmacro try-update (var &key on-error)
"Tries to update the generator named <var> as by UPDATE. If the loop would be terminated as a result of the update operation, it is not terminated.
Any errors occurring during the update are ignored by default; however, it is possible to provide a function to be invoked in case of error to determine what to do. This is the value of the <on-error> parameter, which, if provided, must be a function of two arguments: the first is the value to be returned as the result of the try-update form if the error is suppressed; the second is the condition object itself, which can be resignaled.
Calling TERMINATE inside the function, if it is defined lexically inside the DO+ body, will regularly terminate the loop."
(declare (ignore var on-error))
(error "try-update can only be called inside the body of a do+")) | 32,710 | Common Lisp | .lisp | 525 | 51.213333 | 637 | 0.626463 | alessiostalla/doplus | 8 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 6407433ee6631cb6eb883007f1c1bfb10bc74e3d0acf9769661f31469f97142e | 12,217 | [
-1
] |
12,218 | cl-enumerations.lisp | alessiostalla_doplus/cl-enumerations.lisp | (in-package :doplus)
(defmacro over (enum)
(let ((en (gensym "ENUMERATION")))
(list
`(with (,en ,enum))
(make-iteration :precondition `(enum:has-next-p ,en) :init `(enum:next ,en) :step `(enum:next ,en)))))
| 224 | Common Lisp | .lisp | 6 | 33.5 | 107 | 0.617512 | alessiostalla/doplus | 8 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 0008b92b83ba1d051ca2edfbec163713654cdd8bade8e2e76a73c23e8398f28e | 12,218 | [
-1
] |
12,219 | destructuring.lisp | alessiostalla_doplus/destructuring.lisp | ;;; Copyright (C) 2011 Alessio Stalla
;;;
;;; 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/>.
(in-package :doplus)
(defun extract-variables (lambda-list)
(flet ((extract-variable (form)
(cond ((symbolp form)
(unless (find form lambda-list-keywords)
form))
((symbolp (car form)) ;;&optional/&key (var default)
(car form))
(t (cadar form))))) ;;&key with explicit keyword name ((key var) default)
(let ((rest (cdr lambda-list)))
(remove nil
(list* (extract-variable (car lambda-list))
(if (symbolp rest)
(list (extract-variable rest))
(extract-variables rest)))))))
(defun make-destructuring-form (lambda-list expression)
`(destructuring-bind ,lambda-list ,expression)) | 1,476 | Common Lisp | .lisp | 31 | 40.096774 | 90 | 0.640333 | alessiostalla/doplus | 8 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | d8e807a5b7139e3cc649f1b655bbb2d57679a856696d404682654befdffce3c9 | 12,219 | [
-1
] |
12,220 | packages.lisp | alessiostalla_doplus/packages.lisp | ;;; Copyright (C) 2011 Alessio Stalla
;;;
;;; 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/>.
#+abcl
(require :extensible-sequences)
(defpackage :doplus
(:use :cl)
(:shadow #:declaration #:step)
#+(or abcl sbcl)
(:import-from :sequence #:make-sequence-iterator)
(:export
;;User-level API
#:do+ #:for #:generating #:being #:in #:in-list #:in-vector #:across #:list-tails
#:hash-entries-of #:symbols-in #:from #:to
#:finding #:with #:initially #:finally #:previous #:stop-when #:returning
#:counting #:summing-to #:accumulating-to #:collecting-into
#:summing-to-and-returning #:accumulating-to-and-returning #:collecting-into-and-returning
#:maximizing #:minimizing #:optimizing
#:options
;;Body-local macros
#:collect #:sum #:skip #:terminate #:update #:try-update
;;Extensions API
#:defclause
;;Low-level API
#:make-binding #:make-termination #:make-result #:make-initialization #:make-finalization
#:make-accumulation #:make-prologue #:make-epilogue #:make-step
#:make-iteration #:make-simple-iteration
#:*iteration-variable*)) | 1,699 | Common Lisp | .lisp | 39 | 40.923077 | 93 | 0.718165 | alessiostalla/doplus | 8 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 0835d6d5d1dd4f63f21bc0ad2c056dc74d21ed23fcabe52e3a0ed847c4033750 | 12,220 | [
-1
] |
12,221 | doplus-fset.asd | alessiostalla_doplus/doplus-fset.asd | ;;; Copyright (C) 2011-2012 Alessio Stalla
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(asdf:defsystem :doplus-fset
:name "doplus-fset"
:description "Integration of FSet collections in doplus."
:author "Alessio Stalla <[email protected]>"
:licence "GPLv3"
:serial t
:depends-on (:doplus :fset)
:components
((:static-file "doplus-fset.asd")
(:file "fset")))
| 1,001 | Common Lisp | .asd | 24 | 39.875 | 73 | 0.737705 | alessiostalla/doplus | 8 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 3e09c89ea5862bc2a174291e13b6d668dc0486649a9eb6ba982d3863c9cda117 | 12,221 | [
-1
] |
12,222 | doplus.asd | alessiostalla_doplus/doplus.asd | ;;; Copyright (C) 2011-2021 Alessio Stalla
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(asdf:defsystem :doplus
:name "doplus"
:version "1.1.0"
:description "DO+ (doplus) is a high-level, extensible iteration construct for Common Lisp with a reasonably simple implementation, which in particular does not use a code walker."
:author "Alessio Stalla <[email protected]>"
:licence "GPLv3"
:serial t
:depends-on (:parse-declarations-1.0)
:components
((:static-file "doplus.asd")
(:file "packages")
;;Could be conditionalized to provide different destructuring implementations
(:file "destructuring")
#-(or abcl sbcl)
(:file "sequence-iterator")
(:file "doplus")))
(defmethod perform ((o asdf:test-op) (s (eql (asdf:find-system :doplus))))
(asdf:load-system :doplus-tests)
(eval (read-from-string "(doplus-tests:run-all-tests)"))
t)
| 1,496 | Common Lisp | .asd | 34 | 41.705882 | 182 | 0.733562 | alessiostalla/doplus | 8 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 41e75f78126953896c2c8d87b4d485c627a937fe79016ba1e76e90bc2d56a05e | 12,222 | [
-1
] |
12,223 | doplus-tests.asd | alessiostalla_doplus/doplus-tests.asd | ;;; Copyright (C) 2011-2012 Alessio Stalla
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(asdf:defsystem :doplus-tests
:name "doplus-tests"
:description "Test suite for doplus."
:author "Alessio Stalla <[email protected]>"
:licence "GPLv3"
:serial t
:depends-on (:doplus :fiveam)
:components
((:static-file "doplus-tests.asd")
(:file "tests")))
| 987 | Common Lisp | .asd | 24 | 39.291667 | 73 | 0.735967 | alessiostalla/doplus | 8 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 9db0d33df4906c81a6dd1e44d6419e71947f5bbe91ea3d61f2bda2ae4c5a30a0 | 12,223 | [
-1
] |
12,235 | ci.yml | alessiostalla_doplus/.github/workflows/ci.yml | name: CI
# Github Actions allows for running jobs on a wide variety of events
on:
push: # Commits pushed to Github
pull_request: # Pull request is update
workflow_dispatch: # Manually dispatched from Github's UI
jobs:
test:
name: ${{ matrix.lisp }} on ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
# Each combination of lisp and os are tested
matrix:
lisp: [sbcl-bin, ccl-bin]
os: [macOS-latest]
steps:
- name: Ubuntu specific settings
if: matrix.os == 'ubuntu-latest'
run: |
sudo add-apt-repository ppa:xapienz/curl34
sudo apt-get update
sudo apt-get install libcurl4
- name: Windows specific settings
if: matrix.os == 'windows-latest'
run: |
git config --global core.autocrlf false
echo "name=ROSWELL_INSTALL_DIR::$HOME/ros" >> $GITHUB_ENV
echo "$HOME/ros/bin" >> $GITHUB_PATH
- uses: actions/checkout@v1
- name: Install Roswell
env:
LISP: ${{ matrix.lisp }}
shell: bash
run: curl -L https://raw.githubusercontent.com/roswell/roswell/master/scripts/install-for-ci.sh | sh
- name: Install Test Framework
shell: bash
run: ros install neil-lindquist/ci-utils
- name: Run tests
shell: bash
run: ~/.roswell/bin/run-fiveam -e t -l doplus-tests doplus-tests::doplus-suite | 1,422 | Common Lisp | .l | 40 | 28.35 | 108 | 0.624638 | alessiostalla/doplus | 8 | 0 | 2 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 50d291ba6cea340e55db86004c05a0631b34b62d58f2809733eb1ff67ffc384b | 12,235 | [
-1
] |
12,250 | package.lisp | Izaakwltn_vibratsia/package.lisp | ;;;; package.lisp
;;;;
;;;; Copyright (c) 2021 Izaak Walton
(defpackage #:vibratsia
(:documentation "String Resonance Calculation Package.")
(:use #:cl #:alexandria)
;;; pitch.lisp
(:export
#:note-to-freq
#:freq-to-note
#:make-note
#:freq-adjust
#:freq-incr
#:frequency-ladder)
;;; resonance.lisp
(:export
#:overtones
#:compare-overtones)
;;; instruments.lisp
(:export
#:luthier
#:violin
#:viola
#:cello
#:bass
#:hardanger-fiddle)
;;; scales.lisp
(:export
#:build-scale
#:scale-ranking
#:assess-scale)
;;; analysis.lisp
(:export
#:symp-rating
#:symp-rating-by-note
#:symp-by-string
#:assess-note
#:most-resonant
#:resonance-ranking
#:assess-instrument
#:avg-resonance
#:optimal-keys))
| 802 | Common Lisp | .lisp | 42 | 15.309524 | 58 | 0.645638 | Izaakwltn/vibratsia | 8 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 562d2786ac37ed912532f4fc1d3a1c0545442809b309e5fd4a6a3f2af93cbc1e | 12,250 | [
-1
] |
12,251 | resonance.lisp | Izaakwltn_vibratsia/resonance.lisp | ;;;;resonance.lisp
(in-package #:vibratsia)
;;;Overtone Functions
(defun overtone-ladder (fundamental gap n)
(cond ((< n 1) nil)
(t (cons (+ fundamental gap)
(overtone-ladder (+ fundamental gap) gap (- n 1))))))
(defun overtones (fundamental)
"Generates a list of overtone frequencies for a given pitch-frequency."
(cons fundamental
(overtone-ladder fundamental fundamental 15)))
;;;Resonance Functions
(defun resonance-check (pitch overtone-list)
(loop for overtone in overtone-list
if (< (abs (- overtone pitch)) (* .005 pitch))
collect overtone into common-overtones
finally (return common-overtones)))
(defun resonance-compare (overtones1 overtones2)
(cond ((null overtones1) nil)
((resonance-check (first overtones1) overtones2)
(append (resonance-check (first overtones1) overtones2)
(resonance-compare (rest overtones1) overtones2)))
(t (resonance-compare (rest overtones1) overtones2))))
(defun compare-overtones (fund1 fund2)
"Compares the overtones of two fundamentals, returns sympathetic overlap."
(resonance-compare (overtones fund1) (overtones fund2)))
| 1,112 | Common Lisp | .lisp | 26 | 40.076923 | 76 | 0.755102 | Izaakwltn/vibratsia | 8 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 1985a72cffd0198ec8755804a4866a84e0da8f9ffec68e75ce9d9ba6f5cf3d14 | 12,251 | [
-1
] |
12,252 | pitch.lisp | Izaakwltn_vibratsia/pitch.lisp | ;;;; pitch.lisp
;;;;
;;;; Copyright (c) 2021 Izaak Walton
(in-package #:vibratsia)
;;; Note/Frequency Conversions
(defvar note-freq-table '((C . 16.35)
(C# . 17.32)
;(Db . 17.32)
(D . 18.35)
(D# . 19.45)
;(Eb . 19.45)
(E . 20.6)
(F . 21.83)
(F# . 23.12)
;(Gb . 23.12)
(G . 24.5)
(G# . 25.96)
;(Ab . 25.96)
(A . 27.5)
(Bb . 29.14)
(B . 30.87)))
;;;Functions to convert note to frequency
(defun octave-shift (freq num-octaves)
(* freq (expt 2 num-octaves)))
(defun freq-climber (freq octaves-up)
"Adjusts the note-frequency to the proper octave."
(cond ((zerop octaves-up) freq)
(t (freq-climber (* 2 freq) (- octaves-up 1)))))
(defun note-to-freq (note-name octave);;;has to use quoted note-name
"Takes a note and octave, returns the note's frequency."
(freq-climber (cdr (assoc note-name note-freq-table)) octave))
;;;Functions to convert frequency to note
(defun minimize-freq (frequency counter)
"Minimizes the frequency until it's in the base octave."
(cond ((< frequency 31) (list frequency counter))
(t (minimize-freq (/ frequency 2) (+ counter 1)))))
(defun closest-note (freq freq-list)
"Returns the equal temperament note-name closest to the frequency."
(loop :with min-note := (car (first freq-list))
:with min-freq := (cdr (first freq-list))
:with min-dist := (abs (- freq min-freq))
:for (note . note-freq) :in (rest freq-list)
:for dist := (abs (- freq note-freq))
:when (< dist min-dist)
:do (setf min-note note
min-freq note-freq
min-dist dist)
:finally (return (values min-note
min-dist))))
(defun freq-to-note (freq)
"Takes a frequency and returns a (note octave) pair."
(destructuring-bind (canonical-freq octave)
(minimize-freq freq 0)
(list (closest-note canonical-freq note-freq-table) octave)))
;;; Note Class
(defclass note ()
((note-name :initarg :note-name
:accessor note-name)
(octave :initarg :octave
:accessor octave)
(freq-float :initarg :freq-float
:accessor freq-float))
(:documentation "A note defined by Note-name, octave number,
and frequency."))
(defmethod print-object ((obj note) stream)
(print-unreadable-object (obj stream :type t)
(with-accessors ((note-name note-name)
(octave octave)
(freq-float freq-float))
obj
(format stream "~a-~a, Frequency: ~f" note-name octave freq-float))))
(defun make-note (frequency)
"Makes a full note instance from a given frequency."
(make-instance 'note :note-name (first (freq-to-note frequency))
:octave (second (freq-to-note frequency))
:freq-float frequency))
;;;Frequency generation
;fn = f0 * (a)^n
;f0 = 440
;n = half steps away from fixed note (positive or negative)
;fn = frequency of note n half steps away
;a = 2^1/12
(defun freq-adjust (root interval)
"Raises or lowers a root frequency by an interval n in half-steps.
+----------------------------------+
| n 1/12|
|f(n) = f(0) * (a) where a = 2 |
+----------------------------------+"
(* root (expt (expt 2 (/ 1 12)) interval)))
(defun freq-incr (fixed)
"Raises a frequency by one half-step, for building chromatic test samples.
+----------------------------------+
| 1 1/12|
|f(1) = f(0) * (a) where a = 2 |
+----------------------------------+"
(* fixed (expt (expt 2 (/ 1 12)) 1)))
(defun frequency-ladder (min max)
"Builds a chromatic test-sample within the bounds."
(cond ((> min max) nil)
(t (cons min (frequency-ladder (freq-incr min) max)))))
;;; Note Operations
(defgeneric transpose (object half-steps)
(:documentation "Transposes a given object by a signed number of half-steps."))
(defmethod transpose ((note note) half-steps)
(make-note (freq-adjust (freq-float note) half-steps)))
| 4,140 | Common Lisp | .lisp | 105 | 33.266667 | 99 | 0.582045 | Izaakwltn/vibratsia | 8 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 6ce587b71031bf68962eb8a257550a53561ff62f362cd6282c69c490c9488ae5 | 12,252 | [
-1
] |
12,253 | tuning.lisp | Izaakwltn_vibratsia/tuning.lisp | ;;;;tuning.lisp
(in-package :vibratsia)
;;;;;;functions for changing tuning systems- temperaments but also just changing the A frequency
| 139 | Common Lisp | .lisp | 3 | 44.666667 | 96 | 0.783582 | Izaakwltn/vibratsia | 8 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | ef102f2d0767c0f9a2390c45e3e716ea4075df10e152e8a411dccf7f9c96708f | 12,253 | [
-1
] |
12,254 | instruments.lisp | Izaakwltn_vibratsia/instruments.lisp | ;;;; instruments.lisp
;;;;
;;;; Copyright (c) 2022 Izaak Walton
(in-package #:vibratsia)
;;; The Instrument class
(defclass instrument ()
((name :initarg :name
:accessor name)
(strings :initarg :strings
:accessor strings)
(lower-bound :initarg :lower-bound
:accessor lower-bound)
(upper-bound :initarg :upper-bound
:accessor upper-bound))
(:documentation "A stringed instrument defined by its name, strings, and resonant range."))
(defmethod print-object ((obj instrument) stream)
(print-unreadable-object (obj stream :type t)
(with-accessors ((name name)
(strings strings))
obj
(format stream "~a, strings: ~a" name strings))))
;Also a function is needed for specific lower/upper bounds
(defun luthier (instrument-name string-freqs)
"Builds an instrument object given the name and the frequencies of the strings."
(make-instance 'instrument
:name instrument-name
:strings (loop :for string :in string-freqs
:collect (make-note string))
:lower-bound (reduce #'min string-freqs)
:upper-bound (* 3 (reduce #'max string-freqs))))
;;; Predefined Standard Instruments:
(alexandria:define-constant violin-open-strings '(196 293.66 440 659.25) :test 'equal)
(defvar violin (luthier 'violin violin-open-strings))
(alexandria:define-constant viola-open-strings '(130.8 196 293.66 440) :test 'equal)
(defvar viola (luthier 'viola viola-open-strings))
(alexandria:define-constant cello-open-strings '(65.4 98 146.8 220) :test 'equal)
(defvar cello (luthier 'cello cello-open-strings))
(alexandria:define-constant bass-open-strings '(41.2 55 73.4 98.0) :test 'equal)
(defvar bass (luthier 'bass bass-open-strings))
; add guitar, ukulele, etc, 5 string violin
;;;Pre-defined unusual instruments:
(defvar hardanger-fiddle-strings (mapcar #'(lambda (note-set)
(note-to-freq (first note-set) (second note-set)))
'((B 3) (E 4) (B 4) (F# 5)
(C# 5) (E 5) (F# 5) (G# 5) (B 5))))
(defvar hardanger-fiddle (luthier 'hardanger-fiddle hardanger-fiddle-strings))
;;;;Maybe Sitar, arpeggione
| 2,187 | Common Lisp | .lisp | 47 | 40.851064 | 98 | 0.683192 | Izaakwltn/vibratsia | 8 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 5b5e2c4e8a0b1cc650ab9a6fe53e72cff028e81df81bbe8bd0543e9426a82438 | 12,254 | [
-1
] |
12,255 | package.lisp | Izaakwltn_vibratsia/resonance-calculator/package.lisp | ;;;; resonance-calculator/package.lisp
;;;;
;;;; Copyright (c) 2022 Izaak Walton
(defpackage #:resonance-calculator
(:documentation "String Resonance Calculator web-app")
(:use #:cl))
| 189 | Common Lisp | .lisp | 6 | 29.666667 | 56 | 0.730769 | Izaakwltn/vibratsia | 8 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 08ddbe890d1a2f3cacdf1906076aaf75dcfacde95a208208f9856e9b77c651d2 | 12,255 | [
-1
] |
12,256 | page.lisp | Izaakwltn_vibratsia/resonance-calculator/page.lisp | ;;;; resonance-calculator/page.lisp
;;;;
;;;; Copyright (c) 2022 Izaak Walton
(in-package #:resonance-calculator)
(defmacro with-page ((&key title) &body body)
`(spinneret::with-html-string
(:doctype)
(:html
(:head
(:meta :charset "utf-8")
(:meta :name "viewport" :content "width=device-width, initial-scale=1")
(:link :rel "stylesheet"
:href "https://cdn.simplecss.org/simple.min.css")
(:title ,title))
(:body ,@body)
(:footer "Vibratsia Resonance Calculator - Copyright (c) 2021-2022 "
(:a :href "https://www.github.com/Izaakwltn/vibratsia"
"Written using Common Lisp")))))
| 656 | Common Lisp | .lisp | 18 | 31 | 78 | 0.632075 | Izaakwltn/vibratsia | 8 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | dfbe4565d45d15860ea1c6a772e95656003e47e34cd46229b6a19037356ecf31 | 12,256 | [
-1
] |
12,257 | output.lisp | Izaakwltn_vibratsia/resonance-calculator/output.lisp | ;;;; resonance-calculator/resonance-output.lisp
;;;;
;;;; Copyright (c) 2021-2022 Izaak Walton
(in-package #:resonance-calculator)
;;;;------------------------------------------------------------------------
;;;;Instrument Assessment
;;;;------------------------------------------------------------------------
(defvar instrument-parse-list '(("violin"
(vibratsia::luthier 'violin '(196 293.66 440 659.25)))
("VIOLA"
(vibratsia::luthier 'viola '(130.8 196 293.66 440)))
("CELLO"
(vibratsia::luthier 'cello '(65.4 98 146.8 220)))
("BASS"
(vibratsia::luthier 'bass '(65.4 98 146.8 220)))))
(defvar instr-assessment)
(hunchentoot::define-easy-handler (instrument-assess :uri "/instrument-assess")
(instrument-option)
(setf (hunchentoot:content-type*) "text/html")
(setq instr-assessment (vibratsia::assess-instrument
(eval (second (assoc instrument-option instrument-parse-list :test #'string-equal)))))
(with-page (:title "Instrument Resonance Profile")
(:header
(:h1 "Resonance Calculator")
(:h2 "Instrument Assessment")
(:p "A comprehensive analysis of the resonant keys and frequencies on the violin. "))
(:section
(:h5 (format nil "Instrument name: ~a"
(vibratsia::name (vibratsia::instrument instr-assessment)))))
(:section
(:h5 (format nil "Open-strings:~%"))
(:ul (loop for s in (vibratsia::strings (vibratsia::instrument instr-assessment))
do (:li (format nil "~a-~a Frequency: ~a"
(vibratsia::note-name s)
(vibratsia::octave s)
(vibratsia::freq-float s))))))
(:section
(:h5 (format nil "Most Resonant Keys:"))
(:ul (loop for k in (vibratsia::key-ranks instr-assessment)
do (:li (format nil "~a ~a, resonance rating: ~a"
(second k)
(third k)
(first k))))))
(:section
(:h5 (format nil "Most Resonant Notes:"))
(:ul (loop for n in (vibratsia::note-ranks instr-assessment)
do (:li (format nil "~a-~a Frequency: ~a"
(vibratsia::note-name (second n))
(vibratsia::octave (second n))
(vibratsia::freq-float (second n)))))))
(:a :href "/resonance.html" "Try another calculation")))
;;;;------------------------------------------------------------------------
;;;;Key Assessment
;;;;------------------------------------------------------------------------
;(vibratsia::assess-scale (vibratsia::build-scale root-option quality-option ;3) instrument-option)
;(defvar quality-parse-list '(("major"
(defun lowest-note-available (note-name instrument)
"Finds the lowest octave of a particular note on an instrument"
(second (assoc (second (assoc note-name root-parse-list :test #'string-equal))
(mapcar #'(lambda (freq)
(list (first (vibratsia::freq-to-note freq))
freq))
(vibratsia::frequency-ladder
(vibratsia::lower-bound instrument)
(vibratsia::freq-adjust (vibratsia::lower-bound instrument) 11))))))
(hunchentoot::define-easy-handler (scale-assess :uri "/key-assess")
(root-option quality-option instrument-option)
(setf (hunchentoot:content-type*) "text/html")
(let ((instrument-object (eval
(second
(assoc instrument-option
instrument-parse-list :test #'string-equal))))
(key-assessment (vibratsia::assess-scale
(vibratsia::build-scale
(lowest-note-available root-option instrument-object)
(second (assoc quality-option quality-parse-list :test #'string-equal))
3)
instrument-object)))
(with-page (:title "Key Resonance Profile")
(:header
(:h1 "Resonance Calculator")
(:h2 "Key Resonance Profile")
(:p (format nil "A comprehensive analysis of the key ~a ~a, as played on the ~a"
(first (vibratsia::freq-to-note
(vibratsia::root (vibratsia::scale key-assessment))))
(vibratsia::quality (vibratsia::scale key-assessment))
(vibratsia::name (vibratsia::instr key-assessment)))))
(:section
(:h5 (format nil "Average Sympathetic Vibration Rating: ~a"
(vibratsia::avg-rating key-assessment))))
(:section
(:h5 "The notes of the key ranked by resonance on the chosen instrument:")
(:ul
(loop for n in (vibratsia::rank-list key-assessment)
do (:li (format nil "~a" n)))))
(:a :href "/resonance.html" "Try another calculation"))))
;;;;find the lowest iteration of the key on the instrument, generate a 3 octave scale, return
;the scale assessment
;;;;------------------------------------------------------------------------
;;;;Note Assessment
;;;;------------------------------------------------------------------------
(defvar note-assessment)
(hunchentoot::define-easy-handler (note-assess :uri "/note-assess") (note-option instrument-option)
(setf (hunchentoot:content-type*) "text/html")
(setq note-assessment
(let ((note (vibratsia::make-note (parse-float:parse-float note-option))))
(vibratsia::assess-note (eval (second (assoc instrument-option
instrument-parse-list :test #'string-equal)))
note)))
(with-page (:title "Instrument Resonance Profile")
(:header
(:h1 "Resonance Calculator")
(:h2 "Note-instrument Assessment")
(:p (format nil "A comprehensive analysis of the note, ~a-~a, as played on the ~a"
(first (vibratsia::freq-to-note (parse-float:parse-float note-option)))
(second (vibratsia::freq-to-note (parse-float:parse-float note-option)))
instrument-option)))
(:section
(:h5 (format nil "Sympathetic Vibration Rating: ~a" (vibratsia::rating note-assessment))))
(:section
(:h5 "List of Resonant Frequencies:")
(:ul
(loop for note in (vibratsia::res-list note-assessment)
if (equal (second note) 'string)
do (:li (:b (format nil "~a ~a" (first note) (second note))))
else
do (:ul
(loop for n in note
do (:li (format nil "~a" n)))))))
(:a :href "/resonance.html" "Try another calculation")))
| 6,127 | Common Lisp | .lisp | 130 | 40.546154 | 99 | 0.59719 | Izaakwltn/vibratsia | 8 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 887ee47724aa9310e180f007068e311fd217c70f43c7afb13a984ad743b3ca75 | 12,257 | [
-1
] |
12,258 | app.lisp | Izaakwltn_vibratsia/resonance-calculator/app.lisp | ;;;; resonance-calculator/app.lisp
;;;;
;;;; Copyright (c) 2022 Izaak Walton
(in-package :resonance-calculator)
;;; Generating menu option lists:
(defvar note-option-list (mapcar #'vibratsia::freq-to-note
(vibratsia::frequency-ladder 16.35 4185.6)))
(defvar instrument-option-list '("violin" "viola" "cello" "bass" "hardingfele"))
;add more maybe
(defvar instrument-parse-list '(("violin" vibratsia:violin)
("viola" vibratsia:viola)
("cello" vibratsia:cello)
("bass" vibratsia:bass)
("hardingfele" vibratsia:hardanger-fiddle)))
;(defvar instrument-parse-list '(("violin"
; (vibratsia::luthier 'violin '(196 293.66 440 659.25)))
; ("VIOLA"
; (vibratsia::luthier 'viola '(130.8 196 293.66 440)))
; ("CELLO"
; (vibratsia::luthier 'cello '(65.4 98 146.8 220)))
; ("BASS"
; (vibratsia::luthier 'bass '(65.4 98 146.8 220)))
; ("hardingfele"
; (vibratsia::luthier 'hardanger-fiddle
; vibratsia::hardanger-fiddle-strings))))
(defvar root-option-list '(C C# D D# E F F# G G# A Bb B))
(defvar root-parse-list '(("c" vibratsia::c)
("c#" vibratsia::c#)
("d" vibratsia::d)
("d#" vibratsia::d#)
("e" vibratsia::e)
("f" vibratsia::f)
("f#" vibratsia::f#)
("g" vibratsia::g)
("g#" vibratsia::g#)
("a" vibratsia::a)
("bb" vibratsia::bb)
("b" vibratsia::b)))
(defvar quality-parse-list '(("major" vibratsia::major)
("ionian" vibratsia::ionian)
( "dorian" vibratsia::dorian)
("phrygian" vibratsia::phrygian)
("lydian" vibratsia::lydian)
("mixolydian" vibratsia::mixolydian)
("aeolian" vibratsia::aeolian)
("nat-min" vibratsia::nat-min)
("mel-min" vibratsia::mel-min)
("har-min" vibratsia::har-min)
("locrian" vibratsia::locrian)))
(defvar quality-option-list
'(major ionian dorian phrygian lydian mixolydian aeolian nat-min mel-min har-min locrian))
;;;;------------------------------------------------------------------------
(defun resonance ()
(with-page (:title "Resonance Calculator")
(:header
(:h1 "Resonance Calculator"))
(:section
(:p "Every note played on an instrument, or even sung, is actually a composite sound consisting of approximately 32 overtones. On stringed instruments, these overtones can be isolated using harmonics.
Sympathetic vibration occurs when the overtones of an executed note overlap with the overtones of an open string. Harmonic nodes, as the overtones are called in string geography, respond to similar frequencies, and vibrate the open string audibly, and sometimes even visually."))
(:section
(:h2 "Instrument Assessment")
(:p "Select an instrument to calculate its most resonant keys and most resonant notes:")
(:form :action "/instrument-assess" :id "instrument-assess"
(:select :name "instrument-option" :form "instrument-assess"
(loop for instrument in resonance-calculator::instrument-option-list
do (:option :value instrument (format nil "~a" instrument))))
(:input :type "submit" :value "Assess Instrument" :class "button")))
(:section
(:h3 (:i "Key Assessment"))
(:p "Select the tonic, scale quality, and instrument to find the most resonant notes in the key.")
(:form :action "/key-assess" :id "key-assess"
(:select :name "root-option" :form "key-assess"
(loop for r in resonance-calculator::root-option-list
do (:option :value r (format nil "~A" r))))
(:select :name "quality-option" :form "key-assess"
(loop for qual in resonance-calculator::quality-option-list
do (:option :value qual (format nil "~a" qual))))
(:select :name "instrument-option" :form "key-assess"
(loop for instrument in resonance-calculator::instrument-option-list
do (:option :value instrument (format nil "~a" instrument))))
(:input :type "submit" :value "Assess Key" :class "button")))
(:section
(:h2 "Note Assessment")
(:p "Select a note and an instrument to calculate the sympathetic frequencies on each string.")
(:form :action "/note-assess" :id "note-assess"
:method "get"
(:select :name "note-option" :form "note-assess"
(loop for note in (vibratsia::frequency-ladder 16.35 4185.6)
do (:option :value note
(format nil "~a-~a"
(first (vibratsia::freq-to-note note))
(second (vibratsia::freq-to-note note))))))
(:select :name "instrument-option" :form "note-assess"
(loop for instrument in resonance-calculator::instrument-option-list
do (:option :value instrument
(format nil "~a" instrument))))
(:input :type "submit" :value "Assess Note" :class "button" )))))
(push (hunchentoot::create-prefix-dispatcher "/resonance.html" #'resonance)
hunchentoot::*dispatch-table*)
| 5,018 | Common Lisp | .lisp | 99 | 43.636364 | 279 | 0.631557 | Izaakwltn/vibratsia | 8 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | e53e843b419b1fba394dbfb25e25e88a5302ba300b95ea4f0c58f7d9943456b0 | 12,258 | [
-1
] |
12,259 | launch-site.lisp | Izaakwltn_vibratsia/resonance-calculator/launch-site.lisp | ;;;; resonance-calculator/launch-site.lisp
;;;;
;;;; Copyright (c) 2021-2022 Izaak Walton
(in-package #:resonance-calculator)
(defvar *resonance-app*
(make-instance 'hunchentoot:easy-acceptor
:port 4242
:document-root
(asdf::system-relative-pathname "vibratsia" "resonance-calculator/")))
(defun launch ()
"Launching the webapp"
(hunchentoot::start *resonance-app*))
| 385 | Common Lisp | .lisp | 12 | 29.583333 | 73 | 0.740541 | Izaakwltn/vibratsia | 8 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 676d9168ebb63bbf848605912b98364fbc3f6a23659b235d99aaba6ed7e7d5d0 | 12,259 | [
-1
] |
12,260 | resonance-calculator.asd | Izaakwltn_vibratsia/resonance-calculator.asd | ;;;; resonance-calculator.asd
;;;;
;;;; Copyright (c) 2022 Izaak Walton
(asdf:defsystem #:resonance-calculator
:version "0.0.2"
:author "Izaak Walton <[email protected]>"
:license "GNU General Purpose License"
:description "A Webapp for exploring resonance on string instruments."
:depends-on (#:vibratsia #:hunchentoot #:spinneret #:parse-float)
:serial t
:components ((:module "resonance-calculator"
:serial t
:components ((:file "package")
(:file "launch-site")
(:file "page")
(:file "app")
(:file "output")))))
| 640 | Common Lisp | .asd | 17 | 29.529412 | 72 | 0.596463 | Izaakwltn/vibratsia | 8 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 75acb7c2dc6746f3490dc9d4d2abfc3ecaead81d6bdff4d5b8dfb7af068c5fea | 12,260 | [
-1
] |
12,261 | vibratsia.asd | Izaakwltn_vibratsia/vibratsia.asd | ;;;; vibratsia.asd
;;;;
;;;; Copyright (c) 2021-2022 Izaak Walton
(asdf:defsystem #:vibratsia
:version "0.0.3"
:author "Izaak Walton <[email protected]>"
:license "GNU General Purpose License"
:description "A module for analyzing sympathetic vibrations on stringed instruments."
:depends-on (#:alexandria)
:serial t
:components ((:file "package")
(:file "pitch")
(:file "resonance")
(:file "instruments")
(:file "scales")
(:file "analysis")))
| 504 | Common Lisp | .asd | 16 | 26.9375 | 87 | 0.65567 | Izaakwltn/vibratsia | 8 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 86ec64248831df2fed582eb4cfcff20fd55e06fa493705acffe5bc0d42d87367 | 12,261 | [
-1
] |
12,274 | index.html | Izaakwltn_vibratsia/resonance-calculator/index.html | <!-- index.html -->
<html>
<head>
<title> "Redirect to resonance." </title>
<meta http-equiv="refresh" content="0; url='http://127.0.0.1:4242/resonance.html'" />
</head>
<body style="background-color:black">
</body>
</html>
| 871 | Common Lisp | .l | 9 | 23.888889 | 110 | 0.168213 | Izaakwltn/vibratsia | 8 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 40639dea5d727e1b94d03886a4d662bc16ef46f707d36418f03a94f66f601fd4 | 12,274 | [
-1
] |
12,289 | canvas.lisp | VitoVan_focalizzare/canvas.lisp | ;;
;; No, shit! you are looking at the source code!
;; This is absolutely a piece of shit and might cause physical damage to your eyes.
;;
;; I have been programming for many years,
;; but I have never managed to be professional in any programming language.
;;
;; Especially Lisp.
;;
;; I like Lisp a lot, but it is such a pain to distribute software written in Lisp,
;; and so few people are working on this language (compare to JavaScript? Maybe this is a good thing).
;;
;; So I tried to do some shit work to make Lisp software (SDL2 alike) distribution easier,
;; nothing high-tech, they are just a bunch of shitty bash scripts, some kindergarten C and a little messy Lisp.
;;
;; After the shit work is done, we could generate a cross-platform (Linux / macOS / Windows) software
;; with a single Lisp file.
;;
;; Like this one Focalizzare.
;;
;; All we need is to write a file named `canvas.lisp', and then leave the rest to `CALM' - a shit work bearer.
;;
;; For more about `CALM', please check: https://github.com/VitoVan/calm/
;; Of course, it lacks documentation by the time of now (Feb 2023),
;; and it is just a mix of cl-cairo2, cl-sdl2 and some other things.
;;
;; So, that's it. I will leave you to the code, and may you enjoy Lisp.
;;
(in-package #:calm)
;;
;; CALM version check
;;
(let ((required-version "1.1.0")
(calm-version (slot-value (asdf:find-system 'calm) 'asdf:version)))
(when (uiop:version< calm-version required-version)
(format t "Sorry, this is built on CALM ~A, older version (current: ~A) of CALM won't work.~%" required-version calm-version)
(uiop:quit 42)))
;; the swank server is for debugging, for usage please check
;; Emacs:
;; https://slime.common-lisp.dev/
;; Visual Studio Code
;; https://lispcookbook.github.io/cl-cookbook/vscode-alive.html
(unless (str:starts-with? "dist" (uiop:getenv "CALM_CMD"))
(swank:create-server))
;;
;; by default, the screensaver is disabled,
;; if you want to enable screensaver,
;; please uncomment the following line
;;
;; (setf (uiop:getenv "SDL_VIDEO_ALLOW_SCREENSAVER") "1")
;; setting window properties, for more of this, please check
;; https://github.com/VitoVan/calm/blob/main/src/config.lisp
(setf *calm-window-width* 300)
(setf *calm-window-height* 200)
(setf *calm-window-title* "Focalizzare")
;;
;; custom parameters
;;
(defparameter *bg-color* '(1 1 1))
(defparameter *fg-color* '(0 0 0))
(defparameter *fg-color-pause* (list (/ 142 255) (/ 142 255) (/ 142 255)))
(defparameter *button-color* '(0 0.35 0.59))
(defparameter *button-color-hover* '(0.89 0.12 0.17))
(defparameter *last-second* 0)
(defparameter *timer* (* 25 60))
(defparameter *round* 0)
(defparameter *pause* t)
(defparameter *breaking* nil)
(defparameter *breaking-timer* (* 5 60))
(defparameter *hovering-pause-resume-button* nil)
(defparameter *hovering-reset-button* nil)
(defparameter *show-help* nil)
;;
;; custom logic functions
;;
(defun stop-timer ()
(setf *pause* t)
(setf *last-second* 0))
(defun reset-timer ()
"this resets the timer, not the whole rounds, for that please check `reset-all'"
(format t "RESETING.... ~%")
(format t "ROUND: ~A BREAK: ~A~%" *round* *breaking*)
(if *breaking*
(if (= *round* 3)
(setf *breaking-timer* (* 20 60))
(setf *breaking-timer* (* 5 60)))
(setf *timer* (* 25 60))))
(defun reset-all ()
"reset everything"
(setf *breaking* nil)
(stop-timer)
(setf *round* 0)
(stop-timer)
(reset-timer))
(defun reset-round ()
(setf *round* 0))
(defun record-timer ()
(when (and (not *pause*) (= *last-second* 0))
(setf *last-second* (get-universal-time))))
(defun incf-timer ()
(when (not *pause*)
(c:open-audio-if-not-yet)
(let* ((curr-second (get-universal-time))
(duration (- curr-second *last-second*)))
;; when more than 1 second passed
(when ( >= duration 1)
(setf *last-second* curr-second)
(if *breaking*
(progn (incf *breaking-timer* (* -1 duration)) (when (< *breaking-timer* 0) (setf *breaking-timer* 0)))
(progn (incf *timer* (* -1 duration)) (when (< *timer* 0) (setf *timer* 0))))
(setf *calm-redraw* t))
;; when time is up
(when (<= (if *breaking* *breaking-timer* *timer*) 0)
(if *breaking*
;; if it's breaking, then finish the break
;; and increase the round
(progn
(setf *breaking* nil)
(if (< *round* 3)
(incf *round*)
(setf *round* 0)))
;; if it's not the breaking, then break
(setf *breaking* t))
;; either way, we need to reset the timer and pause
(reset-timer)
(stop-timer)
(when (zerop (sdl2-mixer:playing -1))
(if *breaking*
(c:play-music "assets/bell.ogg")
(c:play-music "assets/bell-break.ogg")))))))
;;
;; custom drawing functions
;;
(defun draw-circle (x y radius)
"draw the dot (round indicator)"
(c:new-sub-path)
(c:arc x y radius 0 (* pi 2)))
(defun draw-resume-button ()
(c:set-line-width 3)
(if *hovering-pause-resume-button*
(apply #'c:set-source-rgb *button-color-hover*)
(apply #'c:set-source-rgb *button-color*))
(c:move-to 55 138)
(c:rel-line-to 20 14)
(c:rel-line-to -20 14)
(c:rel-line-to 0 -20)
(c:close-path)
;; (c:rectangle 53 135 28 33)
(c:stroke))
(defun draw-pause-button ()
(c:set-line-width 3)
(if *hovering-pause-resume-button*
(apply #'c:set-source-rgb *button-color-hover*)
(apply #'c:set-source-rgb *button-color*))
(c:move-to 61 140)
(c:rel-line-to 0 25)
(c:rel-move-to 10 -25)
(c:rel-line-to 0 25)
(c:close-path)
(c:stroke))
(defun draw-reset-button ()
(c:set-line-width 3)
(c:set-line-cap :round)
(if *hovering-reset-button*
(apply #'c:set-source-rgb *button-color-hover*)
(apply #'c:set-source-rgb *button-color*))
(c:new-sub-path)
(c:arc-negative 230 150 10 (* pi 2.8) (* pi 1.05))
(c:rel-move-to -2 0)
(c:rel-line-to 10 0)
(c:rel-move-to -10 0)
(c:rel-line-to 0 -10)
(c:stroke))
(defun browse (url)
"open `url' in the default browser"
#+darwin
(uiop:run-program (str:concat "open " url))
#+linux
(uiop:run-program (str:concat "xdg-open " url))
#+win32
(uiop:run-program (str:concat "start " url)))
(defun window-is-on-top ()
(member :always-on-top (sdl2:get-window-flags *calm-window*)))
;;
;; events handling
;;
(defun on-keyup (key)
(cond
((c:keq key :SCANCODE-T)
(sdl2-ffi.functions:sdl-set-window-always-on-top
*calm-window*
(if (window-is-on-top) sdl2-ffi:+false+ sdl2-ffi:+true+)))
((c:keq key :SCANCODE-R)
(reset-all))
((c:keq key :SCANCODE-SPACE)
(progn (setf *pause* (not *pause*)) (when *pause* (stop-timer))))
((c:keq key :SCANCODE-SLASH)
(setf *show-help* t))
((c:keq key :SCANCODE-ESCAPE :SCANCODE-Q)
(setf *show-help* nil))
((c:keq key :SCANCODE-B)
(browse "https://vitovan.com/focalizzare"))
(t (format t "~%KEY PRESSED: ~A~%" key))))
(defun is-in-rectangle (x y rx ry rwidth rheight)
"to test if the mouse is inside an area, for testing CLICK and HOVER event"
(and
(> x rx) (> y ry)
(< x (+ rx rwidth))
(< y (+ ry rheight))))
(defun on-mousebuttonup (&key button x y clicks)
"clicking pause or resume button"
(declare (ignore button clicks))
(when (is-in-rectangle x y 53 135 28 33)
(setf *pause* (not *pause*))
(when *pause* (stop-timer)))
;; clicking reset button
(when (is-in-rectangle x y 215 135 30 30)
(reset-all)))
(defun think ()
"this method is called every `*calm-delay*' milliseconds, no matter what."
(record-timer)
(incf-timer))
(defun draw-forever ()
"this method is called every `*calm-delay*' milliseconds,
only when the window is not hidden or minimized."
#-linux
(c:select-font-face "Arial" :normal :normal)
#+linux
(c:select-font-face "Liberation Sans" :normal :normal)
(when *show-help*
(c:select-font-face "Courier" :normal :normal)
(c:set-font-size 18)
(apply #'c:set-source-rgb *button-color*)
(c:move-to 30 40)
(c:show-text "esc")
(c:move-to 120 40)
(c:show-text "close help")
(c:move-to 30 70)
(c:show-text "t")
(c:move-to 120 70)
(c:show-text "toggle on top")
(c:move-to 30 100)
(c:show-text "r")
(c:move-to 120 100)
(c:show-text "reset")
(c:move-to 30 130)
(c:show-text "space")
(c:move-to 120 130)
(c:show-text "start / pause")
(c:move-to 30 160)
(c:show-text "b")
(c:move-to 120 160)
(c:show-text "open homepage")
(c:move-to 50 180)
(apply #'c:set-source-rgb *button-color-hover*)
(return-from draw-forever 42))
(apply #'c:set-source-rgb *bg-color*)
(c:paint)
(if (or *pause* *breaking*)
(apply #'c:set-source-rgb *fg-color-pause*)
(apply #'c:set-source-rgb *fg-color*))
(c:move-to 22 100)
(c:set-font-size 100)
(let* ((time-string
(format nil
"~2,'0d:~2,'0d"
(floor (/ *timer* 60)) (mod *timer* 60)))
(time-chars
(coerce time-string
'list)))
(loop for x in time-chars
for c = (string x)
do (progn
(when (equal c ":")
(cairo:rel-move-to 0 -8))
(c:show-text c)
(when (equal c ":")
(c:rel-move-to 0 8))
(c:rel-move-to 2 0))))
(dotimes (i 4)
(let ((x (+ 120 (* i 20)))
(y 150)
(radius 5))
(draw-circle x y radius)
(if (<= i *round*)
(if (and (= i *round*) (not (= *timer* 0)))
;; if this is the current round indicator,
;; and this round is not finished
;; then update the status to 'half filled circle' or 'stroked circle'
(if (< *timer* (* 25 60))
;; if it has started, then fill half cirle
(progn
(c:stroke)
(c:new-sub-path)
(c:arc x y radius (* pi 0.5) (* pi 1.5))
(c:fill-path))
;; if the timer hasn't started yet, stroke
(c:stroke))
;; if this is the previous round(s),
;; or the current *timer* is 0 (finished)
;; then fill the indicator
(c:fill-path))
(c:stroke))))
(when *breaking*
(c:set-source-rgba 0 0 0 1)
(c:move-to 240 25)
(c:set-font-size 20)
(c:show-text
(format nil "~2,'0d:~2,'0d" (floor (/ *breaking-timer* 60)) (mod *breaking-timer* 60))))
;; test the hover states of buttons
(setf *hovering-pause-resume-button* (is-in-rectangle *calm-state-mouse-x* *calm-state-mouse-y* 53 135 28 33))
(setf *hovering-reset-button* (is-in-rectangle *calm-state-mouse-x* *calm-state-mouse-y* 215 135 30 30))
(if *pause*
(draw-resume-button)
(draw-pause-button))
(draw-reset-button)
(setf *calm-redraw* nil))
| 11,082 | Common Lisp | .lisp | 317 | 29.640379 | 129 | 0.6101 | VitoVan/focalizzare | 8 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | be6ac1be937db6e39a01790d1625139e03788c01ba726d870705a1ae11092182 | 12,289 | [
-1
] |
12,291 | index.html | VitoVan_focalizzare/index.html | <!DOCTYPE html>
<html>
<head>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-SJ5CP8DCH9"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-SJ5CP8DCH9');
</script>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width initial-scale=1" />
<title>Focalizzare</title>
<link
rel="apple-touch-icon"
sizes="180x180"
href="./images/apple-touch-icon.png"
/>
<link
rel="icon"
type="image/png"
sizes="32x32"
href="./images/favicon-32x32.png"
/>
<link
rel="icon"
type="image/png"
sizes="16x16"
href="./images/favicon-16x16.png"
/>
<link rel="manifest" href="./images/site.webmanifest" />
<link
rel="mask-icon"
href="./images/safari-pinned-tab.svg"
color="#f2de65"
/>
<link rel="shortcut icon" href="./images/favicon.ico" />
<meta name="msapplication-TileColor" content="#2b5797" />
<meta name="msapplication-config" content="./images/browserconfig.xml" />
<meta name="theme-color" content="#ffffff" />
<style type="text/css">
html {
overflow-x: initial !important;
}
:root {
--bg-color: #ffffff;
--text-color: #333333;
--select-text-bg-color: #b5d6fc;
--select-text-font-color: auto;
--monospace: 'Lucida Console', Consolas, 'Courier', monospace;
}
html {
font-size: 14px;
background-color: var(--bg-color);
color: var(--text-color);
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
}
body {
min-width: 840;
margin: 0px;
padding: 0px;
height: auto;
inset: 0px;
font-size: 1rem;
line-height: 1.42857143;
overflow-x: hidden;
background-image: inherit;
background-size: inherit;
background-attachment: inherit;
background-origin: inherit;
background-clip: inherit;
background-color: inherit;
tab-size: 4;
background-position: inherit;
background-repeat: inherit;
}
iframe {
margin: auto;
}
a.url {
word-break: break-all;
}
a:active,
a:hover {
outline: 0px;
}
.in-text-selection,
::selection {
text-shadow: none;
background: var(--select-text-bg-color);
color: var(--select-text-font-color);
}
#write {
margin: 0px auto;
height: auto;
width: inherit;
word-break: normal;
word-wrap: break-word;
position: relative;
white-space: normal;
overflow-x: visible;
padding-top: 40px;
}
#write.first-line-indent p {
text-indent: 2em;
}
#write.first-line-indent li p,
#write.first-line-indent p * {
text-indent: 0px;
}
#write.first-line-indent li {
margin-left: 2em;
}
.for-image #write {
padding-left: 8px;
padding-right: 8px;
}
body.typora-export {
padding-left: 30px;
padding-right: 30px;
}
.typora-export .footnote-line,
.typora-export li,
.typora-export p {
white-space: pre-wrap;
}
@media screen and (max-width: 500px) {
body.typora-export {
padding-left: 0px;
padding-right: 0px;
}
#write {
padding-left: 20px;
padding-right: 20px;
}
.CodeMirror-sizer {
margin-left: 0px !important;
}
.CodeMirror-gutters {
display: none !important;
}
}
#write li > figure:last-child {
margin-bottom: 0.5rem;
}
#write ol,
#write ul {
position: relative;
}
img {
max-width: 100%;
vertical-align: middle;
image-orientation: from-image;
}
button,
input,
select,
textarea {
color: inherit;
font-family: inherit;
font-size: inherit;
font-style: inherit;
font-variant-caps: inherit;
font-weight: inherit;
font-stretch: inherit;
line-height: inherit;
}
input[type='checkbox'],
input[type='radio'] {
line-height: normal;
padding: 0px;
}
*,
::after,
::before {
box-sizing: border-box;
}
#write h1,
#write h2,
#write h3,
#write h4,
#write h5,
#write h6,
#write p,
#write pre {
width: inherit;
}
#write h1,
#write h2,
#write h3,
#write h4,
#write h5,
#write h6,
#write p {
position: relative;
}
p {
line-height: inherit;
}
h1,
h2,
h3,
h4,
h5,
h6 {
break-after: avoid-page;
break-inside: avoid;
orphans: 4;
}
p {
orphans: 4;
}
h1 {
font-size: 2rem;
}
h2 {
font-size: 1.8rem;
}
h3 {
font-size: 1.6rem;
}
h4 {
font-size: 1.4rem;
}
h5 {
font-size: 1.2rem;
}
h6 {
font-size: 1rem;
}
.md-math-block,
.md-rawblock,
h1,
h2,
h3,
h4,
h5,
h6,
p {
margin-top: 1rem;
margin-bottom: 1rem;
}
.hidden {
display: none;
}
.md-blockmeta {
color: rgb(204, 204, 204);
font-weight: 700;
font-style: italic;
}
a {
cursor: pointer;
}
sup.md-footnote {
padding: 2px 4px;
background-color: rgba(238, 238, 238, 0.7);
color: rgb(85, 85, 85);
border-radius: 4px;
cursor: pointer;
}
sup.md-footnote a,
sup.md-footnote a:hover {
color: inherit;
text-transform: inherit;
text-decoration: inherit;
}
#write input[type='checkbox'] {
cursor: pointer;
width: inherit;
height: inherit;
}
figure {
overflow-x: auto;
margin: 1.2em 0px;
max-width: calc(100% + 16px);
padding: 0px;
}
figure > table {
margin: 0px;
}
tr {
break-inside: avoid;
break-after: auto;
}
thead {
display: table-header-group;
}
table {
border-collapse: collapse;
border-spacing: 0px;
width: 100%;
overflow: auto;
break-inside: auto;
text-align: left;
}
table.md-table td {
min-width: 32px;
}
.CodeMirror-gutters {
border-right-width: 0px;
background-color: inherit;
}
.CodeMirror-linenumber {
}
.CodeMirror {
text-align: left;
}
.CodeMirror-placeholder {
opacity: 0.3;
}
.CodeMirror pre {
padding: 0px 4px;
}
.CodeMirror-lines {
padding: 0px;
}
div.hr:focus {
cursor: none;
}
#write pre {
white-space: pre-wrap;
}
#write.fences-no-line-wrapping pre {
white-space: pre;
}
#write pre.ty-contain-cm {
white-space: normal;
}
.CodeMirror-gutters {
margin-right: 4px;
}
.md-fences {
font-size: 0.9rem;
display: block;
break-inside: avoid;
text-align: left;
overflow: visible;
white-space: pre;
background-image: inherit;
background-size: inherit;
background-attachment: inherit;
background-origin: inherit;
background-clip: inherit;
background-color: inherit;
position: relative !important;
background-position: inherit;
background-repeat: inherit;
}
.md-diagram-panel {
width: 100%;
margin-top: 10px;
text-align: center;
padding-top: 0px;
padding-bottom: 8px;
overflow-x: auto;
}
#write .md-fences.mock-cm {
white-space: pre-wrap;
}
.md-fences.md-fences-with-lineno {
padding-left: 0px;
}
#write.fences-no-line-wrapping .md-fences.mock-cm {
white-space: pre;
overflow-x: auto;
}
.md-fences.mock-cm.md-fences-with-lineno {
padding-left: 8px;
}
.CodeMirror-line,
twitterwidget {
break-inside: avoid;
}
.footnotes {
opacity: 0.8;
font-size: 0.9rem;
margin-top: 1em;
margin-bottom: 1em;
}
.footnotes + .footnotes {
margin-top: 0px;
}
.md-reset {
margin: 0px;
padding: 0px;
border: 0px;
outline: 0px;
vertical-align: top;
text-decoration: none;
text-shadow: none;
float: none;
position: static;
width: auto;
height: auto;
white-space: nowrap;
cursor: inherit;
line-height: normal;
font-weight: 400;
text-align: left;
box-sizing: content-box;
direction: ltr;
background-position: 0px 0px;
}
li div {
padding-top: 0px;
}
blockquote {
margin: 1rem 0px;
}
li .mathjax-block,
li p {
margin: 0.5rem 0px;
}
li {
margin: 0px;
position: relative;
}
blockquote > :last-child {
margin-bottom: 0px;
}
blockquote > :first-child,
li > :first-child {
margin-top: 0px;
}
.footnotes-area {
color: rgb(136, 136, 136);
margin-top: 0.714rem;
padding-bottom: 0.143rem;
white-space: normal;
}
#write .footnote-line {
white-space: pre-wrap;
}
@media print {
body,
html {
border: 1px solid transparent;
height: 99%;
break-after: avoid;
break-before: avoid;
font-variant-ligatures: no-common-ligatures;
}
#write {
margin-top: 0px;
padding-top: 0px;
border-color: transparent !important;
}
.typora-export * {
print-color-adjust: exact;
}
html.blink-to-pdf {
font-size: 13px;
}
.typora-export #write {
padding-left: 32px;
padding-right: 32px;
padding-bottom: 0px;
break-after: avoid;
}
.typora-export #write::after {
height: 0px;
}
.is-mac table {
break-inside: avoid;
}
}
.footnote-line {
margin-top: 0.714em;
font-size: 0.7em;
}
a img,
img a {
cursor: pointer;
}
pre.md-meta-block {
font-size: 0.8rem;
min-height: 0.8rem;
white-space: pre-wrap;
background-color: rgb(204, 204, 204);
display: block;
overflow-x: hidden;
}
p > .md-image:only-child:not(.md-img-error) img,
p > img:only-child {
display: block;
margin: auto;
}
#write.first-line-indent p > .md-image:only-child:not(.md-img-error) img {
left: -2em;
position: relative;
}
p > .md-image:only-child {
display: inline-block;
width: 100%;
}
#write .MathJax_Display {
margin: 0.8em 0px 0px;
}
.md-math-block {
width: 100%;
}
.md-math-block:not(:empty)::after {
display: none;
}
[contenteditable='true']:active,
[contenteditable='true']:focus,
[contenteditable='false']:active,
[contenteditable='false']:focus {
outline: 0px;
box-shadow: none;
}
.md-task-list-item {
position: relative;
list-style-type: none;
}
.task-list-item.md-task-list-item {
padding-left: 0px;
}
.md-task-list-item > input {
position: absolute;
top: 0px;
left: 0px;
margin-left: -1.2em;
margin-top: calc(1em - 10px);
border: none;
}
.math {
font-size: 1rem;
}
.md-toc {
min-height: 3.58rem;
position: relative;
font-size: 0.9rem;
border-radius: 10px;
}
.md-toc-content {
position: relative;
margin-left: 0px;
}
.md-toc-content::after,
.md-toc::after {
display: none;
}
.md-toc-item {
display: block;
color: rgb(65, 131, 196);
}
.md-toc-item a {
text-decoration: none;
}
.md-toc-inner:hover {
text-decoration: underline;
}
.md-toc-inner {
display: inline-block;
cursor: pointer;
}
.md-toc-h1 .md-toc-inner {
margin-left: 0px;
font-weight: 700;
}
.md-toc-h2 .md-toc-inner {
margin-left: 2em;
}
.md-toc-h3 .md-toc-inner {
margin-left: 4em;
}
.md-toc-h4 .md-toc-inner {
margin-left: 6em;
}
.md-toc-h5 .md-toc-inner {
margin-left: 8em;
}
.md-toc-h6 .md-toc-inner {
margin-left: 10em;
}
@media screen and (max-width: 48em) {
.md-toc-h3 .md-toc-inner {
margin-left: 3.5em;
}
.md-toc-h4 .md-toc-inner {
margin-left: 5em;
}
.md-toc-h5 .md-toc-inner {
margin-left: 6.5em;
}
.md-toc-h6 .md-toc-inner {
margin-left: 8em;
}
}
a.md-toc-inner {
font-size: inherit;
font-style: inherit;
font-weight: inherit;
line-height: inherit;
}
.footnote-line a:not(.reversefootnote) {
color: inherit;
}
.md-attr {
display: none;
}
.md-fn-count::after {
content: '.';
}
code,
pre,
samp,
tt {
font-family: var(--monospace);
}
kbd {
margin: 0px 0.1em;
padding: 0.1em 0.6em;
font-size: 0.8em;
color: rgb(36, 39, 41);
background-color: rgb(255, 255, 255);
border: 1px solid rgb(173, 179, 185);
border-radius: 3px;
box-shadow: rgba(12, 13, 14, 0.2) 0px 1px 0px,
rgb(255, 255, 255) 0px 0px 0px 2px inset;
white-space: nowrap;
vertical-align: middle;
}
.md-comment {
color: rgb(162, 127, 3);
opacity: 0.8;
font-family: var(--monospace);
}
code {
text-align: left;
}
a.md-print-anchor {
white-space: pre !important;
border: none !important;
display: inline-block !important;
position: absolute !important;
width: 1px !important;
right: 0px !important;
outline: 0px !important;
text-shadow: initial !important;
background-position: 0px 0px !important;
}
.md-inline-math .MathJax_SVG .noError {
display: none !important;
}
.html-for-mac .inline-math-svg .MathJax_SVG {
vertical-align: 0.2px;
}
.md-math-block .MathJax_SVG_Display {
text-align: center;
margin: 0px;
position: relative;
text-indent: 0px;
max-width: none;
max-height: none;
min-height: 0px;
min-width: 100%;
width: auto;
overflow-y: hidden;
display: block !important;
}
.MathJax_SVG_Display,
.md-inline-math .MathJax_SVG_Display {
width: auto;
margin: inherit;
display: inline-block !important;
}
.MathJax_SVG .MJX-monospace {
font-family: var(--monospace);
}
.MathJax_SVG .MJX-sans-serif {
font-family: sans-serif;
}
.MathJax_SVG {
display: inline;
font-style: normal;
font-weight: 400;
line-height: normal;
zoom: 90%;
text-indent: 0px;
text-align: left;
text-transform: none;
letter-spacing: normal;
word-spacing: normal;
word-wrap: normal;
white-space: nowrap;
float: none;
direction: ltr;
max-width: none;
max-height: none;
min-width: 0px;
min-height: 0px;
border: 0px;
padding: 0px;
margin: 0px;
}
.MathJax_SVG * {
transition: none 0s ease 0s;
}
.MathJax_SVG_Display svg {
vertical-align: middle !important;
margin-bottom: 0px !important;
margin-top: 0px !important;
}
.os-windows.monocolor-emoji .md-emoji {
font-family: 'Segoe UI Symbol', sans-serif;
}
.md-diagram-panel > svg {
max-width: 100%;
}
[lang='flow'] svg,
[lang='mermaid'] svg {
max-width: 100%;
height: auto;
}
[lang='mermaid'] .node text {
font-size: 1rem;
}
table tr th {
border-bottom-width: 0px;
}
video {
max-width: 100%;
display: block;
margin: 0px auto;
}
iframe {
max-width: 100%;
width: 100%;
border: none;
}
.highlight td,
.highlight tr {
border: 0px;
}
svg[id^='mermaidChart'] {
line-height: 1em;
}
mark {
background-color: rgb(255, 255, 0);
color: rgb(0, 0, 0);
}
.md-html-inline .md-plain,
.md-html-inline strong,
mark .md-inline-math,
mark strong {
color: inherit;
}
mark .md-meta {
color: rgb(0, 0, 0);
opacity: 0.3 !important;
}
:root {
--side-bar-bg-color: #fafafa;
--control-text-color: #777;
}
html {
font-size: 16px;
}
body {
font-family: 'Open Sans', 'Clear Sans', Arial, 'Helvetica Neue', Helvetica,
Arial, sans-serif;
color: rgb(51, 51, 51);
line-height: 1.6;
}
#write {
max-width: 860px;
margin: 0 auto;
padding: 30px;
padding-bottom: 100px;
}
@media only screen and (min-width: 1400px) {
#write {
max-width: 1024px;
}
}
@media only screen and (min-width: 1800px) {
#write {
max-width: 1200px;
}
}
#write > ul:first-child,
#write > ol:first-child {
margin-top: 30px;
}
a {
color: #4183c4;
text-decoration: none;
}
a.buy:hover {
color: #f4171e;
}
h1,
h2,
h3,
h4,
h5,
h6 {
position: relative;
margin-top: 1rem;
margin-bottom: 1rem;
font-weight: bold;
line-height: 1.4;
cursor: text;
}
h1:hover a.anchor,
h2:hover a.anchor,
h3:hover a.anchor,
h4:hover a.anchor,
h5:hover a.anchor,
h6:hover a.anchor {
text-decoration: none;
}
h1 tt,
h1 code {
font-size: inherit;
}
h2 tt,
h2 code {
font-size: inherit;
}
h3 tt,
h3 code {
font-size: inherit;
}
h4 tt,
h4 code {
font-size: inherit;
}
h5 tt,
h5 code {
font-size: inherit;
}
h6 tt,
h6 code {
font-size: inherit;
}
h1 {
padding-bottom: 0.3em;
font-size: 2.25em;
line-height: 1.2;
border-bottom: 1px solid #eee;
}
h2 {
padding-bottom: 0.3em;
font-size: 1.75em;
line-height: 1.225;
border-bottom: 1px solid #eee;
}
h3 {
font-size: 1.5em;
line-height: 1.43;
}
h4 {
font-size: 1.25em;
}
h5 {
font-size: 1em;
}
h6 {
font-size: 1em;
color: #777;
}
p,
blockquote,
ul,
ol,
dl,
table {
margin: 0.8em 0;
}
li > ol,
li > ul {
margin: 0 0;
}
hr {
height: 2px;
padding: 0;
margin: 16px 0;
background-color: #e7e7e7;
border: 0 none;
overflow: hidden;
box-sizing: content-box;
}
li p.first {
display: inline-block;
}
ul,
ol {
padding-left: 30px;
}
ul:first-child,
ol:first-child {
margin-top: 0;
}
ul:last-child,
ol:last-child {
margin-bottom: 0;
}
blockquote {
border-left: 4px solid #dfe2e5;
padding: 0 15px;
color: #777777;
}
blockquote blockquote {
padding-right: 0;
}
table {
padding: 0;
word-break: initial;
}
table tr {
border-top: 1px solid #dfe2e5;
margin: 0;
padding: 0;
}
table tr:nth-child(2n),
thead {
background-color: #f8f8f8;
}
table tr th {
font-weight: bold;
border: 1px solid #dfe2e5;
border-bottom: 0;
margin: 0;
padding: 6px 13px;
}
table tr td {
border: 1px solid #dfe2e5;
margin: 0;
padding: 6px 13px;
}
table tr th:first-child,
table tr td:first-child {
margin-top: 0;
}
table tr th:last-child,
table tr td:last-child {
margin-bottom: 0;
}
.CodeMirror-lines {
padding-left: 4px;
}
.code-tooltip {
box-shadow: 0 1px 1px 0 rgba(0, 28, 36, 0.3);
border-top: 1px solid #eef2f2;
}
.md-fences,
code,
tt {
border: 1px solid #e7eaed;
background-color: #f8f8f8;
border-radius: 3px;
padding: 0;
padding: 2px 4px 0px 4px;
font-size: 0.9em;
}
code {
background-color: #f3f4f4;
padding: 0 2px 0 2px;
}
.md-fences {
margin-bottom: 15px;
margin-top: 15px;
padding-top: 8px;
padding-bottom: 6px;
}
.md-task-list-item > input {
margin-left: -1.3em;
}
@media print {
html {
font-size: 13px;
}
table,
pre {
page-break-inside: avoid;
}
pre {
word-wrap: break-word;
}
}
.md-fences {
background-color: #f8f8f8;
}
#write pre.md-meta-block {
padding: 1rem;
font-size: 85%;
line-height: 1.45;
background-color: #f7f7f7;
border: 0;
border-radius: 3px;
color: #777777;
margin-top: 0 !important;
}
.mathjax-block > .code-tooltip {
bottom: 0.375rem;
}
.md-mathjax-midline {
background: #fafafa;
}
#write > h3.md-focus:before {
left: -1.5625rem;
top: 0.375rem;
}
#write > h4.md-focus:before {
left: -1.5625rem;
top: 0.285714286rem;
}
#write > h5.md-focus:before {
left: -1.5625rem;
top: 0.285714286rem;
}
#write > h6.md-focus:before {
left: -1.5625rem;
top: 0.285714286rem;
}
.md-image > .md-meta {
/*border: 1px solid #ddd;*/
border-radius: 3px;
padding: 2px 0px 0px 4px;
font-size: 0.9em;
color: inherit;
}
.md-tag {
color: #a7a7a7;
opacity: 1;
}
.md-toc {
margin-top: 20px;
padding-bottom: 20px;
}
.sidebar-tabs {
border-bottom: none;
}
#typora-quick-open {
border: 1px solid #ddd;
background-color: #f8f8f8;
}
#typora-quick-open-item {
background-color: #fafafa;
border-color: #fefefe #e5e5e5 #e5e5e5 #eee;
border-style: solid;
border-width: 1px;
}
/** focus mode */
.on-focus-mode blockquote {
border-left-color: rgba(85, 85, 85, 0.12);
}
header,
.context-menu,
.megamenu-content,
footer {
font-family: 'Segoe UI', 'Arial', sans-serif;
}
.file-node-content:hover .file-node-icon,
.file-node-content:hover .file-node-open-state {
visibility: visible;
}
.mac-seamless-mode #typora-sidebar {
background-color: #fafafa;
background-color: var(--side-bar-bg-color);
}
.md-lang {
color: #b4654d;
}
.html-for-mac .context-menu {
--item-hover-bg-color: #e6f0fe;
}
#md-notification .btn {
border: 0;
}
.dropdown-menu .divider {
border-color: #e5e5e5;
}
.ty-preferences .window-content {
background-color: #fafafa;
}
.ty-preferences .nav-group-item.active {
color: white;
background: #999;
}
.typora-export li,
.typora-export p,
.typora-export,
.footnote-line {
white-space: normal;
}
</style>
</head>
<body class="typora-export">
<div id="write" class="">
<h1>
<img
style="vertical-align:middle;margin-right:10px;width:60px;"
alt="Focalizzare"
src="./images/icon-head.png"
/><span> Focalizzare</span>
</h1>
<p>
<span>A Timer for Pomodoro Technique.</span>
<a
style="float:right;"
href="https://github.com/VitoVan/focalizzare/"
><span><img alt="GitHub - Source" src="https://img.shields.io/badge/git-src-white?logo=github"> </span></a
>
</p>
<p style="text-align:center;">
<img
width="40%"
alt="Focalizzare Paused"
src="./images/25-minutes.png"
/><span> </span
><img
width="40%"
alt="Focalizzare Running"
src="./images/24-minutes.png"
/>
</p>
<p>
<span>Usage: <b>press ? for help</b></span>
</p>
<p> </p>
<p><span>Download:</span></p>
<p>
<a
href="https://github.com/VitoVan/focalizzare/releases/latest/download/Focalizzare.AppImage"
><img src="https://img.shields.io/badge/Linux-glibc%202.31+-FFD032.svg?logo=linux" alt="Focalizzare.AppImage"/></a>
<span> </span>
<a href="https://github.com/VitoVan/focalizzare/releases/latest/download/Focalizzare.macos-14.dmg">
<img src="https://img.shields.io/badge/macOS-Sonoma-black?logo=apple" alt="Focalizzare.dmg"/>
</a>
<span> </span>
<a href="https://github.com/VitoVan/focalizzare/releases/latest/download/Focalizzare.exe">
<img src="https://img.shields.io/badge/Windows-Windows%2010/11-017fd5.svg?logo=windows" alt="Focalizzare.AppImage"/>
</a>
<span> </span>
<a href="https://github.com/VitoVan/focalizzare/releases/latest/download/Focalizzare.macos-13.dmg">
<img src="https://img.shields.io/badge/macOS-Ventura-white?logo=apple" alt="Focalizzare.dmg"/>
</a>
<span> </span>
<a href="https://github.com/VitoVan/focalizzare/releases/latest/download/Focalizzare.macos-12.dmg">
<img src="https://img.shields.io/badge/macOS-Monterey-white?logo=apple" alt="Focalizzare.macos-12.dmg"/>
</a>
<span> </span>
</p>
<p> </p>
<p>
<a href="https://en.wiktionary.org/wiki/focalizzare"
><span>Focalizzàre</span></a
><span>: /fo.ka.lidˈd͡za.re/, to put into </span
><strong><span>focus</span></strong>
</p>
<p>
<a href="https://en.wiktionary.org/wiki/pomodoro"
><span>Pomodoro</span></a
><span>: /ˌpo.moˈdɔ.ro/, </span><strong><span>tomato</span></strong>
</p>
<p> </p>
<p>
<a href="https://en.wikipedia.org/wiki/Pomodoro_Technique"
><span>Pomodoro Technique</span></a
><span> in short:</span>
</p>
<ol start="">
<li><span>Decide a task</span></li>
<li><span>Work for 25 minutes</span></li>
<li><span>Break for 5 minutes</span></li>
<li>
<span
>Repeat 2-3, if it comes to the 4th break, make it 20 minutes</span
>
</li>
</ol>
<p> </p>
<p>
<span>Made with </span
><a href="https://vitovan.com/jack.html"
><span>Hemorrhoid</span></a
><span> and </span
><a href="https://github.com/VitoVan/calm"><span>CALM</span></a>
<a
style="float:right;"
href="https://github.com/VitoVan/focalizzare/blob/main/assets/ATTRIBUTION.md"
><span>attribution</span></a
>
</p>
<p> </p>
</div>
</body>
</html>
| 29,115 | Common Lisp | .l | 1,194 | 16.260469 | 126 | 0.512549 | VitoVan/focalizzare | 8 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 99347c6670d31546d6e892fde4233b161e8ea0a8f999d1e729da194ea41aaf9d | 12,291 | [
-1
] |
12,293 | browserconfig.xml | VitoVan_focalizzare/images/browserconfig.xml | <?xml version="1.0" encoding="utf-8"?>
<browserconfig>
<msapplication>
<tile>
<square150x150logo src="/mstile-150x150.png"/>
<TileColor>#b91d47</TileColor>
</tile>
</msapplication>
</browserconfig>
| 246 | Common Lisp | .l | 9 | 21 | 58 | 0.607595 | VitoVan/focalizzare | 8 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 78a5ac0c16453500c1a8f0ce1a81fadbac1150392add4c4249c9058c35a9411d | 12,293 | [
-1
] |
12,294 | FUNDING.yml | VitoVan_focalizzare/.github/FUNDING.yml | # These are supported funding model platforms
github: VitoVan # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
custom:
| 740 | Common Lisp | .l | 12 | 60.5 | 93 | 0.803301 | VitoVan/focalizzare | 8 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | caf27d88f5cda7deb0a89b050247f6446fa40d56fff6052d0b504ebbfb028e2c | 12,294 | [
-1
] |
12,295 | build.yml | VitoVan_focalizzare/.github/workflows/build.yml | name: build
permissions:
contents: write
on:
push:
tags:
- "*.*.*"
- "test-*"
jobs:
Linux:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v3
- name: Build
run: |
set -x
curl -L -o calm.tgz https://github.com/VitoVan/calm/releases/download/1.3.2/calm.tgz
mkdir calm
tar xvf calm.tgz
ls -lah calm
export PATH=$PATH:$(pwd)/calm/
export APP_NAME=Focalizzare
export APP_ICON="$(pwd)/images/icon.png"
calm publish
ls -lah .
- name: GH Release
uses: softprops/[email protected]
with:
draft: true
files: |
*.AppImage
macOS:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [macos-12, macos-13, macos-14]
env:
CI_MATRIX_OS: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- name: Build
run: |
set -x
export OS_SUBFIX=".${CI_MATRIX_OS}"
curl -L -o calm.dmg https://github.com/VitoVan/calm/releases/download/1.3.2/calm${OS_SUBFIX}.dmg
hdiutil attach calm.dmg
cp -R "/Volumes/Calm - CALM/Calm.app/Contents/MacOS/" calm
ls -lah calm
rm calm.dmg
export PATH=$PATH:$(pwd)/calm/
export APP_ICON="$(pwd)/images/icon.icns"
export DMG_ICON="$(pwd)/images/icon-dmg.icns"
export APP_VERSION=1.1.3
export APP_ID=com.vitovan.focalizzare
export APP_NAME=Focalizzare
calm publish
ls -lah .
mv *.dmg Focalizzare${OS_SUBFIX}.dmg
- name: GH Release
uses: softprops/[email protected]
with:
draft: true
files: |
*.dmg
Windows:
runs-on: windows-latest
steps:
- uses: actions/checkout@v3
- uses: msys2/setup-msys2@v2
- name: Build
shell: msys2 {0}
run: |
set -x
pacman -S --noconfirm --needed unzip
curl -L -o calm.zip https://github.com/VitoVan/calm/releases/download/1.3.2/calm.zip
unzip calm.zip
ls -lah calm
export PATH=$PATH:$(pwd)/calm/
export APP_ICON="$(pwd)/images/icon.ico"
export APP_NAME=Focalizzare
calm publish
mv ./*-Installer.exe ./Focalizzare.exe
ls -lah .
- name: GH Release
uses: softprops/[email protected]
with:
draft: true
files: |
*.exe
| 2,562 | Common Lisp | .l | 89 | 19.921348 | 106 | 0.542125 | VitoVan/focalizzare | 8 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 7da3cae1f672b604cfd0da1614599a739d70228a1895ac486e18696ba17dae40 | 12,295 | [
-1
] |
12,310 | builder.lisp | informatimago_commands/builder.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: builder.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Builder script for the commands executable.
;;;; This scripts compiles and load all commands
;;;; and their dependencies.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2021-06-02 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2021 - 2021
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(in-package "COM.INFORMATIMAGO.COMMAND.GENERATE")
(defvar *verbose* t)
;;; --------------------------------------------------------------------
(when *verbose* (format *trace-output* "builder.lisp: ~S~%" '(ql:quickload :com.informatimago.common-lisp.cesarum)))
(ql:quickload :com.informatimago.common-lisp.cesarum)
(when *verbose* (format *trace-output* "builder.lisp: ~S~%" '(cl:defpackage "COM.INFORMATIMAGO.COMMAND.GENERATE.E48")))
(cl:defpackage "COM.INFORMATIMAGO.COMMAND.GENERATE.E48"
(:use)
(:export "ACK" "APC" "BEL" "BPH" "BS" "CAN" "CBT" "CCH" "CHA" "CHT"
"CMD" "CNL" "CPL" "CPR" "CR" "CSI" "CTC" "CUB" "CUD" "CUF"
"CUP" "CUU" "CVT" "DA" "DAQ" "DC1" "DC2" "DC3" "DC4" "DCH"
"DCS" "DL" "DLE" "DMI" "DSR" "DTA" "EA" "ECH" "ED" "EF"
"EL" "EM" "EMI" "ENQ" "EOT" "EPA" "ESA" "ESC" "ETB" "ETX"
"FF" "FNK" "FNT" "GCC" "GSM" "GSS" "HPA" "HPB" "HPR" "HT"
"HTJ" "HTS" "HVP" "ICH" "IDCS" "IGS" "IL" "INT" "IS1" "IS2"
"IS3" "IS4" "JFY" "LF" "LS0" "LS1" "LS2" "LS3" "MC" "MW"
"NAK" "NBH" "NEL" "NP" "NUL" "OSC" "PEC" "PFS" "PLD" "PLU"
"PM" "PP" "PPA" "PPB" "PPR" "PTX" "PU1" "PU2" "QUAD" "REP"
"RI" "RIS" "RM" "SACS" "SAPV" "SCI" "SCO" "SCP" "SCS" "SD"
"SDS" "SEE" "SEF" "SGR" "SHS" "SI" "SIMD" "SL" "SLH" "SLL"
"SLS" "SM" "SO" "SOH" "SOS" "SPA" "SPD" "SPH" "SPI" "SPL"
"SPQR" "SR" "SRCS" "SRS" "SS2" "SS3" "SSA" "SSU" "SSW" "ST"
"STAB" "STS" "STX" "SU" "SUB" "SVS" "SYN" "TAC" "TALE"
"TATE" "TBC" "TCC" "TSR" "TSS" "VPA" "VPB" "VPR" "VT"
"VTS"))
(cl:in-package "COM.INFORMATIMAGO.COMMAND.GENERATE.E48")
(cl:eval-when (:compile-toplevel :load-toplevel :execute)
(com.informatimago.common-lisp.cesarum.ecma048:define-all-functions
:export cl:t :8-bit cl:nil :print cl:nil :result-type cl:string))
;;; --------------------------------------------------------------------
;;; generate the program
;;;
(cl:in-package "COM.INFORMATIMAGO.COMMAND.GENERATE")
(import 'com.informatimago.command.generate.e48:sgr)
(defconstant normal 0)
(defconstant black 30)
(defconstant red 31)
(defconstant green 32)
(defconstant yellow 33)
(defconstant blue 34)
(defconstant magenta 35)
(defconstant cyan 36)
(defconstant white 37)
(defconstant black-back 40)
(defconstant red-back 41)
(defconstant green-back 42)
(defconstant yellow-back 43)
(defconstant blue-back 44)
(defconstant magenta-back 45)
(defconstant cyan-back 46)
(defconstant white-back 47)
(defparameter *all-commands*
'("add-cookie" "add-paths" "ansi-test" "batch-emerge"
"bin-to-c-array" "buzzword" "capitalize"
"cddb-to-tag" "check-surface" "clar"
"clean-bd-archive" "clean-name" ;; "clean-paths"
"commands"
"columnify" "cookie-diff" "cookie-loop"
"cookie-merge" "cookie" "dedup"
"departement" "diss" "downcase"
"edit-comments-of-ogg" "entropy" "euronews"
"extend-identifiers" "fetch-pop" "fpm"
"get-directory" "group-files"
"hexbin"
"html-make-image-index" "insulte" "kwic" "lc" "llen"
"lrev" "macosx-port-uninstall-recursively" "memo"
"menu" "merge" "mfod" "new-password" "news-to-mbox"
"nls" "one-of" "pic-resize" "pjb-diff" "programmer"
"pseudo-pop" "radio" "random"
"religion" "remove-duplicate-files" "revlines"
"rotate" "rstuml"
"script-test"
"sleep-schedule" "split-dir"
"split-merge" "substitute" "surveille-host"
"surveille-web-pages" "svn-locate-revision" "text"
"when")
#-(and) '("box" "cpcd" "shell"))
(dolist (name *all-commands*)
(ignore-errors (delete-package (command-package-name name))))
;;; Scan command sources for command :use-systems forms.
(defun register-commands ()
(let ((*default-pathname-defaults* (merge-pathnames (make-pathname :directory '(:relative "commands")
:name nil
:type "lisp"
:version nil)
cl-user::*source-directory*)))
(dolist (name *all-commands*)
(register-command-file name (merge-pathnames name *default-pathname-defaults* nil)))))
;;; Quickload used systems:
(defun quickload-command-dependencies ()
(ql:quickload (delete-duplicates
(mapcan (lambda (name) (copy-list (command-use-systems (command-named name))))
*all-commands*))))
;;; Compile and load all commands:
(defparameter *failures* 0)
(defun compile-and-load-command (name)
(handler-case
(let* ((package (command-package name))
(command (command-named name)))
(if (let ((type (and (find-package "SWANK/GRAY")
(find-symbol "SLIME-OUTPUT-STREAM" "SWANK/GRAY"))))
(and type (typep *standard-output* type)))
(format t "~&;Processing ~A in package ~A~%"
name (package-name package))
(format t "~&;Processing ~A~A~A in package ~A~A~A~%"
(sgr blue) name (sgr normal)
(sgr cyan) (package-name package) (sgr normal)))
(finish-output)
(multiple-value-bind (fasl warnings-p failure-p)
(let ((*program-name* name)
(*package* package))
(with-compilation-unit (:override t)
(compile-file (command-pathname command) :verbose t)))
(if (or warnings-p failure-p)
(progn
(format t "~&;Failed to compile ~S~%" (command-pathname command))
(incf *failures*))
(if (let ((*program-name* name)
(*package* package))
(load fasl :verbose t))
(format t "~&;Successfully loaded ~S~%" fasl)
(progn
(format t "~&;Failed to load ~S~%" (command-pathname command))
(incf *failures*))))))
(error (err)
(format *error-output* "~&~A~%" err) (finish-output *error-output*))))
;;; Generate link script:
(defun generate-link-script ()
(with-open-file (*standard-output*
(merge-pathnames (make-pathname :name "symlink-commands" :type :unspecific :version :unspecific
:defaults cl-user::*release-directory*)
cl-user::*release-directory*
nil)
:direction :output
:if-does-not-exist :create
:if-exists :supersede)
(write-line "#!/bin/bash")
(dolist (name *all-commands*)
(unless (string= name "commands")
(format t "ln -s commands ~A~%" name)))))
(progn
(when *verbose* (format *trace-output* "builder.lisp: ~S~%" '(register-commands)))
(register-commands)
(when *verbose* (format *trace-output* "builder.lisp: ~S~%" '(quickload-command-dependencies)))
(quickload-command-dependencies)
(when *verbose* (format *trace-output* "builder.lisp: ~S~%" '(generate-link-script)))
(generate-link-script)
(when *verbose* (format *trace-output* "builder.lisp: ~S~%" '(setf *failures* 0)))
(setf *failures* 0)
(dolist (name *all-commands*)
(when *verbose* (format *trace-output* "builder.lisp: ~S~%" `(compile-and-load-command ,name)))
(compile-and-load-command name)))
;;;; THE END ;;;;
| 9,001 | Common Lisp | .lisp | 188 | 39.930851 | 119 | 0.561142 | informatimago/commands | 8 | 1 | 0 | AGPL-3.0 | 9/19/2024, 11:26:57 AM (Europe/Amsterdam) | 225112f4682815e3ec02dbf8d1a59c2a9a3f9aa8268eaef997adb341af044483 | 12,310 | [
-1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.