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
1,620
package.lisp
ghollisjr_cl-ana/symbol-utils/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (defpackage #:cl-ana.symbol-utils (:use :cl :cl-ana.list-utils) (:export :keywordify :keysymb :keysymbq))
1,014
Common Lisp
.lisp
26
36.461538
70
0.68997
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
16ec65efc63c08e98f35020c9ee502ea67c69d658e6aa893be0ce070f0c6eed0
1,620
[ -1 ]
1,621
package.lisp
ghollisjr_cl-ana/spline/package.lisp
(defpackage :cl-ana.spline (:use :cl :cl-ana.fitting :cl-ana.macro-utils :cl-ana.list-utils :cl-ana.tensor :cl-ana.math-functions) (:export :polynomial-spline ; supports polynomial splines of arbitrary order ;; struct accessors :polynomial-spline-degree :polynomial-spline-coefs :polynomial-spline-xs :polynomial-spline-deltas :gsl-spline ; supports splines provided by GSL via GSLL :polynomial-spline-constraint ; generate consraint equations :evaluate-polynomial-spline :evaluate-polynomial-spline-derivative ; derivatives to any degree :evaluate-polynomial-spline-integral ; definite integral )) (cl-ana.gmath:use-gmath :cl-ana.spline)
724
Common Lisp
.lisp
21
29.428571
70
0.730659
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
7c638cae8c9d25350f71ec8ab95dd9a3e206e455b21f9deafcef48b36cc0be0f
1,621
[ -1 ]
1,622
spline.lisp
ghollisjr_cl-ana/spline/spline.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2021 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.spline) ;; This project supports natural splines of any order, uniform and ;; non-uniform. ;;; Adding basic FFI for GSL's sparse matrix functions. (defparameter +GSL-CONTINUE+ -2) ; from gsl_errno.h (defparameter +GSL-SUCCESS+ 0) ; from gsl_errno.h (defun GSL-ITERSOLVE-GMRES () (cffi:foreign-symbol-pointer "gsl_splinalg_itersolve_gmres")) ;; I want to use this, but on my system this causes strange memory ;; bugs. ;; ;; (cffi:use-foreign-library gsll::libgsl) ;; ;; So instead I do this: (cffi:define-foreign-library gsl (:windows (:or "libgsl-0.dll" "cyggsl-0.dll")) (:darwin (:or (:framework "libgsl") "libgsl.dylib")) (:unix (:or "libgsl.so.25" "libgsl.so.0" "libgsl.so")) (t (:default "libgsl"))) (cffi:use-foreign-library gsl) ;; Vectors (cffi:defcfun "gsl_vector_alloc" :pointer (nelements :int)) (cffi:defcfun "gsl_vector_free" :void (vector :pointer)) (cffi:defcfun "gsl_vector_get" :double (vector :pointer) (i :int)) (cffi:defcfun "gsl_vector_set" :void (vector :pointer) (i :int) (x :double)) (cffi:defcfun "gsl_vector_ptr" :pointer (vector :pointer) (i :int)) (cffi:defcfun "gsl_vector_set_zero" :void (vector :pointer)) (cffi:defcfun "gsl_vector_set_all" :void (vector :pointer) (x :double)) (cffi:defcfun "gsl_vector_set_basis" :void (vector :pointer) (i :int)) ;; Sparse Matrices (cffi:defcfun "gsl_spmatrix_alloc" :pointer (nrows :unsigned-int) (ncols :unsigned-int)) (cffi:defcfun "gsl_spmatrix_free" :void (matrix :pointer)) (cffi:defcfun "gsl_spmatrix_get" :double (matrix :pointer) (i :int) (j :int)) (cffi:defcfun "gsl_spmatrix_set" :int (matrix :pointer) (i :int) (j :int) (x :double)) (cffi:defcfun "gsl_spmatrix_set_zero" :int (matrix :pointer) (i :int) (j :int)) (cffi:defcfun "gsl_spmatrix_ptr" :pointer (matrix :pointer) (i :int) (j :int)) ;; compress matrix (cffi:defcfun "gsl_spmatrix_ccs" :pointer (matrix :pointer)) ;; Linear algebra ;; returns workspace (cffi:defcfun "gsl_splinalg_itersolve_alloc" :pointer (type :pointer) (n :int) (m :int)) (cffi:defcfun "gsl_splinalg_itersolve_free" :void (workspace :pointer)) (cffi:defcfun "gsl_splinalg_itersolve_name" :pointer (workspace :pointer)) (cffi:defcfun "gsl_splinalg_itersolve_iterate" :int (sparse-matrix :pointer) (rhs-vector :pointer) (tolerance :double) (result-vector :pointer) (workspace :pointer)) (cffi:defcfun "gsl_splinalg_itersolve_normr" :double (workspace :pointer)) ;; Utility/Helper Functions (defun make-splinalg-workspace (nrows &optional (subspacerows 0)) (gsl-splinalg-itersolve-alloc (cffi:mem-ref (GSL-ITERSOLVE-GMRES) :pointer 0) nrows subspacerows)) (defun sp-solve-system (coefs vector) (let* ((nrows (length coefs)) (ncols (length (first coefs))) (mat (gsl-spmatrix-alloc nrows ncols)) (vec (gsl-vector-alloc (length vector))) (w (make-splinalg-workspace nrows nrows)) (tol 1d-3) (res (gsl-vector-alloc (length vector)))) (loop for i from 0 for row in coefs do (loop for j from 0 for x in row when (not (zerop x)) do (gsl-spmatrix-set mat i j x))) (loop for v in vector for i from 0 do (gsl-vector-set vec i v)) (let* ((m (gsl-spmatrix-ccs mat)) (stat +GSL-CONTINUE+)) (loop while (= stat +GSL-CONTINUE+) do (setf stat (gsl-splinalg-itersolve-iterate m vec tol res w)))) (loop for i below (length vector) collecting (gsl-vector-get res i)))) (defstruct polynomial-spline degree ;integer coefs ;2-D array xs ;vector deltas ;vector ) (defun spline-bin-index (xs x) "Returns integer index to spline bin" (loop for i from 0 for xlow across xs when (> xlow x) do (return (1- i)) finally (return (1- (length xs))))) (defun evaluate-polynomial-spline (spline x &key ;; set to T to maintain final value outside ;; domain. Default is to have value 0 ;; outside domain. continued-boundary-p) (with-slots (coefs deltas xs degree) spline (labels ((ev (index x) (polynomial (loop for j to degree collecting (aref coefs index j)) (/ (- x (aref xs index)) (aref deltas index))))) (let* ((index (spline-bin-index xs x))) (cond ((minusp index) (if continued-boundary-p (ev 0 (aref xs 0)) 0d0)) ((> index (- (length xs) 2)) (if continued-boundary-p (ev (- (length xs) 2) (aref xs (1- (length xs)))) 0d0)) (t (ev index x))))))) (defun polynomial-derivative (params x degree) "Evaluates derivative of given degree of polynomial at point x." (polynomial (loop for i from 0 for p in params when (>= i degree) collecting (* (npermutations i degree) p)) x)) (defun polynomial-integral (params xlo xhi) "Evaluates definite integral of polynomial." (flet ((pint (x) (polynomial (cons 0d0 (loop for i from 1d0 for p in params collecting (/ p i))) x))) (- (pint xhi) (pint xlo)))) (defun evaluate-polynomial-spline-derivative (spline x deg) (with-slots (coefs deltas xs degree) spline (labels ((ev (index x) (* (expt (aref deltas index) deg) (polynomial-derivative (loop for j to degree collecting (aref coefs index j)) (/ (- x (aref xs index)) (aref deltas index)) deg)))) (let* ((index (spline-bin-index xs x))) (cond ((minusp index) 0d0) ((> index (- (length xs) 2)) 0d0) (t (ev index x))))))) (defun evaluate-polynomial-spline-integral (spline xlo xhi) "Evaluates definite integral of natural spline." (with-slots (xs deltas coefs degree) spline (labels ((binparams (xbin) (loop for i to degree collecting (aref coefs xbin i))) (wholebinint (xbin) (let* ((params (binparams xbin))) (* (aref deltas xbin) (polynomial-integral params 0d0 1d0))))) (let* ((N (1- (length xs))) (sign (cond ((< xlo xhi) 1d0) ((> xlo xhi) -1d0) (t 0d0))) (xlo (if (minusp sign) xhi xlo)) (xhi (if (minusp sign) xlo xhi)) (xlowbin (awhen (loop for i from 0 for x across xs when (>= x xlo) do (return (1- i)) finally (return nil)) (max it 0))) (xlowoffset (when xlowbin (max (- xlo (aref xs xlowbin)) 0d0))) (xhighbin (awhen (loop for i downfrom (- N 1) downto 0 for x = (aref xs i) when (< x xhi) do (return i) finally (return nil)) (min (- N 1) it))) (xhighoffset (when xhighbin (min (- xhi (aref xs xhighbin)) (aref deltas (1- N))))) (lowparams (when xlowbin (binparams xlowbin))) (highparams (when xhighbin (binparams xhighbin)))) (if (and xlowbin xhighbin (= xlowbin xhighbin)) (* (aref deltas xlowbin) (polynomial-integral lowparams xlowoffset xhighoffset)) (let* ((lowint (when xlowbin (* (aref deltas xlowbin) (polynomial-integral lowparams (/ (- xlowoffset (aref xs xlowbin)) (aref deltas xlowbin)) 1d0)))) (highint (when xhighbin (* (aref deltas xhighbin) (polynomial-integral highparams 0d0 (/ xhighoffset (aref deltas xhighbin))))))) (when (and lowint highint) (+ lowint highint (loop for i from (1+ xlowbin) to (1- xhighbin) summing (wholebinint i)))))))))) (defun polynomial-spline-constraint (poly-degree npoints bin value &key (side :left) ; can be :right (derivative 1)) "Generates a constraint list for the polynomial-spline function. Poly-degree sets the polynomial degree, nbins specifies the number of points in the spline, bin determines the spline polynomial to constrain (0 through npoints-2), value sets the value for the RHS vector, and derivative selects the degree of derivative which the constraint applies to. This can be used to create more complex constraints by using value=0 and adding together whatever linear combinations of constraints you need, finally setting the last element to whatever constraint value you need. Set side to :right to constrain a polynomial using the right point of the bin rather than the left point. CAUTION: You can use this function to generate nonsensical constraints that are incompatible with the rest of the spline, which will lead to failure to solve the system of equations. Derivatives are generally safe to set, whereas values are already constrained by the nature of the spline, which is why the derivative argument defaults to 1 rather than 0." (let* ((nbins (1- npoints)) (ncoefs (* (1+ poly-degree) nbins)) (result (make-array (1+ ncoefs) :initial-element 0d0))) (case side (:left (setf (aref result (+ derivative (* (1+ poly-degree) bin))) (->double-float (factorial derivative)))) (:right (loop for i from derivative to poly-degree for ii = (+ (* (1+ poly-degree) bin) i) do (setf (aref result ii) (->double-float (npermutations i derivative)))))) (setf (aref result ncoefs) value) (coerce result 'list))) (defun polynomial-spline (points &key derivatives constraints (degree 3) (tolerance 1d-5)) "Creates polynomial spline of arbitrary degree and adjustable derivative constraints. Polynomial splines have most degrees of freedom constrained by requiring continuity of all but one non-zero derivative. Natural splines set the remaining degrees of freedom by mandating derivatives of sufficient order at the first and last domain points be zero. By leaving the derivatives argument NIL, natural polynomial splines will be produced. If you set derivatives to a list of degree-1 numerical values, these will be used as values for the remaining derivatives. The order is as follows: For even degree: First degree/2 values are first-point derivatives, Last degree/2-1 values are last-point derivatives. For odd degree: First (degree-1)/2 are first-point, Last (degree-1)/2 are last-point. For ultimate flexibility, use the constraints argument as a list of linear equation lists where all elements except the last are a row of the coefficient matrix and the last element is the RHS vector value. The utility function polynomial-spline-constraint assists in generating these." (let* ((derivatives (coerce (aif derivatives (->double-float it) (loop for i below (1- degree) collecting 0d0)) 'vector)) (npoints (length points)) (N (1- npoints)) (nrows (* (1+ degree) N)) (coefs (gsl-spmatrix-alloc nrows nrows)) (vec (gsl-vector-alloc (* (1+ degree) N))) (equation-index 0) (xs (coerce (cars points) 'vector)) (ys (coerce (cdrs points) 'vector)) (deltas (- (subseq xs 1) xs)) (w (make-splinalg-workspace nrows nrows)) (tol (->double-float tolerance)) (res (gsl-vector-alloc nrows)) (sp (make-polynomial-spline :coefs (make-array (list N (1+ degree))) :degree degree :xs xs :deltas deltas))) ;;; coefficients matrix ;;; ;;; Five constraint types: ;;; 1. Left boundaries. ;;; 2. Right boundaries. ;;; 3. Continuity. ;;; 4. Left natural derivatives. ;;; 5. Right natural derivatives. ;; 1. Left boundaries. (loop for i below N for j = (* (1+ degree) i) do ;; coefs (gsl-spmatrix-set coefs i j 1d0) ;; vector (gsl-vector-set vec i (->double-float (aref ys i)))) (incf equation-index N) ;; 2. Right boundaries (loop for i below N for ii = (+ equation-index i) do ;; coefs (loop for j to degree for jj = (+ j (* (1+ degree) i)) do (gsl-spmatrix-set coefs ii jj 1d0)) ;; vector (gsl-vector-set vec ii (->double-float (aref ys (1+ i))))) (incf equation-index N) ;; Continuity (loop for L from 1 below degree ; degree-1 fold do (loop for i below (1- N) for ii = (+ equation-index (* (- L 1) (1- N)) i) do ;; coefs ;; rhs (gsl-spmatrix-set coefs ii (+ (* (1+ degree) (1+ i)) L) -1d0) ;; lhs (loop for j from L to degree for jj = (+ (* (1+ degree) i) j) do (gsl-spmatrix-set coefs ii jj (->double-float (* (binomial j L) (expt (/ (aref deltas (1+ i)) (aref deltas i)) L))))) ;; vec (gsl-vector-set vec ii 0d0))) (incf equation-index (* (1- degree) (1- N))) ;; either natural derivatives or explicit constraints: (if (and constraints (length-equal constraints (1- degree))) (loop for i from equation-index for constraint in constraints do (loop for j from 0 for c in (butlast constraint) do (gsl-spmatrix-set coefs i j (->double-float c))) (gsl-vector-set vec i (->double-float (first (last constraint))))) ;; natural derivatives (cond ((= degree 2) (gsl-spmatrix-set coefs equation-index 2 1d0) ;; vec (gsl-vector-set vec equation-index 0d0)) (t (let* ((leftstart (if (evenp degree) (floor degree 2) (floor (+ degree 1) 2))) (rightstart (if (evenp degree) (+ (floor degree 2) 1) (floor (+ degree 1) 2)))) ;; 4. left (loop for i from 0 for L from leftstart below degree for ii = (+ equation-index i) do ;; coefs (gsl-spmatrix-set coefs ii L 1d0) ;; vec (gsl-vector-set vec ii (aref derivatives i))) (incf equation-index (- degree leftstart)) ;; 5. right (loop for i from 0 for L from rightstart below degree for ii = (+ equation-index i) do ;; coefs (loop for j from L to degree for jj = (+ j (* (1+ degree) (- npoints 2))) do (gsl-spmatrix-set coefs ii jj (->double-float (npermutations j L)))) ;; vec (gsl-vector-set vec ii (aref derivatives (+ i (- degree leftstart))))))))) ;; solve (let* ((m (gsl-spmatrix-ccs coefs)) (stat +GSL-CONTINUE+)) (loop while (= stat +GSL-CONTINUE+) do (setf stat (gsl-splinalg-itersolve-iterate m vec tol res w))) (loop for i below nrows for ii = (floor i (1+ degree)) for jj = (mod i (1+ degree)) do (setf (aref (polynomial-spline-coefs sp) ii jj) (gsl-vector-get res i))) ;; cleanup (gsl-spmatrix-free m) (gsl-spmatrix-free coefs) (gsl-vector-free vec) (gsl-vector-free res) (gsl-splinalg-itersolve-free w)) (values (lambda (x) (evaluate-polynomial-spline sp x)) sp))) (defun gsl-spline (points &key (type gsll:+cubic-spline-interpolation+)) "Returns a Lisp function which returns the spline interpolation of these points using GSLL. Defaults to a cubic spline. Returns 0 outside of the original domain since GSLL croaks outside of it for at least the cubic spline." (let* ((points (sort (copy-list points) #'< :key #'car)) (xmin (apply #'min (cars points))) (xmax (apply #'max (cars points))) (xs (grid:make-foreign-array 'double-float :initial-contents (cars points))) (ys (grid:make-foreign-array 'double-float :initial-contents (cdrs points))) (spline (gsll:make-spline type xs ys))) (values (lambda (x) (if (not (<= xmin x xmax)) 0d0 (gsll:evaluate spline x))) spline)))
21,214
Common Lisp
.lisp
580
23.860345
92
0.496748
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
b35dc91efeb1f04dcd5f06c0b30c1df815b6ad0836c0bc3d57e5acff9678b488
1,622
[ -1 ]
1,623
package.lisp
ghollisjr_cl-ana/makeres-block/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (defpackage #:cl-ana.makeres-block (:use :cl :cl-ana.macro-utils :cl-ana.list-utils :cl-ana.makeres ;; :cl-ana.symbol-utils ;; :cl-ana.map ;; :cl-ana.hash-table-utils ) (:export :blocktrans :defresblock))
1,148
Common Lisp
.lisp
31
33.580645
70
0.670251
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
85905d8d1151f948ef596bc81e2509ca73eabd5b9d55fc859d7ed94061d2455f
1,623
[ -1 ]
1,624
makeres-block.lisp
ghollisjr_cl-ana/makeres-block/makeres-block.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.makeres-block) (defvar *project->bid->body* (make-hash-table :test 'equal) "Map from project to block id (symbol block appended to list of ids defined by block) to the body defining the block") (defmacro defresblock ((&rest ids) &body body) "Macro defining a body which, when executed, will result in multiple targets having their values set." `(progn (when (not (gethash (project) *project->bid->body*)) (setf (gethash (project) cl-ana.makeres-block::*project->bid->body*) (make-hash-table :test 'equal))) (setf (gethash ',ids (gethash (project) cl-ana.makeres-block::*project->bid->body*)) ',body) ,@(loop for id in ids collecting `(defres ,id (makeres-block ,@body))))) (defun blocktrans (target-table) "Target table transformation supporting the definition of blocks which will result in multiple targets being computed at once." (flet ((copy-table (table) (let ((result (make-hash-table :test 'equal))) (loop for id being the hash-keys in table for target being the hash-values in table do (setf (gethash id result) (copy-target target))) result))) (let ((result-table (copy-table target-table)) (bid->body (gethash (project) *project->bid->body*))) (loop for bid being the hash-keys in bid->body for body being the hash-values in bid->body do (let ((tmpid (gensym))) (setf (gethash tmpid result-table) (make-target tmpid `(progn ,@body))) (loop for id in bid do (setf (target-expr (gethash id result-table)) `(progn (res ,tmpid) (resfn ',id)))))) result-table)))
2,860
Common Lisp
.lisp
67
34.164179
75
0.602366
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
6b088ac3cc9af61f418c5dc70efb35eb6e5a8b3209fd4fe72ac837b0745e52cc
1,624
[ -1 ]
1,625
test.lisp
ghollisjr_cl-ana/makeres-block/test.lisp
(require 'cl-ana) (in-package :cl-ana) (defproject makeres-block-test "/home/ghollisjr/test/makeres-block/test" (list #'blocktrans) (fixed-cache 5)) (defres a (list 1 2 3)) (defresblock (b c d) (setres b (sum (res a))) (setres c (zip (res a) (list (resfn 'b)))) (setres d 5))
296
Common Lisp
.lisp
12
22
45
0.657143
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
7d5b178322503fa1096908e2be6e710b20cc7bc4a6ec2cad6118f724a01c2564
1,625
[ -1 ]
1,626
logres-test.lisp
ghollisjr_cl-ana/makeres/logres-test.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (require 'cl-ana.makeres) (in-package :cl-ana.makeres) (in-project logres-test) (set-project-path "~/logres-test/") (defres source (list (list :x 1) (list :x 2) (list :x 3))) (defres vector (vector 1 2 3 4 5)) (defres (mean x) (/ (sum (mapcar (lambda (x) (getf x :x)) (res source))) (length (res source)))) (defres hash-table (let ((hash-table (make-hash-table :test 'equal))) (setf (gethash 'x hash-table) 'x) hash-table)) (defres nested (let ((ht (make-hash-table :test 'equal))) (setf (gethash 'hash-table ht) (res hash-table)) ht))
1,521
Common Lisp
.lisp
45
30.177778
70
0.652352
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
8edca0b9e2d279235df8743c0bf9fca559aa190896caad69e20724912eb2e9b2
1,626
[ -1 ]
1,627
function.lisp
ghollisjr_cl-ana/makeres/function.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.makeres) (defmethod printable ((f function)) nil) (define-save-target-method function id (functionp (target-val (or (gethash id (target-table)) (gethash id (gethash *project-id* *fin-target-tables*))))) nil) (defmethod save-object ((fn function) path) (format t "Warning: cannot save functions~%") nil) (defmethod load-object ((fn (eql 'function)) path) (format t "Warning: cannot load functions~%") nil)
1,437
Common Lisp
.lisp
35
35.914286
73
0.652827
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
55203f21e0d7f3690497adf13c5cc046960dd819cb26aa1b10bb30a773660e5f
1,627
[ -1 ]
1,628
package.lisp
ghollisjr_cl-ana/makeres/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (defpackage #:cl-ana.makeres (:use :cl :external-program :cl-ana.memoization :cl-ana.error-propogation :cl-ana.hdf-utils :cl-ana.macro-utils :cl-ana.list-utils :cl-ana.symbol-utils :cl-ana.map :cl-ana.functional-utils :cl-ana.file-utils :cl-ana.string-utils :cl-ana.serialization :cl-ana.histogram :cl-ana.pathname-utils :cl-ana.table :cl-ana.reusable-table :cl-ana.hash-table-utils :cl-ana.plotting) (:export ;; target :target :target-id :target-expr :target-deps :target-pdeps :target-val :target-stat :target-timestamp :make-target :copy-target ;; propogation: :transforms-propagate :res-dependencies :res-dependents :makeres-set-auto-propagate :makeres-propagate! :makeres-set-sticky-pars ;; hash tables (these are for debugging only :*symbol-tables :*target-tables* :*fin-target-tables* :*project-id* :*transformation-table* :*params-table* :*args-tables* :*makeres-args* ;; noisy messages: :*makeres-warnings* ;; functions accessing hash tables :project :project-parameters :project-targets :symbol-table :target-table :copy-target-table ;; dependency sorting: :depmap :dep< :depsort :depsort-graph :topological-sort :target-table-edge-map :decompress-edge-map :compress-edge-map :invert-edge-map ;; target and parameter macros :res :resfn :par :parfn :mres :with-mres :remakeres ;; project macros :defproject :in-project :defpars :undefpars :defres :defres-uniq :undefres :setresfn :setres :unsetresfn :unsetres :unsetdeps :unsetdepsfn :clrres :clrresfn :settrans ; set transformation pipeline :transform-target-table ; transforms table via pipeline :makeres-form ; returns the lambda form to perform the computation :makeres ; compile and call result generator :makeres-naive ; makeres without any transformation pipeline ;; project utilities :target-ids :fin-target-ids ;; INCLUDED TRANSFORMATIONS: ;; Logical targets: :lrestrans :lres ;; Transformation utilities: :*trans->propogator-fn* :*copy-target-table-p* :defpropogator ;; logres: :save-target :load-target :load-target-manual :unload-target :commit-form :define-save-target-method :define-load-target-method :load-object :save-object :cleanup :project-path :set-project-path :save-project :load-project :checkout-version :logres-ignore :logres-ignorefn :logres-ignore-by :logres-track :logres-trackfn :logres-track-by :function-target? :printable :current-path :target-path :work-path ;;; Snapshot Control: :save-snapshot :load-snapshot ;;; Caching: :defcache :init-logged-stats ;; Strategies: :open-cache :singleton-cache :fixed-cache ;; Utilities: :checkres :pruneres :purgeres :printres :mvres :evres :evresfn)) (cl-ana.gmath:use-gmath :cl-ana.makeres)
4,037
Common Lisp
.lisp
173
19.17341
70
0.680664
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
1dea355e18efff43d9fc96988156d9749feec8ac1be9df694c9f0cde2ae3d896
1,628
[ -1 ]
1,629
hash-table.lisp
ghollisjr_cl-ana/makeres/hash-table.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.makeres) (defmethod printable ((obj hash-table)) nil) (defmethod save-object ((ht hash-table) path) (let* ((savedir (make-pathname :directory (namestring path))) (indexpath (merge-pathnames "index" savedir))) (ensure-directories-exist savedir) (let ((index-alist nil)) (loop for k being the hash-keys in ht for v being the hash-values in ht for i from 0 do ;; save content: (push (cons (list i (target-type k)) (list i (target-type v))) index-alist) (save-object k (merge-pathnames (mkstr "k" i) savedir)) (save-object v (merge-pathnames (mkstr "v" i) savedir))) (with-open-file (file indexpath :direction :output :if-exists :supersede :if-does-not-exist :create) (format file "~s~%" (nreverse index-alist)) (format file "~s~%" (hash-table-test ht)))))) (defmethod load-object ((type (eql 'hash-table)) path) (let* ((loaddir (make-pathname :directory (namestring path))) (indexpath (merge-pathnames "index" loaddir))) (let ((index-alist nil) (test nil)) (with-open-file (file indexpath :direction :input :if-does-not-exist :error) (setf index-alist (read file)) (setf test (read file))) (map->hash-table (mapcar (lambda (cons) (destructuring-bind ((kid ktype) . (vid vtype)) cons (cons (load-object ktype (merge-pathnames (mkstr "k" kid) loaddir)) (load-object vtype (merge-pathnames (mkstr "v" vid) loaddir))))) index-alist) test))))
3,129
Common Lisp
.lisp
77
27.857143
70
0.513451
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
fc35534ff6fb5ba5e8d0e883d36e4feee99d1a30cb4156481fe8f6f3fab1a9ac
1,629
[ -1 ]
1,630
lrestrans.lisp
ghollisjr_cl-ana/makeres/lrestrans.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.makeres) ;;;; This file serves as a regrettably bad example as to how to write ;;;; target table/graph transformations. ;;;; ;;;; The following are rules for graph/target table transformations: ;;;; ;;;; * The graph given as an argument is a free to be modified in any ;;;; way, but only the return value is used for the next ;;;; transformation in the pipeline. ;;;; ;;;; * Modification of the global variables in the makeres package can ;;;; be done at the user's peril, this is highly dependent on the ;;;; order in which information is pulled/pushed into these ;;;; variables. The lrestrans is an example of how to do this (and ;;;; how messy it is). ;;;; ;;;; * All targets present in (gethash *project-id* *target-tables*) ;;;; must be present in the output of the last transformation in the ;;;; pipeline; no need to restrict these too much by forcing it on ;;;; every stage. You the user can decide whether you want to be a ;;;; hard-ass. ;;;; ;;;; * The output of the last transformation in the pipeline goes in ;;;; (gethash *project-id* *fin-target-tables*), so modifying this ;;;; table is probably a bad idea for your algorithm. ;;;; ;;;; * Target dependencies created via make-target make use of ;;;; find-dependencies, so if you want a different mechanism you ;;;; need to use (make-instance 'target ...) and supply explicit ;;;; values when you create the output graph. ;; lrestrans uses a new operator, lres, which denotes a logical result ;; to be recomputed every time makeres is run. (eval-when (:compile-toplevel :load-toplevel :execute) ;; Note that this method is dirty; the target-stat values are ;; assumed to be unmanaged by the transformations due to the model ;; of computation: they are to return a new graph without knowledge ;; of previous versions etc. This transformation directly violates ;; this assumption. (defun lrestrans (target-table) "Sets all lres result statuses in the final target table and target table to nil" (let ((result (make-hash-table :test 'equal))) (loop for key being the hash-keys in target-table for val being the hash-values in target-table do (progn (setf (gethash key result) (copy-target val)) (when (eq (first (second (target-expr val))) 'lres) (destructuring-bind (progn expr &rest someone-does-not-understand-lres) (target-expr val) (destructuring-bind (lres expr) expr ;; immediate result table: (setf (target-stat (gethash key result)) nil) (setf (target-expr (gethash key result)) `(progn ,expr)) (unsetresfn key)))))) result)))
3,953
Common Lisp
.lisp
85
39.211765
71
0.629917
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
bf2d24b2f1e93dfc73f31e4dcbcbeb690e1c6eca72ec543da66b143c738b65e0
1,630
[ -1 ]
1,631
err-num.lisp
ghollisjr_cl-ana/makeres/err-num.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package cl-ana.makeres) (in-package :cl-ana.makeres) (defmethod printable ((obj err-num)) ;; Checking if this works: ;; nil t) (defmethod load-object ((type (eql 'err-num)) path) ;; (print type) (with-open-file (file path :direction :input) (read file))) (defmethod save-object ((obj err-num) path) (with-open-file (file path :direction :output :if-exists :supersede :if-does-not-exist :create) (format file "~s~%" obj)))
1,414
Common Lisp
.lisp
37
33.945946
70
0.657434
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
dc0f03863364c94207653407ea5cca6b29e3fd1d50271342e63ca140c722dbe6
1,631
[ -1 ]
1,632
cons.lisp
ghollisjr_cl-ana/makeres/cons.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.makeres) (defun printable-cons (obj) "Returns T if obj is a cons structure which can be printed" #+sbcl (let ((standard-method (first (sb-mop:compute-applicable-methods #'save-object (list nil ""))))) (or (equal (first (sb-mop:compute-applicable-methods #'save-object (list obj ""))) standard-method) (and (consp obj) (printable-cons (car obj)) (printable-cons (cdr obj))))) ;; Default is no printable objects #-(or sbcl) nil) (defmethod printable ((obj cons)) (or (null obj) (and (printable (car obj)) (printable (cdr obj))))) (defmethod save-object ((cell cons) path) (if (printable cell) (with-open-file (file path :direction :output :if-does-not-exist :create :if-exists :supersede) (format file "~s~%" cell)) (let* ((savedir (make-pathname :directory (namestring path))) (indexpath (merge-pathnames "index" savedir))) (ensure-directories-exist savedir) (let ((car-type (target-type (car cell))) (cdr-type (target-type (cdr cell)))) (with-open-file (file indexpath :direction :output :if-exists :supersede :if-does-not-exist :create) (format file "~a~%" (cons car-type cdr-type))) (save-object (car cell) (merge-pathnames "car" savedir)) (save-object (cdr cell) (merge-pathnames "cdr" savedir)))))) (defmethod load-object ((type (eql 'cons)) path) (if (cl-fad:directory-exists-p path) ;; general method (let* ((loaddir (make-pathname :directory (namestring path))) (indexpath (merge-pathnames "index" loaddir))) (let ((index-cons nil)) (with-open-file (file indexpath :direction :input :if-does-not-exist :error) (setf index-cons (read file))) ;; (print index-cons) (destructuring-bind (car-type . cdr-type) index-cons ;; (print car-type) ;; (print cdr-type) (cons (load-object car-type (merge-pathnames "car" loaddir)) (load-object cdr-type (merge-pathnames "cdr" loaddir)))))) ;; special case for printable cons structures (with-open-file (file path :direction :input) (read file))))
3,927
Common Lisp
.lisp
98
27.336735
70
0.512814
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
7cb7254aa43c1807c8bb4c5501466e80c29a041ed736e294cd9c822ad71c6248
1,632
[ -1 ]
1,633
function-test.lisp
ghollisjr_cl-ana/makeres/function-test.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (require 'cl-ana.makeres) (defpackage #:cl-ana.function-test (:use :cl :makeres)) (cl-ana.package-utils:use-package-group :cl-ana :cl-ana.function-test) (in-package :cl-ana.function-test) (in-project function-test) (set-project-path "function-test/") (logres-ignore-by #'functionp) (defres f (lambda (x) (print x)))
1,207
Common Lisp
.lisp
31
37.16129
70
0.713185
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
0226b0202b0e52e52af9e5328516ac11fd8092e604485a08cfd0a986a003c0fc
1,633
[ -1 ]
1,634
makeres.lisp
ghollisjr_cl-ana/makeres/makeres.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.makeres) (declaim (optimize (debug 3))) ;;;; makeres is a make-like tool for generating your analysis, i.e. it ;;;; uses a dependency graph to determine what to do in order to ;;;; generate any/all results you desire. Why couldn't you just use ;;;; GNU make? Well because for any non trivial work, you'll have to ;;;; specify a bit of how to do what you want, and furthermore since ;;;; the target is von Neumann architecture computers, you'll have to ;;;; provide some optimizations if you want to do things ;;;; declaratively and efficiently. ;;;; ;;;; makeres bridges the gap by allowing you to specify any number of ;;;; graph transformations to put in between the initial dependency ;;;; graph specification and the final ;;;; ready-for-literal-interpretation dependency graph. ;;;; ;;;; My initial (and still rather exemplary) usage concept was for ;;;; analyzing particle physics data. This consisted of making ;;;; multiple passes over semilarge datasets, collecting various ;;;; results along the way. The approach almost everyone uses ;;;; starting out is to ;;;; ;;;; * Do everything in a single pass over the entire dataset ;;;; ;;;; But this fails once you need information from the initial pass to ;;;; do something like filtering: you need a second pass. ;;;; ;;;; So this procedure results in either numbering your passes to keep ;;;; track of how many you have or trying to come up with memorable ;;;; names for each pass. (If you want to get fancy, you can call it ;;;; a pipeline.) ;;;; ;;;; My work had escalated to the point of combining the two ;;;; approaches, having names with numerical suffixes denoting various ;;;; stages of the analysis, but always wondering if the distinctions ;;;; were really necessary. I had formalized this system to a degree ;;;; that made me think a computer should be doing the work. ;;;; ;;;; Probably due to my experience with make, I found that viewing the ;;;; problem as a series of targets and dependencies made much more ;;;; sense than trying to keep up with passes over data. I tried many ;;;; approaches in my head before settling on makeres. ;; computations for a graph with different parameters are placed in ;; the same graph. Provide functions for copying graph to a new ;; graph-id to allow storage of different results. ;;;; There is one concern about recovering from errors. As written, ;;;; the algorithm is: Generate final graph -> Compute final graph ;;;; results -> Copy results from final graph. But, if any nodes in ;;;; the temp graph fail, then the final results may not be copied ;;;; properly. This could be alleviated by providing a handler with ;;;; an option to copy completed results to the final graph. This ;;;; would mean that the handler expression would need access to the ;;;; final graph object, but seems doable. (eval-when (:compile-toplevel :load-toplevel :execute) ;; structure containing target information (defclass target () ((id :accessor target-id :initarg :id :documentation "Identification") (expr :accessor target-expr :initarg :expr :documentation "Expression for computing") (deps :accessor target-deps :initarg :deps :documentation "list of target ids which are needed prior") (pdeps :accessor target-pdeps :initarg :pdeps :documentation "list of explicit parameter dependencies") (val :accessor target-val :initarg :val :initform nil :documentation "computation value, nil when needs computing, return value whenever computed") (stat :accessor target-stat :initarg :stat :initform nil :documentation "computation status, nil when needs computing, t otherwise") (timestamp :accessor target-timestamp :initarg :timestamp :initform nil :documentation "Time of most recent computation in seconds") (load-stat :accessor target-load-stat :initarg :load-stat :initform nil :documentation "T if target is loaded into memory, NIL otherwise") ;; save-stat not necessary due to new model: Targets are always ;; written to disk immediately after computation. Therefore the ;; only disk status necessary is the load status. ;; ;; (save-stat ;; :accessor target-save-stat ;; :initarg :save-stat ;; :initform nil ;; :documentation "T if most recent computation has been written to ;; disk, NIL otherwise") ))) (defmethod print-object ((tar target) stream) (format stream "~S" (copy-list `(target :id ,(target-id tar) :expr ,(target-expr tar) :deps ,(target-deps tar) :pdeps ,(target-pdeps tar) :val ,(target-val tar) :stat ,(target-stat tar) :timestamp ,(target-timestamp tar) :load-stat ,(target-load-stat tar))))) (defun find-dependencies (expr token) "Descends through expr, finding any forms of the form (token x) which is then interpreted as a dependency on x (token must be a symbol)" (let ((deps (make-hash-table :test 'equal))) (flet ((actual-listp (x) (and (listp x) (listp (cdr (last x)))))) (labels ((rec (ex) ;; check for (when (actual-listp ex) (if (and (length-equal ex 2) (eq (first ex) token)) (setf (gethash (second ex) deps) t) (mapcar #'rec ex))))) (rec expr) (hash-keys deps))))) (defun make-target (id expr &key val stat timestamp load-stat) (let ((deps (find-dependencies expr 'res)) (pdeps (find-dependencies expr 'par))) (make-instance 'target :id id :expr expr :deps (remove-if (lambda (d) (equal d id)) deps) :pdeps pdeps :val val :stat stat :timestamp timestamp :load-stat load-stat))) (defun copy-target (target) (make-instance 'target :id (copy-tree (target-id target)) :expr (copy-tree (target-expr target)) :deps (copy-tree (target-deps target)) :pdeps (copy-tree (target-pdeps target)) :val (copy-tree (target-val target)) :stat (copy-tree (target-stat target)) :timestamp (target-timestamp target) :load-stat (target-load-stat target))) (defun copy-target-test (target) (make-instance 'target :id (target-id target) :expr (copy-tree (target-expr target)) :deps (target-deps target) :pdeps (target-pdeps target) :val (copy-tree (target-val target)) :stat (target-stat target) :timestamp (target-timestamp target) :load-stat (target-load-stat target))) (defparameter *makeres-propagate* nil "Set to t if you want dependents of uncomputed results to have their statuses set to nil") (defparameter *copy-target-table-p* t "This is T by default so that transformations know to not modify their input arguments, but can be set to NIL by other functions once the graph has been copied once.") (defun makeres-set-auto-propagate (stat) "nil stat means don't propagate need-to-recompute to dependents of results needing computation, non-nil stat means do propagate." (setf *makeres-propagate* stat)) (defvar *compiled-generators* (make-hash-table :test 'equal) "Maps from project id to a gensym used for the compiled function name generated by compres.") (defvar *target-tables* (make-hash-table :test 'equal)) (defvar *fin-target-tables* (make-hash-table :test 'equal)) (defvar *project-id* nil) (defvar *transformation-table* (make-hash-table :test 'equal)) (defvar *params-table* (make-hash-table :test 'equal)) (defvar *makeres-args* (make-hash-table :test 'equal) "Map from arg symbol to supplied or default value at makeres execution") (defun compres-fname (&optional project-id) "Returns gensym for project used for compres" (symbol-macrolet ((gsym (gethash project-id *compiled-generators*))) (if gsym gsym (setf gsym (gensym))))) (defun project () "Returns current project" *project-id*) (defun project-parameters () (mapcar #'first (gethash (project) *params-table*))) (defun project-targets () (hash-keys (target-table))) (defun target-table (&optional (project-id *project-id*)) (gethash project-id *target-tables*)) (defun copy-target-table (target-table) "Returns a new hash-table object with copies of each target from target-table." (let ((result (make-hash-table :test 'equal))) (loop for id being the hash-keys in target-table for tar being the hash-values in target-table do (setf (gethash id result) (copy-target tar))) result)) ;; makeres utilities: (defun pipe-functions (fns input) "Evaluates each function in fns given input either from the initial input or from the output of the previous function in the list fns" (let ((val (copy-target-table input))) (loop for f in fns do (setf val (funcall f val))) val)) ;; Major function: res-dependencies ;; ;; returns full list of dependencies on a target (defun res-dependents (res-id target-table) "Returns full list of result-dependent targets in target-table" (let* (;; table mapping from id to those targets immediately ;; dependent on id (dependent-table (make-hash-table :test 'equal)) (explicit-deps (loop for id being the hash-keys in target-table for tar being the hash-values in target-table when (member res-id (target-deps tar) :test #'equal) collecting id)) (deps nil)) ;; fill dependent-table (loop for id being the hash-keys in target-table for target being the hash-values in target-table do (loop for d in (target-deps target) do (push id (gethash d dependent-table)))) ;; collect all dependents of explicit-deps and insert into deps (labels ((rec (id) (setf deps (adjoin id deps :test #'equal)) (mapcar #'rec (gethash id dependent-table)))) (mapcar #'rec explicit-deps) deps))) ;; Major function: dep< ;; ;; this uses lists for sets, inefficient for large dependency ;; graphs, so it needs to be updated in the future (defun res-dependencies (graph id) (labels ((rec (id) ;; returns full list of dependencies for id (let ((tar (gethash id graph))) (when tar (let ((deps (copy-list (target-deps tar)))) (when deps (reduce (lambda (ds d) (adjoin d ds :test #'equal)) (mapcan #'rec deps) :initial-value deps))))))) (rec id))) (defun depmap-old-old (target-table) "Returns the dependency map for a target-table. Used by dep< and can be useful for generating the explicit dependency graph for a target table." (let ((depmap (make-hash-table :test 'equal))) (memolet ((rec (id) ;; returns full list of dependencies for id (let ((tar (gethash id target-table))) (when tar (let ((deps (copy-list (target-deps tar)))) (when deps (reduce (lambda (ds d) (adjoin d ds :test #'equal)) (mapcan (lambda (i) (copy-list (rec i))) deps) :initial-value deps))))))) (loop for id being the hash-keys in target-table do (setf (gethash id depmap) (rec id))) depmap))) ;; A simple set library (defun mkset (lst) (declare (list lst)) (let ((result (make-hash-table :test 'equal))) (loop for x in lst do (setf (gethash x result) t)) result)) (defun set* (x y) (declare (hash-table x) (hash-table y)) (let ((result (make-hash-table :test 'equal))) (loop for k being the hash-keys in x for vy = (gethash k y) when vy do (setf (gethash k result) t)) result)) (defun set+ (x y) (declare (hash-table x) (hash-table y)) (let ((result (make-hash-table :test 'equal))) (loop for k being the hash-keys in x do (setf (gethash k result) t)) (loop for k being the hash-keys in y when (not (gethash k result)) do (setf (gethash k result) t)) result)) (defun set- (x y) "Returns the elements in x that aren't in y" (declare (hash-table x) (hash-table y)) (let ((result (make-hash-table :test 'equal))) (loop for k being the hash-keys in x when (not (gethash k y)) do (setf (gethash k result) t)) result)) (defun set^ (x y) "Returns set XOR of x and y" (declare (hash-table x) (hash-table y)) (set+ (set- x y) (set- y x))) (defun set-empty? (x) (declare (hash-table x)) (zerop (hash-table-count x))) (defun set-equal? (x y) (declare (hash-table x) (hash-table y)) (set-empty? (set^ x y))) (defun set-member (s x) (declare (hash-table s)) (gethash x s)) (defun set->list (x) (declare (hash-table x)) (loop for k being the hash-keys in x collecting k)) (defun depmap (target-table) "Returns the dependency map for a target-table. Used by dep< and can be useful for generating the explicit dependency graph for a target table." (let ((depmap (make-hash-table :test 'equal))) (memolet ((rec (id) ;; returns full set of dependencies for id (let ((tar (gethash id target-table))) (if tar (let ((deps (target-deps tar))) (if deps (reduce #'set+ (mapcar #'rec deps) :initial-value (mkset deps)) (mkset nil))) (mkset nil))))) (loop for id being the hash-keys in target-table do (setf (gethash id depmap) (set->list (rec id)))) depmap))) (defun compressed-table (target-table) (let* ((maxid 0) (idmap (make-hash-table :test 'equal)) (result (make-hash-table))) (declare (integer maxid)) (memolet ((id (x) (setf (gethash x idmap) maxid) (incf maxid) ;; (1- maxid) ;; (mkstr x) (intern (mkstr x) :keyword) ;; x )) (loop for id being the hash-keys in target-table do (setf (gethash (id id) result) (mapcar #'id (target-deps (gethash id target-table)))))) result)) (defun keyword-compressed-table (target-table) (let* ((reverse-map (make-hash-table)) (result (make-hash-table))) (flet ((id (x) (let ((sym (intern (mkstr x) :keyword))) (setf (gethash sym reverse-map) x) sym) ;; x )) (loop for id being the hash-keys in target-table for tar being the hash-values in target-table do (setf (gethash (id id) result) (mapcar #'id (target-deps tar))))) (values result reverse-map))) (defun depmap-compressed (compressed) "Returns the dependency map for a target-table. Used by dep< and can be useful for generating the explicit dependency graph for a target table." (let ((depmap (make-hash-table))) (memolet ((rec (id) ;; returns full set of dependencies for id (let ((deps (gethash id compressed))) (if deps (reduce #'set+ (mapcar #'rec deps) :initial-value (mkset deps)) (mkset nil))))) (loop for id being the hash-keys in compressed do (setf (gethash id depmap) (set->list (rec id)))) depmap))) (defun depmap-new (target-table) (multiple-value-bind (compressed reverse-map) (keyword-compressed-table target-table) (let* ((compressed-result (depmap-compressed compressed)) (result (make-hash-table :test 'equal))) (loop for k being the hash-keys in compressed-result for v being the hash-values in compressed-result do (setf (gethash (gethash k reverse-map) result) (mapcar (lambda (x) (gethash x reverse-map)) v))) result))) (defun testdepmap (x y) "Should return true if two depmaps contain identical information. Used to test depmap upgrade." (loop for k being the hash-keys in x for vx being the hash-values in x do (multiple-value-bind (vy vy-p) (gethash k y) (let* ((vx (mkset vx)) (vy (mkset vy))) (when (or (not vy-p) (not (set-equal? vx vy))) (return-from testdepmap nil))))) (return-from testdepmap t)) (defun dep< (target-table) "Returns comparison function from target-table which returns true when the left argument does not depend on the right argument." (let ((depmap (depmap target-table))) (lambda (x y) (not (member y (gethash x depmap) :test #'equal))))) ;; Topological sort functions ;; ;; This is the replacement for the inefficient topological sorting ;; algorithm I called depsort only because I had never heard the term ;; topological sorting and had never read an actual algorithm. As ;; usual, there are much better algorithms than the one I whipped up ;; in a few minutes. (defun target-table-edge-map (&optional (target-table (target-table))) "Returns an edge map from the target-table. This returns an inverted dependency graph, with children mapping to parents instead of parents mapping to children. Therefore, the result of this needs to be inverted before passing to topological sorting." (let ((result (make-hash-table :test 'equal))) (loop for id being the hash-keys in target-table do (setf (gethash id result) (target-deps (gethash id target-table)))) result)) (defun edge-map-ids (edge-map) (let ((edge-map (map->alist edge-map)) (traversed (make-hash-table :test 'equal))) (loop for n in edge-map do (destructuring-bind (p . cs) n (when (not (gethash p traversed)) (setf (gethash p traversed) t)) (loop for c in cs do (when (not (gethash c traversed)) (setf (gethash c traversed) t))))) (hash-keys traversed))) (defun decompress-edge-map (edge-map) "Generates an alist of single-dependency edges, the standard academic representation of a DAG" (let ((edge-map (map->hash-table edge-map 'equal)) (decompressed nil)) (loop for parent being the hash-keys in edge-map do (let ((children (gethash parent edge-map))) (if children (loop for c in children do (push (cons parent c) decompressed)) (push (list parent) decompressed)))) decompressed)) (defun compress-edge-map (edge-map-alist) "Generates a hash-table of compressed edges, i.e. all direct children listed for each parent." (let ((result (make-hash-table :test 'equal))) (loop for (p . c) in edge-map-alist do (if (null c) (when (not (gethash p result)) (setf (gethash p result) nil)) (push c (gethash p result)))) result)) (defun edge-map-node-set (edge-map) "Returns a hash-table acting as the set of nodes referenced in edge-map." (let ((result (make-hash-table :test 'equal))) (flet ((insert (x) (when (not (gethash x result)) (setf (gethash x result) t)))) (loop for id being the hash-keys in edge-map for deps being the hash-values in edge-map do (insert id) (loop for d in deps do (insert d)))) result)) (defun invert-edge-map (edge-map) "Inverts an edge-map. edge-map represents the edges in a directed acyclic graph with keys being the parent nodes and values being lists of all immediate child nodes." (let* ((edge-map (map->hash-table edge-map 'equal)) ;; original node set (edge-map-nodes (edge-map-node-set edge-map)) (nodes (hash-keys edge-map)) (decompressed (decompress-edge-map edge-map)) (inverted (loop for cons in decompressed when (cdr cons) collecting (cons (cdr cons) (car cons)) ;; Old version ;; collecting ;; (if (cdr cons) ;; (cons (cdr cons) ;; (car cons)) ;; (list (car cons))) )) (compressed (compress-edge-map inverted)) (result-nodes (edge-map-node-set compressed))) ;; Add uncaptured nodes back into the result as singletons (loop for k being the hash-keys in edge-map-nodes when (not (gethash k result-nodes)) do (setf (gethash k compressed) nil)) compressed)) (defun topological-sort (edge-map) "Topologically sorts an edge-map which represents a directed acyclic graph. edge-map should be a datatype that has a method map->hash-table defined. The keys should be parent nodes, and the values should be lists of child nodes. Since makeres uses the reverse scheme, instead listing nodes as keys and their parents as value lists, invert-edge-map needs to be used on target-table edge-maps before topologically sorting the values." (let* ((edge-map (map->hash-table edge-map 'equal)) ;; Traversed nodes (tset (make-hash-table :test 'equal)) ;; List of all nodes (nodes (edge-map-ids edge-map)) ;; Sorted ids (sorted nil)) ;; Algorithm is very simple ;; ;; 1. Start with the first node in remaining ;; 2. If node is already in tset, do nothing ;; 3. Else, place node into the list of traversed nodes ;; 4. If node has children, then loop over children ;; 5. After looping over children, place node at the top of ;; sorted and pop out of remaining ;; 6. Continue over remaining until no more nodes are in remaining (labels ((traverse (node) (when (not (gethash node tset)) (setf (gethash node tset) t) (let* ((children (gethash node edge-map))) (when children (mapcar #'traverse children)) (push node sorted))))) (mapcar #'traverse nodes) sorted))) ;; depsort-graph functions: ;; Here, dep< means "does not depend". So, (dep< x y) being T means ;; that x does not depend on y. It's like a less-than relationship ;; because sorting using "does not depend" results in a list sorted ;; from least dependent to most dependent. (defun last-dep (x lst dep<) "Returns last dependency of x found in lst and t; if no dependencies are found then returns two nil values" (let ((res (remove-if (lambda (d) (funcall dep< x d)) lst))) (if res (values (first (last res)) t) (values nil nil)))) (defun insert-after! (insertion lst token) "Inserts insertion into list immediately following the first element #'equal to token." (if (null lst) (push insertion lst) (if (equal (first lst) token) (setf (cdr lst) (cons insertion (cdr lst))) (insert-after! insertion (cdr lst) token)))) (defun depsort (ids dep<) "Sorts a list of values given dependency comparison function dep<; special algorithm since sort needs transitive operator while dep< is not transitive in general." (let ((result nil)) (loop for i in ids do (multiple-value-bind (last-dep any) (last-dep i result dep<) (if any (insert-after! i result last-dep) (push i result)))) result)) ;; old depsort graph algorithm (defun depsort-graph-old (target-table &optional dep<) "Returns dependency-sorted target ids from target-table, if dep< is provided then it is used instead of the dep< computed from the target-table." (let ((dep< (if dep< dep< (dep< target-table)))) (depsort (hash-keys target-table) dep<))) (defun depsort-graph (target-table) "Returns dependency-sorted target ids from target-table. Uses the new topological sort algorithm." (topological-sort (invert-edge-map (target-table-edge-map target-table)))) ;; Major function: param-dependents ;; ;; finds full list of targets which depend on parameter and returns ;; list of ids (defun param-dependents (parameter target-table) "Returns full list of parameter-dependent targets in target-table" (let* (;; table mapping from id to those targets immediately ;; dependent on id (dependent-table (make-hash-table :test 'equal)) (explicit-deps (loop for id being the hash-keys in target-table for tar being the hash-values in target-table when (member parameter (target-pdeps tar) :test #'equal) collecting id)) (deps nil)) ;; fill dependent-table (loop for id being the hash-keys in target-table for target being the hash-values in target-table do (loop for d in (target-deps target) do (push id (gethash d dependent-table)))) ;; collect all dependents of explicit-deps and insert into deps (labels ((rec (id) (setf deps (adjoin id deps :test #'equal)) (mapcar #'rec (gethash id dependent-table)))) (mapcar #'rec explicit-deps) deps))) ;;; Caching (defparameter *cache-table* (make-hash-table :test 'equal) "Map from project id to cache function") (defun defcache (cache-fn) "Sets the caching function. cache-fn should be a function which, when given a single target id, manages the cache according to its strategy and leaves the target table in a state such that the result for the given target id is ready to be accessed from the target table. Default behavior is unlimited cache, i.e. all results remain in the target table." (setf (gethash (project) *cache-table*) cache-fn)) (defun cacheres (id) (when (and (or (gethash id (target-table)) (gethash id (gethash *project-id* *fin-target-tables*))) (not (ignored? id))) (let ((cache-fn (gethash (project) *cache-table*))) (if cache-fn (funcall cache-fn id) (open-cache id))))) ;;; Various caching strategies: (defun open-cache (id) "Caching which assumes infinite cache size" (symbol-macrolet ((tar (gethash id (target-table))) (fintar (gethash id (gethash *project-id* *fin-target-tables*)))) (let ((load-stat (target-load-stat (or tar fintar)))) (when (not load-stat) (load-target id))))) (defun singleton-cache (id) "Caching which only allows a single target to be loaded at a time. Minimal memory use, maximal strain on hard drive." (let* ((fintab (gethash *project-id* *fin-target-tables*))) (symbol-macrolet ((tar (gethash id (target-table))) (fintar (gethash id (gethash *project-id* *fin-target-tables*)))) (let ((load-stat (cond (tar (target-load-stat tar)) (fintar (target-load-stat fintar))))) (when (not load-stat) ;; Unload target table ids (loop for unload-id being the hash-keys in (target-table) for unload-tar being the hash-values in (target-table) do (unload-target id)) ;; Unload final target table ids ;; ;; Technically double-unloads target table ids, but it ;; doesn't cost much time. (loop for unload-id being the hash-keys in fintab for unload-tar being the hash-values in fintab do (unload-target unload-id)) (load-target id)))))) (defun fixed-cache (size) "Returns a caching function which limits the number of in-memory targets to size." (let ((cache (make-array size :initial-element nil)) (i 0)) (lambda (id) (symbol-macrolet ((tar (gethash id (target-table))) (fintar (gethash id (gethash *project-id* *fin-target-tables*)))) (let ((load-stat (target-load-stat (or tar fintar)))) (when (not load-stat) ;; this technically excludes NIL from being a target id (when (aref cache i) (unload-target (aref cache i))) (load-target id) (setf (aref cache i) id) (setf i (mod (+ i 1) size)))))))) (defun fixed-mem-cache (maxmem) "Returns a caching function which limits the number of in-memory targets based on how much total memory is currently consumed by the Lisp image in bytes. Uses size of log file as a heuristic for estimating the size needed in active memory, which isn't true for compressed storage, but alas." (flet (;; current memory usage in bytes (mem () #+sbcl (sb-kernel:dynamic-usage)) (logged-size (id) (handler-case (with-open-file (f (target-path id "data") :direction :input) ;; file-length returns KB (* 1000 (file-length f))) (error nil nil)))) (let ((cache nil)) (lambda (id) (symbol-macrolet ((tar (gethash id (target-table))) (fintar (gethash id (gethash *project-id* *fin-target-tables*)))) (let ((load-stat (target-load-stat (or tar fintar)))) ;; this technically excludes NIL from being a target id (when (not load-stat) ;; Clear as much memory as needed, but always try to ;; load. (let* ((size (logged-size id))) (loop for mem = (mem) for total = (+ size mem) while (and cache (> total maxmem)) do (unload-target (pop cache)))) (load-target id) (setf (cdr (last cache)) (list id))))))))) ;; Caching utility functions: (defun unload-target (id) (symbol-macrolet ((tar (gethash id (target-table))) (fintar (gethash id (gethash *project-id* *fin-target-tables*)))) (cond (tar (setf (target-val tar) nil) (setf (target-load-stat tar) nil) (setf (target-val fintar) nil) (setf (target-load-stat fintar) nil)) (fintar (setf (target-val fintar) nil) (setf (target-load-stat fintar) nil))))) ;; Result retrieval (defmacro res (id) "Expands to whatever the symbol for id in project identified by project-id is, nil if id or project not specified." `(resfn ',id)) (defun resfn (id &optional (project-id *project-id*)) (cacheres id) (multiple-value-bind (tar tarstat) (gethash id (gethash project-id *target-tables*)) (if tarstat (target-val tar) (multiple-value-bind (fintab fintabstat) (gethash project-id *fin-target-tables*) (if fintabstat (target-val (gethash id fintab)) (error "target ~a does not exist" id)))))) (defmacro par (id) "Outside of generating function, returns the last used value of a parameter. Inside, expands to whatever the current parameter value is." `(values (gethash ',id (gethash *project-id* *makeres-args*)))) (defun parfn (id) (values (gethash id (gethash *project-id* *makeres-args*)))) ;;;; Additional transformation-induced dependencies ;; defunct (defparameter *trans->added-deps-fn* (make-hash-table :test 'eq)) ;; defunct (defmacro deftransdeps (trans fn) "Assigns function for finding additional transformation-induced dependencies for a given target in a graph. Transformation-induced means any dependencies not found by searching the target expression directly for (res ...) forms. trans should be a graph transformation function. fn should be a function accepting one argument, a target graph, and returning a modified graph with each target having sufficiently many additional dependencies induced by the transformation to allow propogration via makeres-propagate!." `(setf (gethash ,trans *trans->added-deps-fn*) ,fn)) (defparameter *trans->propogator-fn* (make-hash-table :test 'eq)) (defmacro defpropogator (trans fn) "Assigns function for finding additional transformation-induced dependencies for a given target in a graph. Transformation-induced means any dependencies not found by searching the target expression directly for (res ...) forms. trans should be a graph transformation function. fn should be a function accepting one argument, a target graph, and returning a modified graph with each target having sufficiently many additional dependencies induced by the transformation to allow propogration via makeres-propagate!, as well as having the target status for each target be appropriate for makeres-propagate!, as the result graph is what will be checked, not the original target table." `(setf (gethash ,trans *trans->propogator-fn*) ,fn)) ;; Project creation macro ;; ;; Parameters should be: ;; * Project ID ;; * Project path ;; * Transformations ;; * Caching strategy (defmacro defproject (id path transformations cache-strategy &key warnings-p ;; Unless something changes, functions can't ;; be logged (ignore-functions-p t)) "Defines a makeres project. id is unevaluated whereas all other arguments are evaluated. path should be an absolute path. warnings-p controls whether warnings are printed during compilation. ignore-functions-p should be set to T unless you find a way to log functions." `(progn (in-project ,id) (set-project-path ,path) (settrans ,transformations :op :set) (defcache ,cache-strategy) (setf *makeres-warnings* ,warnings-p) ;; This doesn't work due to being called before any targets are ;; defined. The user needs to call load-project after loading ;; his/her project definition. ;; ;; Initialize target-stat for each logged result ;; (init-logged-stats) (when ,ignore-functions-p (logres-ignore-by #'function-target?)))) (defmacro in-project (project-id) "Selects graph identified by graph-id for use. Graph does not need initialization, will be initialized automatically if necessary." `(in-project-fn ',project-id)) (defun in-project-fn (project-id) (setf *project-id* project-id) ;; initialize target table (when (not (gethash project-id *target-tables*)) (setf (gethash project-id *target-tables*) (make-hash-table :test 'equal))) ;; initialize final target table (when (not (gethash project-id *fin-target-tables*)) (setf (gethash project-id *fin-target-tables*) (make-hash-table :test 'equal))) project-id) (defmacro defpars (params) "Adds parameters to project, updating default values for existing parameters." (alexandria:with-gensyms (result ps) `(let* ((,ps ',params) (,result (set-difference (gethash *project-id* *params-table*) ,ps :key (lambda (x) (if (listp x) (first x) x))))) (loop for p in ,ps do (push p ,result)) (setf (gethash *project-id* *params-table*) ,result) nil))) (defmacro undefpars (&rest params) "Undefines parameters in params from project" (alexandria:with-gensyms (ps) `(let ((,ps ',params)) (setf (gethash *project-id* *params-table*) (remove-if (lambda (p) (member p ,ps :test #'equal)) (gethash *project-id* *params-table*)))))) (defmacro defres (id &body body) "Defines a result target with id and value expression `(progn ,@body)." ;; establish symbol mapping (alexandria:with-gensyms (tartab oldtar val stat) `(let* ((,tartab (target-table *project-id*)) (,oldtar (gethash ',id ,tartab)) (,val (if ,oldtar (target-val ,oldtar) nil)) ;; statuses are reset (,stat nil)) (setf (gethash ',id ,tartab) (make-target ',id `(progn ,@',body) :val ,val :stat ,stat)) ',id))) (defun defresfn (id expr) "Defines a result target with id and expression" (let* ((tartab (target-table *project-id*)) (oldtar (gethash id tartab)) (val (if oldtar (target-val oldtar) nil)) ;; statuses are reset (stat nil)) (setf (gethash id tartab) (make-target id (if (or (not (listp expr)) (not (eq (first expr) 'progn))) `(progn ,expr) expr) :val val :stat stat)) id)) (defun defresfn-uniq (id expr) "Defines a result target with id and expression" (let* ((tartab (target-table *project-id*)) (oldtar (gethash id tartab)) (val (if oldtar (target-val oldtar) nil)) ;; statuses are reset (stat nil)) (setf (gethash id tartab) (make-target id (if (or (not (listp expr)) (not (eq (first expr) 'progn))) `(progn ,expr) expr) :val val :stat stat)) id)) (defmacro defres-uniq (id &body body) "Only defines the target if the expression would be different from that already in the target table." (alexandria:with-gensyms (bod) `(let ((,bod `(progn ,@',body))) (when (or (not (gethash ',id (target-table))) (not (equal (target-expr (gethash ',id (target-table))) ,bod))) (defres ,id ,@body))))) (defmacro undefres (&rest res) "Undefines result targets" `(progn ,@(loop for r in res collecting `(progn (remhash ',r (gethash *project-id* *target-tables*)) (remhash ',r (gethash *project-id* *fin-target-tables*)))) nil)) (defun setresfn (id value &optional timestamp) "Function version of setres. Only sets value in target-table if id is present. Creates new target in final target table if one is not present." ;; *target-tables*: (when (gethash id (target-table)) (setf (target-stat (gethash id (target-table))) t) (setf (target-timestamp (gethash id (target-table))) (if timestamp timestamp (get-universal-time))) (setf (target-val (gethash id (target-table))) value) ;; Caching (save-target id) (cacheres id)) ;; *fin-target-tables*: (when (gethash id (gethash *project-id* *fin-target-tables*)) (setf (target-stat (gethash id (gethash *project-id* *fin-target-tables*))) t) (when (gethash id (gethash *project-id* *target-tables*)) (setf (target-timestamp (gethash id (gethash *project-id* *fin-target-tables*))) (target-timestamp (gethash id (gethash *project-id* *target-tables*))))) (setf (target-val (gethash id (gethash *project-id* *fin-target-tables*))) value) ;; Caching (when (not (gethash id (target-table))) (save-target id) (cacheres id)))) (defmacro setres (id value) "Sets target value of id in project to value and the status to t so it will not be recomputed." `(setresfn ',id ,value)) (defun unsetresfn (id) "Function version of unsetres" (setf (target-stat (gethash id (gethash *project-id* *target-tables*))) nil) (when (gethash id (gethash *project-id* *fin-target-tables*)) (setf (target-stat (gethash id (gethash *project-id* *fin-target-tables*))) nil))) (defmacro unsetres (id) "Sets status of target to nil, will be recomputed." `(unsetresfn ',id)) (defun clrresfn () "Function version of clrres" (let ((tartab (gethash *project-id* *target-tables*)) (fintab (gethash *project-id* *fin-target-tables*))) (loop for k being the hash-keys in tartab do (setf (target-stat (gethash k tartab)) nil)) (loop for k being the hash-keys in fintab do (setf (target-stat (gethash k fintab)) nil)))) (defmacro clrres () "Clears all status for result targets in current project" `(clrresfn)) (defun settrans (transforms &key (op :add)) "Takes each transformation function in list transforms (should be names of functions available at compile & load times) and depending on op does something to the project referred to by project-id. transforms will not be evaluated and should be a list form containing the transform functions. op can be :set or :add for setting the entire list of transforms or adding to the front of the transform list. (Front-adding seemed more reasonable since this allows languages to be built on top of previous layers.) Each transformation is a function taking a target table and returning a new target table. The only constraint is that the initial targets be present in the output table. Returns full transformation list from project after applying op." (let ((pid (project))) (case op (:add (setf (gethash pid *transformation-table*) (append transforms (gethash pid *transformation-table*)))) (:set (setf (gethash pid *transformation-table*) transforms))) (gethash pid *transformation-table*))) (defparameter *makeres-warnings* t "Set to nil if you want to suppress warnings from compilation") (defun compseq (forms) "Compiles a sequence of forms sequentially" (loop for i from 1 for f in forms collecting (symbol-function (compile 'compseqfn `(lambda () ,f))))) (defun makeres-forms (fintab &optional (project-id *project-id*)) "Returns the individual target forms for the makeres computation" ;; ensure symbols are defined for fintab (alexandria:with-gensyms (val) (let* ((sorted-ids (depsort-graph fintab)) (set-exprs (progn (loop for id in sorted-ids when ;; old ;; (not (target-stat ;; (gethash id ;; (gethash project-id ;; *fin-target-tables*)))) ;; new (not (target-stat (gethash id fintab))) collecting (let ((tar (gethash id fintab))) `(let ((,val ,(target-expr tar))) (setresfn ',id ,val)))) ))) set-exprs))) (defun makeres-form (fintab) "Returns the form for a function which performs the makeres computation" ;; ensure symbols are defined for fintab (alexandria:with-gensyms (val) (let* ((sorted-ids (depsort-graph fintab)) (set-exprs (progn (loop for id in sorted-ids when (not (target-stat (gethash id (gethash project-id *fin-target-tables*)))) collecting (let ((tar (gethash id fintab))) `(let ((,val ,(target-expr tar))) (setresfn ',id ,val)))) )) (lambda-list (gethash project-id *params-table*)) (params (mapcar (lambda (x) (first (mklist x))) lambda-list)) (body (progn `(progn ;; Save supplied parameter values: ,@(loop for p in params appending `((when (not (equal ,p (gethash ',p (gethash (project) *makeres-args*)))) (setf (gethash ',p (gethash (project) *makeres-args*)) ,p)))) ;; execute computations for targets which need ;; updating. ,@set-exprs nil))) (comp-form `(lambda (&key ,@lambda-list) (macrolet ((par (id) id)) ,body)))) comp-form))) (defun transform-target-table (&optional (project-id *project-id*)) "Returns the fully transformed target table by passing it through the transformation pipeline." (let* ((*copy-target-table-p* nil) (fns (gethash project-id *transformation-table*)) (input (copy-target-table (gethash project-id *target-tables*)))) (if fns (pipe-functions fns input) input))) (defun compres (&optional (project-id *project-id*)) "Returns a compiled function which will generate result targets given keyword arguments for each project parameter. If default values of parameters are specified, these will be used when no explicit value is given." (let ((fintab (transform-target-table project-id))) ;; Update fintab: (setf (gethash project-id *fin-target-tables*) fintab) ;; ensure symbols are defined for fintab (let ((target-fns (if *makeres-warnings* (compseq (makeres-forms fintab)) (suppress-output (compseq (makeres-forms fintab)))))) (lambda (&rest args) (loop for fn in target-fns do (funcall fn)))))) ;; Old version of compres. Compiles a single form, but this started ;; to cost an insane amount of memory. SBCL doesn't handle the large ;; form very well, so now each target form gets its own function, and ;; the functions are called in sequence. (defun compres-old (&optional (project-id *project-id*)) "Returns a compiled function which will generate result targets given keyword arguments for each project parameter. If default values of parameters are specified, these will be used when no explicit value is given." (let ((fintab (transform-target-table project-id))) ;; Update fintab: (setf (gethash project-id *fin-target-tables*) fintab) ;; ensure symbols are defined for fintab (let ((comp-form (makeres-form fintab))) (symbol-function (if *makeres-warnings* (compile (compres-fname project-id) comp-form) (suppress-output (compile (compres-fname project-id) comp-form))))))) ;; Defunct (defun added-dep-graph (graph) (let* ((trans-list (gethash (project) *transformation-table*)) (added-fns (remove nil (mapcar (lambda (x) (gethash x *trans->added-deps-fn*)) trans-list)))) (pipe-functions added-fns graph))) (defun transforms-propagate (graph) "Propagates as makeres-propagate! would but for special cases which graph transformations must individually manage." (let* ((trans-list (gethash (project) *transformation-table*)) (propogators (remove nil (mapcar (lambda (x) (gethash x *trans->propogator-fn*)) trans-list)))) (pipe-functions propogators graph))) (defun makeres-propagate! () (let ((graph (transforms-propagate (target-table)))) (loop for id being the hash-keys in graph for tar being the hash-values in graph do (when (null (target-stat tar)) (loop for r in (res-dependents id graph) when (gethash r (target-table)) do (unsetresfn r)))))) (defvar *sticky-pars* t "Set to nil if you don't want default values to be updated by new args to makeres") (defun makres-set-sticky-pars (stat) (setf *sticky-pars* stat) "Sets sticky parameter switch; non-nil means new values given to makeres are used for the new default value.") (defvar *proj->par->def-last?* (make-hash-table :test #'equal) "map from project to parameter to whether the last value given was the default value or not") (defun par-def-last? (par) (gethash par (gethash *project-id* *proj->par->def-last?*))) (defun par-set-last? (par) (second (multiple-value-list (gethash par (gethash *project-id* *makeres-args*))))) (defun par-empty-last? (par) "Returns true if parameter was neither default last time nor had an explicit value set" (not (or (par-def-last? par) (par-set-last? par)))) (defun assert-par-def-last! (par def-last-p) "Assert that parameter's value was default last time" (setf (gethash par (gethash *project-id* *proj->par->def-last?*)) def-last-p)) (defun par-needs-updating? (par args) "Returns true if parameter par needs updating given the argument list args" (let ((pkeysym (keywordify par)) (arg-map (map->hash-table (plist->alist args) 'eq))) (multiple-value-bind (argval argstat) (gethash pkeysym arg-map) (multiple-value-bind (lastval laststat) (gethash par (gethash *project-id* *makeres-args*)) (if (par-empty-last? par) t (if *sticky-pars* ;; sticky case argstat ;; non-sticky case (if (par-def-last? par) argstat ;; par-set-last? (or (null argstat) (not (equal argval lastval)))))))))) (defun computation-stat-path () "Returns the path for the computation status file" (let ((path (make-pathname :name "stat" :directory (pathname-directory (current-path))))) (ensure-directories-exist path))) (defun makeres () "Function which compiles and executes generating function." (let ((all-args nil)) (when (not (gethash *project-id* *makeres-args*)) (setf (gethash *project-id* *makeres-args*) (make-hash-table :test 'eq))) (when (not (gethash *project-id* *proj->par->def-last?*)) (setf (gethash *project-id* *proj->par->def-last?*) (make-hash-table :test 'eq))) ;; argument parsing: (let* ((targets (if (keywordp (first all-args)) (project-targets) (first all-args))) (args (if (keywordp (first all-args)) all-args (rest all-args)))) ;; unset any results dependent on new parameter values (let* ((params (gethash *project-id* *params-table*)) (arg-map (map->hash-table (plist->alist args) 'eq))) (loop for p in params do (let ((psym (first (mklist p)))) (multiple-value-bind (val stat) (gethash (keywordify psym) arg-map) (multiple-value-bind (oldval oldstat) (gethash psym (gethash *project-id* *makeres-args*)) (when (par-needs-updating? psym args) (when stat (setf (gethash psym (gethash *project-id* *makeres-args*)) val)) (let ((pdeps (param-dependents psym (gethash *project-id* *target-tables*)))) (loop for pdep in pdeps do (progn (unsetresfn pdep))))) ;; remove from stored table if not specified and not sticky: (when (and (not *sticky-pars*) (null stat)) (remhash psym (gethash *project-id* *makeres-args*)))))))) ;; When sticky pars update args: (when *sticky-pars* (loop for psym being the hash-keys in (gethash *project-id* *makeres-args*) do (when (second (multiple-value-list (gethash psym (gethash *project-id* *makeres-args*)))) (setf (getf args (keywordify psym)) (gethash psym (gethash *project-id* *makeres-args*)))))) ;; Perform sanity check on the target table: (when (not (checkres)) (error "Target table fails checkres test")) ;; Whenever *makeres-propagate* is non-nil, unset any results ;; dependent on null-stat results (when *makeres-propagate* (makeres-propagate!)) (let ((comp (compres))) ;; Write computation status file: (let ((*print-pretty* nil)) (with-open-file (stat-file (computation-stat-path) :direction :output :if-does-not-exist :create :if-exists :supersede) (let ((timestamp (get-universal-time)) (to-compute (loop for id being the hash-keys in (target-table) for tar being the hash-values in (target-table) when (null (target-stat tar)) collecting id))) (format stat-file "~a~%~a~%" timestamp to-compute)))) (apply comp args) (delete-file (computation-stat-path)) ;; NOTE: I'm not sure if tables which are in the final target ;; table which get unloaded and then reloaded will cause ;; memory leaks. In the future, it might be necessary to ;; Prune the targets not present in the target table ;; ;; NOTE: In the future, it might be nicer to just remove final ;; targets not present in the target table instead of pruning ;; the whole log, but right now this is a good substitute (pruneres t))))) ;;;; Utilities: (defun target-ids (&optional (filter #'identity)) "Returns list of IDs for defined targets in project. filter should be a function taking an ID as an argument and returning T for IDs which should be shown." (remove-if-not filter (hash-keys (gethash *project-id* *target-tables*)))) (defun fin-target-ids () "Returns list of ids for defined targets in final target table." (hash-keys (gethash *project-id* *fin-target-tables*))) ;; Could create print representation of targets, that way there could ;; just be targets and fin-targets as functions which would return all ;; project targets and final target table targets. ;; Inspects target table to see if there are spurious references to ;; targets (defun checkres (&optional target-table) (let ((target-table (if target-table target-table (target-table))) (*print-pretty* nil) (result t)) (loop for id being the hash-keys in target-table for tar being the hash-values in target-table do (loop for dep in (target-deps tar) do (when (not (gethash dep target-table)) (setf result nil) (format t "~s: ~s not present in target-table~%" id dep)))) result)) ;; Deletes target logs for targets which are not present in the ;; target-table. (defun pruneres (&optional delete-p) (let* ((logged-paths (mapcar #'pathname (directory (merge-pathnames "**" (merge-pathnames "targets/" (current-path)))))) (logged-id-strings (mapcar (lambda (pn) (read-from-string (first (last (pathname-directory pn))))) logged-paths)) (*print-pretty* nil)) (loop for logged-id in logged-id-strings for logged-path in logged-paths do (when (or (not (gethash logged-id (target-table))) (ignored? logged-id)) (if delete-p (progn (format t "Deleting ~a~%" logged-id) (uiop:delete-directory-tree logged-path :validate t)) (format t "~a not tracked~%" logged-id)))))) (defun purgeres (&optional delete-p) "Finds targets which have null statuses and optionally deletes their logs." (let ((null-stats (loop for id being the hash-keys in (target-table) for tar being the hash-values in (target-table) when (and (not (target-stat tar)) (probe-file (target-path id))) collecting id))) (if delete-p (loop for id in null-stats do (progn (format t "Deleting ~s~%" id) (uiop:delete-directory-tree (make-pathname :directory `(:absolute ,(target-path id))) :validate t))) (loop for id in null-stats do (format t "~s~%" id))))) (defun printres (&optional (filter (constantly t))) "Prints the target-table with optional filter function which takes two arguments (id and value) to determine which targets to print." (let ((map (mapcar (lambda (cons) (cons (car cons) (resfn (car cons)))) (map->alist (target-table))))) (format t "Target Table:~%") (loop for cons in map when (funcall filter (car cons) (cdr cons)) do (format t "~a: ~a~%" (car cons) (cdr cons))))) ;; Utility functions used by mvres: (defun replace-id (old new form) "Replaces (res old) with (res new) wherever it occurs in a form." (subst `(res ,new) `(res ,old) form :test #'equal)) (defun replace-log-id (old new path) (let* ((*print-pretty* nil) (oldform (read-from-string (with-open-file (file path :direction :input) (read file)))) (newform (replace-id old new oldform))) ;; write new form: (with-open-file (file path :direction :output :if-exists :supersede :if-does-not-exist :create) (format file "~s~%" (with-output-to-string (s) (format s "~s" newform)))))) (defun mvres (old-id new-id &key quiet-p) "Moves a target from old-id to new-id in the target-table, final-target-table, the logged target path, and in any existing logged forms. This process is potentially irreversible, so backups may be expedient. Set quiet-p to non-NIL to disable progress messages." ;; Check if old-id is in the target-table: (when (gethash old-id (target-table)) ;; Move in target-table (let* ((tar (gethash old-id (target-table)))) ;; Move log (when (not (ignored? old-id)) (when (not quiet-p) (format t "Moving log...~%")) (rename-file (target-path old-id) (target-path new-id))) (when (not quiet-p) (format t "Moving in target-table...~%")) ;; delete hash-table entry (remhash old-id (target-table)) ;; modify target (setf (target-id tar) new-id) ;; Add new target to table: (setf (gethash new-id (target-table)) tar)) ;; Modify all affected targets: (loop for id being the hash-keys in (target-table) do (symbol-macrolet ((tar (gethash id (target-table)))) (when (member old-id (target-deps tar) :test #'equal) (when (not quiet-p) (format t "Modifying ~a~%" id)) (setf (target-deps tar) (mapcar (lambda (i) (if (equal i old-id) new-id i)) (target-deps tar))) (when (not (ignored? id)) (replace-log-id old-id new-id (target-path id "form"))) (setf (target-expr tar) (replace-id old-id new-id (target-expr tar)))))) ;; Move in final-target-table (symbol-macrolet ((fintab (gethash (project) *fin-target-tables*))) (when (gethash old-id fintab) (when (not quiet-p) (format t "Moving in \"fintab\"...~%")) (let* ((tar (gethash old-id fintab))) ;; delete hash-table entry (remhash old-id fintab) ;; modify target (setf (target-id tar) new-id) ;; Add new target to table: (setf (gethash new-id fintab) tar)) ;; Modify all affected targets: (loop for id being the hash-keys in fintab do (symbol-macrolet ((tar (gethash id fintab))) (when (member old-id (target-deps tar) :test #'equal) (when (not quiet-p) (format t "Modifying ~a~%" id)) (setf (target-deps tar) (mapcar (lambda (i) (if (equal i old-id) new-id i)) (target-deps tar))) (setf (target-expr tar) (replace-id old-id new-id (target-expr tar)))))))))) (defun unsetdepsfn (id &key quiet-p) "Unsets all dependencies of id in the target-table. Set quiet-p to non-NIL to disable progress messages." (when (gethash id (target-table)) (let ((graph (transforms-propagate (target-table)))) (loop for dep in (res-dependents id graph) do (when (not quiet-p) (format t "Unsetting ~s~%" dep)) (unsetresfn dep))))) (defmacro unsetdeps (id &key quiet-p) "Macro version of unsetresfn. id is unevaluated, quiet-p is." `(unsetdepsfn ',id :quiet-p ,quiet-p)) ;; Utility macro which evaluates the expression for a given target: (defmacro evres (id) (target-expr (gethash id (target-table)))) ;; and the function (defun evresfn (id) (eval `(evres ,id))) ;; Utility function to naively compute all targets which haven't been ;; evaluated yet without using the transformation pipeline. (defun makeres-naive (&optional ids) (let* ((ids (if ids ids (hash-keys (target-table))))) (loop for id in ids for tar = (gethash id (target-table)) when (not (target-stat tar)) do (setresfn id (evresfn id)))))
68,599
Common Lisp
.lisp
1,756
28.502278
86
0.562264
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
77d6b21c54fbdb59b76e84ae708e01ed79067ba87cd29a4e0b32433f2154476c
1,634
[ -1 ]
1,635
array.lisp
ghollisjr_cl-ana/makeres/array.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.makeres) ;; fix in the future (defmethod printable ((vector array)) nil) (defmethod save-object ((vector array) path) (let* ((savedir (make-pathname :directory (namestring path))) (indexpath (merge-pathnames "index" savedir))) (ensure-directories-exist savedir) (let ((index-list (loop for elt across vector for i from 0 collect (let ((type (target-type elt))) (save-object elt (merge-pathnames (mkstr i) savedir)) (list i type))))) (with-open-file (file indexpath :direction :output :if-exists :supersede :if-does-not-exist :create) (format file "~a~%" index-list))))) (defmethod load-object ((type (eql 'array)) path) (let* ((loaddir (make-pathname :directory (namestring path))) (indexpath (merge-pathnames "index" loaddir))) (let ((index-list nil)) (with-open-file (file indexpath :direction :input :if-does-not-exist :error) (setf index-list (read file))) (map 'vector (lambda (elt) (destructuring-bind (elt-id elt-type) elt (load-object elt-type (merge-pathnames (mkstr elt-id) loaddir)))) index-list))))
2,574
Common Lisp
.lisp
68
26.911765
70
0.538369
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
e2df8b833cba53caac9719f6664c165583531168eaefeee3e1a588e97ad3cc58
1,635
[ -1 ]
1,636
makeres-test.lisp
ghollisjr_cl-ana/makeres/makeres-test.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (require 'cl-ana) (in-package :cl-ana) ;;;; Demo of language: ;;; Must use/select a project before using makeres ;; Select project (in-project test) ;; project ID can be any lisp form ;; Select transformations (simply omit this expression if you don't ;; want any): (settrans (list #'lrestrans)) ;; We're using the logical result transformation ;; Define parameters for project (defpars ((source (list 1 2 3 4 5 6 7)) (scale 1))) ;; Each parameter form will be used in a keyword lambda-list, so you ;; can provide default values if you like or just use a symbol if ;; default should be nil. ;;; Results to be computed are defined via defres. Arguments are an ;;; id (any lisp form) and a body of expressions to be evaluated to ;;; yield the value. ;;; ;;; Note that the transformation pipeline can give meaning to ;;; otherwise invalid expressions, making it possible to define DSLs ;;; for use with makeres which would be unwieldy otherwise. ;; Notice that (par source) is used to refer to the parameter "source" (defres filtered (print 'filtered) (remove-if (lambda (x) (< x 5)) (par source))) ;; Notice that (res filtered) is used to refer to the result target ;; "filtered" (defres squared (print 'squared) (mapcar (lambda (x) (* x x)) (res filtered))) ;; And this combines par and res. Also notice that target ids can be ;; any form, not just symbols (defres (sum scaled) (print '(sum scaled)) (* (par scale) (+ (res filtered) (res squared)))) ;; To demonstrate the logical result transformation, we'll define a ;; logical result target: (defres lres-test (lres (print 'lres-test))) ;;; execute (makeres) to test. makeres accepts keyword arguments for ;;; whatever have been defined via defpars. (makeres) ;; or with other arguments: (makeres :source (list 9 10)) (makeres :source (list 9 15) :scale -1) ;;; After you've run whatever computations you're interested in, you ;;; can examine the results with the res macro: (print (res filtered)) (print (res squared)) (print (res (sum scaled))) ;;; You can also examine what the last parameter values were: (print (par source)) (print (par scale))
3,089
Common Lisp
.lisp
84
34.380952
70
0.708068
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
8b823559b2950bb0a2c099749987d18bd7f6ad718242920ccc8523b8c4ab73f6
1,636
[ -1 ]
1,637
test.lisp
ghollisjr_cl-ana/makeres/test.lisp
(require 'cl-ana) (in-package :cl-ana) (defproject makeres-test "/home/ghollisjr/cl-ana/makeres/makeres-test" (list #'macrotrans #'progresstrans) #'singleton-cache) (defres a (list 1 2 3 4)) (defres (a sum) (sum (res a))) (defres b 5) (defres (+ a b) (+ (res a) (res b))) (defres craziness (range 1 2)) (defres z (+ (res a) (res b) (res (+ a b)))) (defres snapshot-test 'a) (defres fn (lambda () (print t))) (defres delayed (sleep 5) t) (defres delayed2 (and (res delayed) (sleep 5)) t)
557
Common Lisp
.lisp
33
13.757576
49
0.615234
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
85dc569ded4f8fca9cc1e2a85d975ba1f65e2aa81d06b5d30bfbed30e90ed50f
1,637
[ -1 ]
1,638
histogram.lisp
ghollisjr_cl-ana/makeres/histogram.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.makeres) (defmethod printable ((h histogram)) nil) (defmethod save-object ((h histogram) path) (with-open-hdf-file (file path :direction :output :if-exists :supersede :if-does-not-exist :create) (write-histogram h file "/histogram"))) (defmethod load-object ((type (eql 'sparse-histogram)) path) (with-open-hdf-file (file path :direction :input :if-does-not-exist :error) (read-histogram file "/histogram" :sparse))) (defmethod load-object ((type (eql 'contiguous-histogram)) path) (with-open-hdf-file (file path :direction :input :if-does-not-exist :error) (read-histogram file "/histogram" :contiguous)))
1,719
Common Lisp
.lisp
39
37.307692
70
0.637015
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
eeded6830419c906de1ce73b8cd0d030b17f65356587956811b99f0b6956c8cb
1,638
[ -1 ]
1,639
string.lisp
ghollisjr_cl-ana/makeres/string.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.makeres) (defmethod printable ((str string)) t) (defmethod load-object ((type (eql 'string)) path) (with-open-file (file path :direction :input :if-does-not-exist :error) (read file))) (defmethod save-object ((str string) path) (with-open-file (file path :direction :output :if-exists :supersede :if-does-not-exist :create) (format file "~s~%" str)))
1,376
Common Lisp
.lisp
34
35.411765
70
0.649477
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
c7c2ca63eac8ad9a0609e41463e9115e992ed676b1c3970679e6c6eb7d9017af
1,639
[ -1 ]
1,640
package.lisp
ghollisjr_cl-ana/statistics/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (defpackage #:cl-ana.statistics (:use :cl :cl-ana.macro-utils :cl-ana.map :cl-ana.list-utils :cl-ana.histogram :cl-ana.math-functions) (:shadow :mean :standard-deviation) (:export :mean :variance :standard-deviation :standard-scores ;; general sample moment function: :sample-moment ;; general k-statistic function: :k-statistic :skewness :kirtosis :moving-average :quantiles :percentiles :qq-plot :determination-coefficient :anderson-darling-normality-test :shaped-random)) (cl-ana.gmath:use-gmath :cl-ana.statistics)
1,627
Common Lisp
.lisp
47
28.510638
70
0.637516
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
08d57a5f435d14774b5b4ea7fe45c14d04fd7e519b5b6930c8ab01488b3f6d67
1,640
[ -1 ]
1,641
statistics.lisp
ghollisjr_cl-ana/statistics/statistics.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.statistics) (defgeneric mean (data) (:documentation "Returns mean (and count) of data") (:method (data) (let ((count (length data))) (values (/ (sum data) count) count))) (:method ((hist histogram)) (let ((count (htint hist))) (values (/ (sum (mapcar (lambda (x) (dbind (c x) x (* c x))) (hbv hist))) count) count)))) (defgeneric variance (data) (:documentation "Returns variance of data") (:method (data) (multiple-value-bind (mean count) (mean data) (/ (sum (map 'list (lambda (x) (expt (- x mean) 2)) data)) (- count 1)))) (:method ((hist histogram)) (multiple-value-bind (mean count) (mean hist) (/ (sum (mapcar (lambda (x) (dbind (c x) x (* c (expt (- x mean) 2)))) (hbv hist))) (- count 1))))) (defun standard-deviation (data) (sqrt (variance data))) (defun standard-scores (data) "Returns the list of standard-scores (number of standard deviations away from the mean) for the data" (let ((mean (mean data)) (sigma (standard-deviation data))) (mapcar (lambda (x) (/ (- x mean) sigma)) data))) (defun sample-moment (data &key (order 1) (type :r)) "Returns the order-th sample moment of the data according to type. type can be :r (raw), :c (central), or :s (standardized). second return value is size of data sample." (case type ;; raw (:r (mean (mapcar (lambda (x) (expt x order)) data))) (:c (let ((mean (mean data))) (mean (mapcar (lambda (x) (expt (- x mean) order)) data)))) (:s (let ((mean (mean data)) (sigma (standard-deviation data))) (mean (mapcar (lambda (x) (expt (/ (- x mean) sigma) order)) data)))))) ;; Technically, all the standard moments like mean, variance, ;; skewness, etc. should come from this k-statistic function, but ;; since I can't seem to find a reference which gives a formula for ;; all of them, I'm stuck with this approach where I basically splice ;; the function together. (defun k-statistic (data order) "Returns the orderth k-statistic (unbiased estimator of orderth cumulant)" (case order (1 (mean data)) (2 (variance data)) (3 (multiple-value-bind (m3 n) (sample-moment data :order 3 :type :c) (* n n (/ (* (- n 1) (- n 2))) m3))) (4 (multiple-value-bind (m4 n) (sample-moment data :order 4 :type :c) (let ((m2 (sample-moment data :order 2 :type :c))) (/ (* n n (- (* (+ n 1) m4) (* 3 (- n 1) m2 m2))) (* (- n 1) (- n 2) (- n 3)))))))) (defun skewness (data) (k-statistic data 3)) (defun kirtosis (data) (k-statistic data 4)) (defun quantiles (data) "Returns an alist mapping each datum to its quantile." (let ((denom (+ 1 (length data))) (compressed (compress data :test #'equal :singleton-pairs t :sort-by #'<)) (acc 0d0)) (loop for (x . c) in compressed do (incf acc c) collecting (cons x (/ acc denom)) into result finally (return result)))) (defun qq-plot (data cdf-inv) "Returns data suitable for a Q-Q probability scatter plot given data and inverse of cummulative density function. Useful for checking whether data is distributed according to cdf or not." (mapcar (lambda (x) (cons (funcall cdf-inv (cdr x)) (car x))) (quantiles data))) (defun percentiles (data) "Returns an alist mapping each datum to its percentile." (let ((denom (length data)) (compressed (compress (sort (copy-list data) #'<) :test #'equal :singleton-pairs t)) (acc 0d0)) (loop for (x . c) in compressed do (incf acc c) collecting (cons x (/ acc denom)) into result finally (return result)))) (defun mean-accumulator (&rest sample) "Utility function used by moving-average. Returns two values: 1. A function which returns the (updated) moving/running average each time you call it on a value. The samples you give provide the initilization data and the size of the data subset to maintain while computing the moving average. 2. The initial value for the moving average; this is so that subsequent calls on the moving average function will return the immediate updated mean." (let* ((lst (copy-list sample)) (length (length lst)) (end (last lst)) (initial-mean (/ (sum lst) length))) (values (lambda (x) (setf (cdr end) (list x)) (setf end (cdr end)) (setf lst (rest lst)) (/ (sum lst) length)) initial-mean))) (defun moving-average (data subset-length) "Returns a list of the moving averages on the data (must be a list) with subsets of length subset-length. subset-length is not checked to be in bounds, so be careful." (multiple-value-bind (acc init-mean) (apply #'mean-accumulator (subseq data 0 subset-length)) (cons init-mean (mapcar acc (subseq data subset-length))))) (defun determination-coefficient (data function) "Calculates R^2, or the coefficient of determination, for the function against the data. data should have type with map->alist defined." (let ((alist (map->alist data))) (- 1 (/ (sum (expt (mapcar (lambda (cons) (- (funcall function (car cons)) (cdr cons))) alist) 2)) (let* ((ys (mapcar #'cdr alist)) (mean (mean ys))) (sum (expt (mapcar (lambda (x) (- x mean)) ys) 2))))))) ;; Anderson-Darling normality test (defun anderson-darling-normality-test (data &key (critical 2.492)) "Applies Anderson-Darling test for normality. Returns true if normal, or NIL if not. Critical selects the critical value. Common values are: 1.621 for 15% 1.933 for 10% 2.492 for 5% 3.070 for 2.5% 3.878 for 1%" (let* ((cv critical) (z-scores (sort (standard-scores data) #'<)) (n (length data)) (sum (loop for i from 1 for z in z-scores summing (+ (* (- (* 2 i) 1) (log (normal-cdf z))) (* (+ (* 2 (- n i)) 1) (log (- 1 (normal-cdf z))))))) (test (+ (- n) (- (/ sum (->double-float n)))))) (values (<= test cv) test))) ;;;; Generating random data: (defun shaped-random (inverse-cdf) "Generates 1-D random data using the inverse-cdf to provide the shape." (funcall inverse-cdf (random 1d0)))
8,810
Common Lisp
.lisp
252
24.84127
73
0.522554
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
f64a0c825255bfc1fa5cca8758872470cbe913df59eeb0741744f876dbf68d95
1,641
[ -1 ]
1,642
test.lisp
ghollisjr_cl-ana/statistics/test.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (require 'cl-ana.statistics) (in-package :cl-ana.statistics) (print (moving-average (list 1f0 2f0 3f0 4f0 5f0 6f0) 2))
1,012
Common Lisp
.lisp
25
38.48
70
0.703252
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
54a32ecf6fd4735ac8ee4ac148f553bfa558d6a71370176aad5218f1afbfbd96
1,642
[ -1 ]
1,643
package.lisp
ghollisjr_cl-ana/int-char/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (defpackage #:cl-ana.int-char (:use :cl) (:export :int-char))
938
Common Lisp
.lisp
23
39.434783
70
0.704918
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
768714b50bbd08a4fbc9eea4685adc52b26a2871bef342a43fde2daf83ac2f2a
1,643
[ -1 ]
1,644
int-char.lisp
ghollisjr_cl-ana/int-char/int-char.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.int-char) (defparameter *printable-ascii-codes* (list (cons 32 #\Space) (cons 33 #\!) (cons 34 #\") (cons 35 #\#) (cons 36 #\$) (cons 37 #\%) (cons 38 #\&) (cons 39 #\') (cons 40 #\() (cons 41 #\)) (cons 42 #\*) (cons 43 #\+) (cons 44 #\,) (cons 45 #\-) (cons 46 #\.) (cons 47 #\/) (cons 48 #\0) (cons 49 #\1) (cons 50 #\2) (cons 51 #\3) (cons 52 #\4) (cons 53 #\5) (cons 54 #\6) (cons 55 #\7) (cons 56 #\8) (cons 57 #\9) (cons 58 #\:) (cons 59 #\;) (cons 60 #\<) (cons 61 #\=) (cons 62 #\>) (cons 63 #\?) (cons 64 #\@) (cons 65 #\A) (cons 66 #\B) (cons 67 #\C) (cons 68 #\D) (cons 69 #\E) (cons 70 #\F) (cons 71 #\G) (cons 72 #\H) (cons 73 #\I) (cons 74 #\J) (cons 75 #\K) (cons 76 #\L) (cons 77 #\M) (cons 78 #\N) (cons 79 #\O) (cons 80 #\P) (cons 81 #\Q) (cons 82 #\R) (cons 83 #\S) (cons 84 #\T) (cons 85 #\U) (cons 86 #\V) (cons 87 #\W) (cons 88 #\X) (cons 89 #\Y) (cons 90 #\Z) (cons 91 #\[) (cons 92 #\\) (cons 93 #\]) (cons 94 #\^) (cons 95 #\_) (cons 96 #\`) (cons 97 #\a) (cons 98 #\b) (cons 99 #\c) (cons 100 #\d) (cons 101 #\e) (cons 102 #\f) (cons 103 #\g) (cons 104 #\h) (cons 105 #\i) (cons 106 #\j) (cons 107 #\k) (cons 108 #\l) (cons 109 #\m) (cons 110 #\n) (cons 111 #\o) (cons 112 #\p) (cons 113 #\q) (cons 114 #\r) (cons 115 #\s) (cons 116 #\t) (cons 117 #\u) (cons 118 #\v) (cons 119 #\w) (cons 120 #\x) (cons 121 #\y) (cons 122 #\z) (cons 123 #\{) (cons 124 #\|) (cons 125 #\}) (cons 126 #\~))) (defparameter *ascii-map* (make-hash-table :test 'equal)) (loop for (code . char) in *printable-ascii-codes* do (setf (gethash code *ascii-map*) char)) (defun int-char (integer) (gethash integer *ascii-map*))
2,832
Common Lisp
.lisp
126
18.952381
70
0.545354
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
ba860a539aab5e0de789664e94a0d5b36e4f63c55b26586a583de026d12fb55d
1,644
[ -1 ]
1,645
package.lisp
ghollisjr_cl-ana/hdf-typespec/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; package.lisp (defpackage #:cl-ana.hdf-typespec (:use :cl :cffi :hdf5 :cl-ana.list-utils :cl-ana.string-utils :cl-ana.symbol-utils :cl-ana.memoization :cl-ana.typespec :alexandria) (:export :typespec->hdf-type :hdf-type->typespec))
1,140
Common Lisp
.lisp
33
32.454545
70
0.701627
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
d6d4fc2c4c62177a028da6115857ad5898044ef5616d490a06c9f1c60768405b
1,645
[ -1 ]
1,646
hdf-typespec.lisp
ghollisjr_cl-ana/hdf-typespec/hdf-typespec.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.hdf-typespec) ;;; hdf-cffi interface utilities: (defparameter *hdf-cffi-type-map* (list (cons hdf5:+H5T-NATIVE-CHAR+ :char) (cons hdf5:+H5T-NATIVE-UCHAR+ :uchar) (cons hdf5:+H5T-NATIVE-SHORT+ :short) (cons hdf5:+H5T-NATIVE-USHORT+ :ushort) (cons hdf5:+H5T-NATIVE-INT+ :int) (cons hdf5:+H5T-NATIVE-UINT+ :uint) (cons hdf5:+H5T-NATIVE-LLONG+ :long-long) (cons hdf5:+H5T-NATIVE-ULLONG+ :ullong) (cons hdf5:+H5T-NATIVE-FLOAT+ :float) (cons hdf5:+H5T-NATIVE-DOUBLE+ :double))) (defun cffi-native-type (hdf-native-type) (cdr (find hdf-native-type *hdf-cffi-type-map* :key #'car :test (lambda (t1 t2) (let ((cmp (hdf5:h5tequal t1 t2))) (if (zerop cmp) nil t)))))) (defun hdf-native-type (cffi-native-type) (car (rassoc cffi-native-type *hdf-cffi-type-map*))) ;; defines the structure as an hdf type if necessary from the typespec. (defun-memoized typespec->hdf-type (typespec) ;; (defun typespec->hdf-type (typespec) (if (listp typespec) ;; handle compound and array types (case (first typespec) ;; array typespec: (:array type rank dim-list) (:array (let ((type (typespec->hdf-type (typespec-array-element-type typespec))) (rank (typespec-array-rank typespec)) (dim-list (typespec-array-dim-list typespec))) (with-foreign-object (dims 'hsize-t rank) (loop for d in dim-list for i from 0 do (setf (mem-aref dims 'hsize-t i) d)) (hdf5:h5tarray-create2 type rank dims)))) (:compound (let* ((names (typespec-compound-field-names typespec)) (specs (typespec-compound-field-specs typespec)) (hdf-types (mapcar #'typespec->hdf-type specs)) (slot-symbols (mapcar (compose #'keywordify #'intern #'string) names)) (cstruct (typespec->cffi-type typespec)) (offsets (mapcar (lambda (x) (foreign-slot-offset cstruct x)) slot-symbols)) (compound-tid (hdf5:h5tcreate :H5T-COMPOUND (foreign-type-size cstruct)))) (loop for name in names for offset in offsets for type in hdf-types do (hdf5:h5tinsert compound-tid name offset type)) compound-tid))) ;; return the hdf type corresponding to the cffi type: (hdf-native-type typespec))) ;; Construct typespec from hdf type: (defun h5tget-member-name-as-lisp-string (hdf-type i) (let* ((name (hdf5:h5tget-member-name hdf-type i)) (lisp-name (cffi:foreign-string-to-lisp name))) (cffi:foreign-free name) lisp-name)) (defun-memoized hdf-type->typespec (hdf-type) ;; (defun hdf-type->typespec (hdf-type) ;; may need cleaning up (let ((hdf-class (hdf5:h5tget-class hdf-type))) (case hdf-class (:H5T-INTEGER (cffi-native-type (hdf5:h5tget-native-type hdf-type :H5T-DIR-DEFAULT))) (:H5T-FLOAT (cffi-native-type (hdf5:h5tget-native-type hdf-type :H5T-DIR-DEFAULT))) (:H5T-ARRAY (let* ((base-type (hdf5:h5tget-super hdf-type)) (native-base-type (hdf5:h5tget-native-type base-type :H5T-DIR-DEFAULT)) (array-rank (hdf5:h5tget-array-ndims hdf-type))) (with-foreign-object (array-dims-pointer 'hsize-t array-rank) (hdf5:h5tget-array-dims2 hdf-type array-dims-pointer) (let (array-dims) (dotimes (index array-rank) (push (mem-aref array-dims-pointer 'hsize-t index) array-dims)) (append (list :array) (list (cffi-native-type native-base-type)) array-dims))))) (:H5T-COMPOUND (let* ((nmembers (hdf5:h5tget-nmembers hdf-type)) (names (loop for i from 0 to (1- nmembers) collecting (h5tget-member-name-as-lisp-string hdf-type i))) (member-typespecs (loop for i from 0 to (1- nmembers) collecting (hdf-type->typespec (hdf5:h5tget-member-type hdf-type i)))) (names-specs (zip names member-typespecs))) (cons :compound names-specs))))))
5,025
Common Lisp
.lisp
121
34.768595
78
0.638202
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
e29a793ca6798e6d1262259fdf3b02cb1826452faca306c243287ba4db0474fe
1,646
[ -1 ]
1,647
package.lisp
ghollisjr_cl-ana/package-utils/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (defpackage #:cl-ana.package-utils (:use :cl :alexandria) (:export :shadowing-use-package :add-package-to-group :defpackage-in-group :use-package-group))
1,072
Common Lisp
.lisp
27
36.851852
70
0.690613
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
28654d21a9576ac9d235d059ffa496b29fef7fe221946e97013615bba92004fe
1,647
[ -1 ]
1,648
package-utils.lisp
ghollisjr_cl-ana/package-utils/package-utils.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.package-utils) (defun shadowing-use-package (from-package &optional to-package) "shadowing-imports all the exported symbols from gmath into the current package" (let ((from-pac (find-package from-package)) (to-pac (if to-package (find-package to-package) *package*))) (do-external-symbols (s from-pac) (let ((sym (find-symbol (string s) from-pac))) (unintern sym to-pac) (shadowing-import sym to-pac))))) ;;;; Package Groups ;;; A package group is simply a collection of packages. The concept ;;; is useful for maintaining a high degree of modularity: Instead of ;;; creating a single common package for a set of functionality, each ;;; individual piece of the software can have its own package and then ;;; the combined exported symbols can easily be imported into another ;;; package via a package group. (defvar *package-groups* (make-hash-table :test 'equal)) (defun add-package-to-group (package group) "Adds the package to the package group given by group." (let ((pac (find-package package))) (symbol-macrolet ((hash-value (gethash group *package-groups*))) (setf hash-value (adjoin pac hash-value :test #'equal))))) (defmacro defpackage-in-group (package-name group &body package-body) "Defines a package while placing this package into the group specified by group. group can technically be any object, but I like to stick to keyword symbols. Any package statements can be used in the package-body portion." (with-gensyms (pac-name) `(let ((,pac-name ,package-name)) (defpackage ,pac-name ,@package-body) (add-package-to-group ,pac-name ,group)))) (defun use-package-group (group &optional dest-package) "Calls shadowing-use-package on each package in group and either the current package or dest-package." (let ((packages (gethash group *package-groups*)) (dest-pac (if dest-package dest-package *package*))) (loop for p in packages do (shadowing-use-package p dest-pac))))
3,023
Common Lisp
.lisp
70
38.642857
70
0.690767
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
346e4e3bf0a7121d95e1338d2e6672a8b1ac77a13f6a5a7b3c8757ae2e02a7bf
1,648
[ -1 ]
1,649
package.lisp
ghollisjr_cl-ana/makeres-macro/package.lisp
;;;; makeres-macro is a Common Lisp make-like tool for computations. ;;;; Copyright 2014 Gary Hollis ;;;; ;;;; This file is part of makeres-macro. ;;;; ;;;; makeres-macro 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. ;;;; ;;;; makeres-macro 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 makeres-macro. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis via email at ;;;; [email protected] (defpackage #:cl-ana.makeres-macro (:use :cl :cl-ana.list-utils :cl-ana.makeres) (:export :define-res-macro :define-res-function :expand-res-macros :add-binding-ops :macrotrans :ensure-binding-ops :*proj->binding-ops* :ensure-op-expanders :*proj->op->expander*))
1,277
Common Lisp
.lisp
33
34.272727
77
0.672566
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
a633cf831b37c0b6687f784fa6357287f573ef0f3277ac3804d09719acbcc6a2
1,649
[ -1 ]
1,650
makeres-macro.lisp
ghollisjr_cl-ana/makeres-macro/makeres-macro.lisp
;;;; makeres-macro is a Common Lisp make-like tool for computations. ;;;; Copyright 2014 Gary Hollis ;;;; ;;;; This file is part of makeres-macro. ;;;; ;;;; makeres-macro 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. ;;;; ;;;; makeres-macro 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 makeres-macro. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis via email at ;;;; [email protected] (in-package :cl-ana.makeres-macro) (declaim (optimize (debug 3))) ;;; Macros (defvar *proj->res-macros* (make-hash-table :test 'equal) "Map from project to macro symbols for project") (defmacro define-res-macro (name lambda-list &body body) "Defines a res-macro to be expanded in the pipeline." `(progn (symbol-macrolet ((macros (gethash (project) *proj->res-macros*))) (setf macros (adjoin ',name macros :test #'eq))) (defmacro ,name ,lambda-list ,@body))) (defun ensure-default-macros () "All default res-macros will be defined by cl-ana with project ID of NIL, so these are copied to the current project by this function." (let* ((defaults (gethash nil *proj->res-macros*))) (symbol-macrolet ((macros (gethash (project) *proj->res-macros*))) (loop for name in defaults do (setf macros (adjoin name macros :test #'eq)))))) (defparameter *cl-let-ops* (list 'let 'let* 'symbol-macrolet) "list of operators following the let binding format") (defparameter *cl-flet-ops* (list 'flet 'labels 'macrolet) "list of operators following the flet binding format") (defparameter *cl-bind-ops* (list 'destructuring-bind 'multiple-value-bind) "list of operators following the *-bind binding format") (defparameter *lambda-ops* (list 'lambda ;; from cl-ana: 'mlambda 'klambda)) (defparameter *lambda-expander* (lambda (expander form) (destructuring-bind (op lambda-list &rest body) form (let* ((lambda-list (mapcar (lambda (v) (if (listp v) (list* (first v) (funcall expander (second v)) (rest (rest v))) v)) lambda-list)) (body (mapcar expander body))) (list* op lambda-list body))))) (defparameter *cl-let-expander* (lambda (expander form) (destructuring-bind (op bindings &rest body) form (let* ((bsyms (mapcar #'first bindings)) (bexprs (mapcar expander (mapcar #'second bindings))) (body (mapcar expander body))) (list* op (mapcar (lambda (sym bind) (list sym bind)) bsyms bexprs) body)))) "Expander function for common lisp let-like operators needing special treatment during expansion.") (defparameter *cl-flet-expander* (lambda (expander form) (destructuring-bind (op bindings &rest body) form (let* ((fnames (mapcar #'first bindings)) (fargs (mapcar #'second bindings)) (fbodies (mapcar (lambda (x) (mapcar expander (rest (rest x)))) bindings)) (fargs-expanded (mapcar (lambda (lambda-list) (mapcar (lambda (x) (if (listp x) (list* (first x) (funcall expander (second x)) (when (third x) (list (third x)))) x)) lambda-list)) fargs)) (body (mapcar expander body))) (list* op (mapcar #'list* fnames fargs-expanded fbodies) body)))) "Expander function for common lisp flet-like operators needing special treatment during expansion.") (defparameter *cl-bind-expander* (lambda (expander form) (destructuring-bind (op bind-form expr &rest body) form (let* ((expr (funcall expander expr)) (body (mapcar expander body))) (list* op bind-form expr body)))) "Expander function for common lisp *-bind operators needing special treatment during expansion.") (defvar *proj->binding-ops* (make-hash-table :test 'equal)) ;; Since each operator may have a different structure/different areas ;; off-limits to expansion, this map stores the expander functions ;; (taking expander function and form arguments) (defvar *proj->op->expander* (make-hash-table :test 'equal) "map from project to operator to expander function") (defun ensure-binding-ops () (symbol-macrolet ((binding-ops (gethash (project) *proj->binding-ops*))) (let ((stat (second (multiple-value-list binding-ops)))) (when (not stat) (setf binding-ops (append *cl-let-ops* *cl-flet-ops* *cl-bind-ops* *lambda-ops*)))))) (defun ensure-op-expanders () (symbol-macrolet ((op->expander (gethash (project) *proj->op->expander*))) (let ((stat (second (multiple-value-list op->expander)))) (when (not stat) (setf op->expander (make-hash-table :test 'eq)))) (loop for op in *cl-let-ops* do (setf (gethash op op->expander) *cl-let-expander*)) (loop for op in *cl-flet-ops* do (setf (gethash op op->expander) *cl-flet-expander*)) (loop for op in *cl-bind-ops* do (setf (gethash op op->expander) *cl-bind-expander*)) (loop for op in *lambda-ops* do (setf (gethash op op->expander) *lambda-expander*)))) (defun add-binding-ops (ops-expanders) "Takes a list of lists of the form (op expander) and adds the operators along with their expanders to the current project." (ensure-binding-ops) (ensure-op-expanders) (symbol-macrolet ((binding-ops (gethash (project) *proj->binding-ops*)) (op->expander (gethash (project) *proj->op->expander*))) (let ((ops (cars ops-expanders))) (setf binding-ops (list->set (append ops binding-ops) #'equal))) (loop for (op expander) in ops-expanders do (setf (gethash op op->expander) expander)))) ;; res-macro expansion rule: inner-most macros are expanded first, ;; first macros found expanded before later macros (defun expand-res-macros (expr) "Finds & repeatedly expands any res-macros present in expr until none are present." (let ((resmacs (gethash (project) *proj->res-macros*)) (binding-ops (gethash (project) *proj->binding-ops*))) (labels ((rec (f &optional no-op) ;; non-nil no-op means that the form being passed ;; should not be treated for operator content. (let ((result (cond ((atom f) f) ((and (not no-op) (member (first f) resmacs :test #'eq)) (let ((newf (macroexpand-1 f))) (rec newf))) ((and (not no-op) (member (first f) binding-ops :test #'eq)) (let* ((op (first f)) (expander (gethash op (gethash (project) *proj->op->expander*)))) (funcall expander #'rec f))) (t (cons (rec (car f)) (rec (cdr f) t)))))) result))) (rec expr)))) ;;;; Functions (defmacro define-res-function (name lambda-list &body body) "Defines a res-macro with the same syntax you would use for defining a function, which is just removing the double-evaluation of the body form. Note that this still just defines a macro, so wrap calls to it in a lambda form when e.g. mapping." `(define-res-macro ,name (&rest args) `(destructuring-bind ,',lambda-list (list ,@args) ,@',body))) (defun macrotrans (target-table) "Implements macro expansion transformation" ;; initialize *proj->binding-ops* for project if necessary: (ensure-default-macros) (ensure-binding-ops) (ensure-op-expanders) (let ((result (if *copy-target-table-p* (copy-target-table target-table) target-table))) (loop for id being the hash-keys in result for tar being the hash-values in result do (let* ((newtar (copy-target tar)) (oldval (target-val tar)) (oldstat (target-stat tar))) (setf (gethash id result) (make-target id (expand-res-macros (target-expr tar)) :val oldval :stat oldstat)))) result)) (defpropogator #'macrotrans (lambda (graph) (macrotrans graph)))
10,287
Common Lisp
.lisp
262
27.572519
77
0.538592
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
19f511faea0364bd3c8923e5e3e204b10d274d59114f527bd4dba59a754450b8
1,650
[ -1 ]
1,651
fn-test.lisp
ghollisjr_cl-ana/makeres-macro/tests/fn-test.lisp
(require 'cl-ana) (in-package :cl-ana) (defproject fn-test "/home/ghollisjr/test/fn-test" (list #'macrotrans #'progresstrans) (fixed-cache 5)) (defres x 2) (define-res-function *x (x) (* (res x) x)) (defres y (*x 5)) (define-res-function fn (a b &rest keys &key c) (list :a a :b b :keys keys :c c :x (res x))) (defres z (fn (res x) (res y) :c (* (res x) 2)))
392
Common Lisp
.lisp
17
20.117647
50
0.605978
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
6a49bf76d03304728263504511012e7822532050e2f223334edf0b13325399a5
1,651
[ -1 ]
1,652
dep-test.lisp
ghollisjr_cl-ana/makeres-macro/tests/dep-test.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (require 'cl-ana) (in-package :cl-ana) (defproject dep-test "/home/ghollisjr/test/makeres-macro-dep-test" (list #'macrotrans #'progresstrans) (fixed-cache 5)) (define-res-macro +a (arg) `(+ (res a) ,arg)) (defres a 5) (defres b (+ 6 (+a 7)))
1,134
Common Lisp
.lisp
32
33.65625
70
0.697993
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
27e4bec8c776891a52dfd0d315a505c85b6fb9746e014cb1dabdc5bde63fe446
1,652
[ -1 ]
1,653
test.lisp
ghollisjr_cl-ana/makeres-macro/tests/test.lisp
;;;; makeres-macro is a Common Lisp make-like tool for computations. ;;;; Copyright 2014 Gary Hollis ;;;; ;;;; This file is part of makeres-macro. ;;;; ;;;; makeres-macro 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. ;;;; ;;;; makeres-macro 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 makeres-macro. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis via email at ;;;; [email protected] (require 'cl-ana.makeres-macro) (in-package cl-ana.makeres-macro) (in-project makeres-macro) (settrans (list #'macrotrans) :op :set) (define-res-macro tagged-res (&rest tags) `(list ,@(loop for m in (loop for id being the hash-keys in (target-table) when (every (lambda (tag) (member tag id :test #'eq)) tags) collect id) append (copy-list `((res ,m)))))) (defres (x) 'x) (defres (y) 'y) (defres (test) (tagged-res x))
1,520
Common Lisp
.lisp
37
34.675676
77
0.627119
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
664c27e3206face0304c5e1dbf9f5acb81ce87f52b59a62501957e1c55b2556c
1,653
[ -1 ]
1,654
package.lisp
ghollisjr_cl-ana/table/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (defpackage #:cl-ana.table (:use #:cl #:alexandria #:cl-ana.list-utils #:cl-ana.macro-utils #:cl-ana.string-utils #:cl-ana.symbol-utils #:cl-ana.functional-utils) (:export :table :table-open-p :table-field-names :table-access-mode :table-field-symbols :table-load-next-row :table-activate-fields :table-get-field :table-set-field :table-push-fields :table-commit-row :table-close :table-nrows :do-table :table-reduce ;; table-chain: :open-table-chain :reset-table-chain ;; plist-table: :plist-table-plists :open-plist-table :create-plist-table))
1,565
Common Lisp
.lisp
50
27.28
70
0.668428
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
997f7572933792479095f66c516402707dcb48a64f922942f05a0f23ac4347fe
1,654
[ -1 ]
1,655
table-chain.lisp
ghollisjr_cl-ana/table/table-chain.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.table) ;;;; table-chain: A read-only chain of tables of any type; initialized ;;;; by providing code to evaluate which generates the appropriate ;;;; table object whenever it is time to load it. It is implemented ;;;; using closures. (defclass table-chain (table) ((creation-functions :initarg :creation-functions :initform () :accessor table-chain-creation-functions :documentation "Functions which create each table in the chain.") (current-table :initarg :current-table :initform nil :accessor table-chain-current-table :documentation "Current table being accessed.") (current-table-index :initarg :current-table-index :initform -1 :accessor table-chain-current-table-index :documentation "Index to current table."))) (defun open-table-chain (creation-functions) "Creates a chain of tables by running the appropriate creation-function when the previous table fails on table-load-next-row. Each creation function should be a function taking zero arguments and returning a table." (let ((table (make-instance 'table-chain :creation-functions (concatenate 'vector creation-functions)))) (load-next-table table) (setf (table-field-names table) (table-field-names (table-chain-current-table table))) table)) (defun reset-table-chain (table-chain) "Resets the table counter in the chain so that it can be re-read." (setf (table-chain-current-table-index table-chain) -1)) (defun load-next-table (table-chain) "Loads the next table in the chain." (with-accessors ((current-table table-chain-current-table) (current-table-index table-chain-current-table-index) (creation-functions table-chain-creation-functions)) table-chain (let ((n-tables (length creation-functions))) (if (< current-table-index (1- n-tables)) (setf current-table (funcall (elt creation-functions (incf current-table-index)))) nil)))) (defmethod table-load-next-row ((table table-chain)) (with-accessors ((current-table table-chain-current-table) (current-table-index table-chain-current-table-index) (creation-functions table-chain-creation-functions)) table (if (table-load-next-row current-table) t (and (load-next-table table) (table-load-next-row table))))) (defmethod table-get-field ((table table-chain) field-symbol) (with-accessors ((current-table table-chain-current-table)) table (table-get-field current-table field-symbol)))
3,373
Common Lisp
.lisp
83
37.457831
70
0.73118
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
c95da1315b64cb49b47f8446da1f21854e50b061f0b4923fcc72421d13976984
1,655
[ -1 ]
1,656
plist-table.lisp
ghollisjr_cl-ana/table/plist-table.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.table) ;;;; plist-table: A table created in-memory from a list of plists. ;;;; Not meant for high-performance computing, but can be useful. ;;;; ;;;; With this theme, it is a read-only table type since writing would ;;;; be done by first converting it into another object and writing it ;;;; however you wish. (defclass plist-table (table) ((plists :initarg :plists :initform nil :accessor plist-table-plists :documentation "The plists containing the data.") (current-table-index :initarg :current-table-index :initform -1 :accessor plist-table-current-table-index :documentation "Index to the current table in the plist array."))) ;;; Reading functions: (defun open-plist-table (plists) (make-instance 'plist-table :plists (coerce plists 'vector) :field-names (mapcar #'string (every-nth (first plists) 2)) :access-mode :read)) (defmethod table-load-next-row ((table plist-table)) (with-accessors ((plists plist-table-plists) (current-table-index plist-table-current-table-index)) table (if (< current-table-index (1- (length plists))) (incf current-table-index) nil))) (defmethod table-get-field ((table plist-table) field-symbol) (with-accessors ((current-table-index plist-table-current-table-index) (plists plist-table-plists)) table (getf (elt plists current-table-index) field-symbol))) (defmethod table-close ((table plist-table)) (when (eq (table-access-mode table) :write) (setf (plist-table-plists table) (reverse (rest (plist-table-plists table))))) nil) ;;; Writing functions: (defun create-plist-table (field-names) (make-instance 'plist-table :plists (list (list)) :field-names field-names :access-mode :write)) (defmethod table-set-field ((tab plist-table) field-symbol value) (with-accessors ((plists plist-table-plists)) tab (setf (getf (first plists) field-symbol) value))) (defmethod table-commit-row ((tab plist-table)) (with-accessors ((plists plist-table-plists)) tab (push (list) plists))) ;; Misc methods: (defmethod table-nrows ((tab plist-table)) (length (plist-table-plists tab)))
3,165
Common Lisp
.lisp
81
34.765432
72
0.687622
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
80c91493c12d78c446897cea09ee4e1a0657f052fb8ee012a6ea0c9628ad37af
1,656
[ -1 ]
1,657
table.lisp
ghollisjr_cl-ana/table/table.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; table.lisp ;;;; I've been thinking about the way I currently implement dotable, ;;;; and I may in fact change my mind to let the user explicitly state ;;;; which variables should be accessed inside the body of the loop. ;;;; The present method is a bit ugly in that it doesn't take into ;;;; account any lexical scoping issues which would shadow the ;;;; bindings of field variables. ;;;; Some thoughts on the even higher-level interface: I could create ;;;; a heterogeneous table type which would contain a list of row ;;;; blocks, each row block being a list of tables for the rows in the ;;;; block. This allows me to extend a table by adding rows or ;;;; fields to an existing table. The table-get-field could be ;;;; facilitated via 2 hash tables: one from row-index to field block ;;;; one from symbols to table index; from there just calling ;;;; table-get-field function after accessing the appropriate table ;;;; from the appropriate row block. (in-package :cl-ana.table) (declaim (optimize (speed 2) (safety 1) (compilation-speed 0) (debug 1))) (defclass table () ((field-names :initarg :field-names :initform () :accessor table-field-names :documentation "List of field names.") (access-mode :initarg :access-mode :initform nil :accessor table-access-mode :documentation ":write for a writable table, :read for a readable table, and :both for a table which has no restriction on being written to or read from only. nil for a table which is not open."))) (defun table-open-p (table) (table-access-mode table)) (defun table-field-symbols (table) (mapcar (compose #'keywordify #'intern) (table-field-names table))) (defgeneric table-load-next-row (table) (:documentation "Loads the next row into the current row buffer. Returns nil if the next row does not exist/there is a read failure (which can be the same thing), non-nil otherwise.")) (defgeneric table-activate-fields (table field-names) (:documentation "Function for optimization based on which fields are to be read from the table; default method is to do nothing which works when these optimizations do nothing for a particular table type.") (:method (table field-names) nil)) (defgeneric table-get-field (table field-symbol) (:documentation "Gets the field datum from the current row for field denoted by the field-symbol")) ;; writing is done in a stateful manner, where you access the current ;; table row for writing and then tell the table to commit/write the ;; row when you're done. (defgeneric table-set-field (table field-symbol value) (:documentation "Sets the field value of the current output row")) (defgeneric table-commit-row (table) (:documentation "Commits (writes) the current output row to the table")) (defmacro table-push-fields (table &body field-specs) "Sets fields and commits row of table using field-specs. Each field-spec is either a symbol which represents both the field-symbol and the variable storing the field data." `(progn ,@(loop for fs in field-specs collecting (if (listp fs) `(table-set-field ,table ,(keywordify (first fs)) ,(second fs)) `(table-set-field ,table ,(keywordify fs) ,fs))) (table-commit-row ,table))) ;; Closing tables, sometimes necessary but always call just in case (defgeneric table-close (table) (:documentation "Close any open files, etc.")) ;; default: do nothing (defmethod table-close (table) (call-next-method)) ;; after method for taking care of access mode: (defmethod table-close :after ((tab table)) (setf (table-access-mode tab) nil)) ;; Some tables can tell you about their size: (defgeneric table-nrows (table) (:documentation "When available, returns the number of rows stored in the table, otherwise returns nil.") (:method (table) nil)) ;;;; Table processing functions/macros (defun table-reduce (table fields fn &key initial-value) "table-reduce mimics reduce but with the modification that fn should take one more argument than the number of fields specified with the first argument used to store the state as fn is called across the table. table-reduce can be used as a functional/non-macro solution to looping over the table. fields is a list of field names/symbols. They will be passed in the order specified to fn. fn is function taking the computation state as the first argument and then each selected field as an argument in the order given in fields; can use the state argument to collect a list of values for example." (table-activate-fields table fields) (let ((field-symbols (mapcar (compose #'keywordify #'intern #'string) fields))) (flet ((get-fields () (loop for f in field-symbols collect (table-get-field table f)))) ;; initial row read: (if (table-load-next-row table) (do* ((field-vals nil (get-fields)) (state initial-value (apply fn state field-vals)) (read-status t (table-load-next-row table))) ((not read-status) state)) initial-value)))) (defmacro do-table ((rowvar table) field-selections &body body) "Macro for iterating over a table. rowvar is a symbol which will be bound to the row number inside the loop body. You can optionally use a list (rowtype rowvar) which will allow for the rowvar to have a type declared for it. table is the table which will be looped upon. To select specific fields from the table for reading, specify all the desired field names in field-selections; if field-selections is nil then all fields will be read. Note that it is still more efficient to specify all desired fields; for two field data this results in about a 16% running time difference. Also you must specify either none or all of the desired fields to work with during the loop body. Each field-selection is a list of 1. field names to access during the loop, by default the value will be bound to the lispified field name as a symbol, 2. A list containing a symbol as the first element and the field name as the second which will be bound to the symbol given as the first element of the list. The code body will be run for each row in the table. If fields are explicitly selected, then you can use declare statements at the beginning of the loop body; otherwise this is not supported." (let* ((selected-field-names (mapcar (lambda (x) (if (listp x) (second x) x)) field-selections)) (bound-field-symbols (mapcar (lambda (x) (if (listp x) (first x) (intern x))) field-selections))) (multiple-value-bind (rowt rowv) (if (listp rowvar) (values (first rowvar) (second rowvar)) (values 'integer rowvar)) (if field-selections ;; explicit fields (let ((field-keyword-symbols (mapcar (compose #'keywordify #'string) selected-field-names))) (with-gensyms (load-row tab) `(let ((,tab ,table)) (do ((,rowv 0 (1+ ,rowv)) (,load-row (table-load-next-row ,tab) (table-load-next-row ,tab))) ((not ,load-row) nil) (declare (,rowt ,rowv)) (olet ,(loop for b in bound-field-symbols for k in field-keyword-symbols collecting `(,b (table-get-field ,tab ,k))) ,@body))))) ;; implicit fields (with-gensyms (field-symbols field-names bound-symbols bound xs x) `(let* ((,field-names (table-field-names ,table)) (,field-symbols (table-field-symbols ,table)) (,bound-symbols (mapcar (compose #'intern #'string) ,field-symbols))) (table-reduce ,table ,field-names (lambda (,rowv &rest ,xs) (declare (,rowt ,rowv)) (loop for ,bound in ,bound-symbols for ,x in ,xs do (set ,bound ,x)) ,@body (1+ ,rowv)) :initial-value 0))))))) ;; DEFUNCT & DEPRECATED ;; ;; This is kept for comparison with the non-olet version (defmacro do-table-old ((rowvar table) field-selections &body body) "Macro for iterating over a table. rowvar is a symbol which will be bound to the row number inside the loop body. You can optionally use a list (rowtype rowvar) which will allow for the rowvar to have a type declared for it. table is the table which will be looped upon. To select specific fields from the table for reading, specify all the desired field names in field-selections; if field-selections is nil then all fields will be read. Note that it is still more efficient to specify all desired fields; for two field data this results in about a 16% running time difference. Also you must specify either none or all of the desired fields to work with during the loop body. Each field-selection is a list of 1. field names to access during the loop, by default the value will be bound to the lispified field name as a symbol, 2. A list containing a symbol as the first element and the field name as the second which will be bound to the symbol given as the first element of the list. The code body will be run for each row in the table. If fields are explicitly selected, then you can use declare statements at the beginning of the loop body; otherwise this is not supported." (let* ((selected-field-names (mapcar (lambda (x) (if (listp x) (second x) x)) field-selections)) (bound-field-symbols (mapcar (lambda (x) (if (listp x) (first x) (intern (lispify x)))) field-selections))) (multiple-value-bind (rowt rowv) (if (listp rowvar) (values (first rowvar) (second rowvar)) (values 'integer rowvar)) (if field-selections `(table-reduce ,table (list ,@selected-field-names) (lambda (,rowv ,@bound-field-symbols) (declare (,rowt ,rowv)) ,@body (1+ ,rowv)) :initial-value 0) (with-gensyms (field-symbols field-names bound-symbols bound xs x) `(let* ((,field-names (table-field-names ,table)) (,field-symbols (table-field-symbols ,table)) (,bound-symbols (mapcar (compose #'intern #'string) ,field-symbols))) (table-reduce ,table ,field-names (lambda (,rowv &rest ,xs) (declare (,rowt ,rowv)) (loop for ,bound in ,bound-symbols for ,x in ,xs do (set ,bound ,x)) ,@body (1+ ,rowv)) :initial-value 0)))))))
13,320
Common Lisp
.lisp
298
33.90604
79
0.59498
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
062841189089b7b6a0e00ad9dfb254d78f3250793790b9f107515dc51171ff1f
1,657
[ -1 ]
1,658
test.lisp
ghollisjr_cl-ana/table/test.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (require 'cl-ana) (in-package :cl-ana) (defparameter *plist-table* (open-plist-table (loop for i below 10 collecting (list :|x| i :x (* i 2))))) (do-table (ri *plist-table*) ("x" "X") (print |x|) (print X))
1,136
Common Lisp
.lisp
33
31.575758
70
0.66788
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
8aaed26abf6a5f5cce881d12728ff7d2b3bcc056453429106dd801a67a9fe443
1,658
[ -1 ]
1,659
makeres-branch.lisp
ghollisjr_cl-ana/makeres-branch/makeres-branch.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 makeres. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis via email at ;;;; [email protected] (in-package :cl-ana.makeres-branch) (defmacro branch (branch-list &optional form) "branch operator takes the branch-list and an optional expression as arguments. branch-list must be either 1. A form which can be evaluated in the null-environment to yield a list whose elements each correspond to a separate branch of a computation, or 2. A (res id) form which denotes co-branching. Each branching computation has access to the value during its evaluation, and branch operators can be nested, although this is technically unnecessary." nil) ;; These branch functions take full target expressions (defun branch? (expr) (destructuring-bind (progn &rest forms) expr (and (single forms) (listp (first forms)) (eq (first (first forms)) 'branch)))) (defun branch-list (expr) (when (branch? expr) (second (second expr)))) (defun branch-expr (expr) (when (branch? expr) (third (second expr)))) (defun branch-test (expr) (let ((result (fourth (second expr)))) (if result result 'equal))) (defun branch-source? (expr) (and (branch? expr) (= (length (second expr)) 2))) (defun res? (expr) (and (listp expr) (eq (first expr) 'res))) (defun unres (expr) (second expr)) (defun branch-chains (graph) "Finds chains of branches; returns list of id chains, each of the form (source &rest co-branches)" (let* ((branch-ids (loop for id being the hash-keys in graph for tar being the hash-values in graph when (let ((expr (target-expr tar))) (branch? expr)) collecting id)) (source-branch-ids (loop for id in branch-ids when (let ((expr (target-expr (gethash id graph)))) (branch-source? expr)) collecting id)) ;; map from id to all immediate dependents (id->imm-dependent (let ((result (make-hash-table :test 'equal))) (loop for id in branch-ids when (res? (branch-list (target-expr (gethash id graph)))) do (let ((source (unres (branch-list (target-expr (gethash id graph)))))) (setf (gethash source result) (adjoin id (gethash source result) :test #'equal)))) result))) (labels ((collect-dependents (id) ;; returns list of all dependents on id (append (gethash id id->imm-dependent) (mapcan #'collect-dependents (gethash id id->imm-dependent))))) (loop for source in source-branch-ids collecting (cons source (collect-dependents source)))))) ;;;; Branch transformation algorithm: ;;;; ;;;; The algorithm is recursive, applying a single pass to every layer ;;;; of nested branches present in the target table. It assumes that ;;;; efficient recombination of targets into passes will be done via ;;;; other graph transformations occurring later in the transformation ;;;; pipeline, e.g. makeres-table. ;;;; ;;;; 1. Find branch chains, branches with shared sources ;;;; ;;;; 2. Create targets for each individual branch. ;;;; ;;;; 3. Modify targets of final result targets to simply collect ;;;; hash-tables of the resulting passes (defun branch-replace (value tree branch-ids) "Replaces (branch) or (branch branch-id) forms with `',value. (branch) is replaced up to context of outermost branch, (branch branch-id) is replaced to all levels" (labels ((rec (tree) (cond ((null tree) nil) ((equal tree '(branch)) value) ((atom tree) tree) ((eq (first tree) 'branch) tree) ((atom (cdr (last tree))) (cons (rec (car tree)) (rec (cdr tree)))) (t (mapcar #'rec tree))))) (sublis (loop for id in branch-ids collecting `((branch ,id) . ,value)) (rec tree) :test #'equal))) (defun branchtrans (graph) (let* ((result (if *copy-target-table-p* (cl-ana.makeres:copy-target-table graph) graph)) (branch-chains (branch-chains graph)) (source-branch-ids (mapcar #'first branch-chains)) (source->branch-ids (let ((ht (make-hash-table :test 'equal))) (loop for chain in branch-chains do (let ((source (first chain))) (loop for id in chain do (push `(res ,id) (gethash source ht))) (push (branch-list (target-expr (gethash source graph))) (gethash source ht)))) ht)) (source->branch-list (let ((id->list (make-hash-table :test 'equal))) (loop for id in source-branch-ids do (setf (gethash id id->list) (eval (branch-list (target-expr (gethash id graph)))))) id->list))) (if (some (lambda (chain) (some (lambda (id) (and (not (target-stat (gethash id graph))) (not (branch-source? (target-expr (gethash id graph)))))) chain)) branch-chains) (progn (loop for chain in branch-chains do (let* ((source (first chain)) (branch-ids (gethash source source->branch-ids)) (branch-list (gethash source source->branch-list)) (id->branch->gsym (let ((ht (make-hash-table :test 'equal))) (loop for id in chain when (not (target-stat (gethash id graph))) do (let* ((raw-expr (target-expr (gethash id graph))) (test (branch-test raw-expr))) (setf (gethash id ht) (make-hash-table :test test))) (loop for branch in branch-list do (setf (gethash branch (gethash id ht)) (gensym)))) ht))) (loop for id in chain when (not (target-stat (gethash id graph))) do (let* ((raw-expr (target-expr (gethash id graph))) (test (branch-test raw-expr)) (expr (let ((e (branch-expr raw-expr))) (if (eq (first e) 'progn) e `(progn ,e))))) (loop for branch in branch-list do (let ((gsym (gethash branch (gethash id id->branch->gsym))) (body (branch-replace branch (sublis (loop for chain-id in chain collecting (cons `(res ,chain-id) (if (target-stat (gethash chain-id graph)) `(gethash ,branch (res ,chain-id)) `(res ,(gethash branch (gethash chain-id id->branch->gsym)))))) expr :test #'equal) branch-ids))) (setf (gethash gsym result) (make-target gsym body)))) (when (not (branch-source? (target-expr (gethash id result)))) (setf (target-expr (gethash id result)) `(let ((result (make-hash-table :test ',test))) ,@(loop for branch in branch-list collecting `(setf (gethash ',branch result) (res ,(gethash branch (gethash id id->branch->gsym))))) result))))))) (branchtrans result)) result)))
11,051
Common Lisp
.lisp
251
25.250996
99
0.431803
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
4d0409b37d77ec5bf9e79ca5d37f19f997f29c49c87adeeae364cef81809c5b8
1,659
[ -1 ]
1,660
package.lisp
ghollisjr_cl-ana/makeres-branch/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 makeres. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis via email at ;;;; [email protected] (defpackage #:cl-ana.makeres-branch (:use :cl :cl-ana.list-utils :cl-ana.makeres) (:export ;; transformation function: :branchtrans ;; Branching operator :branch ;; Branch operator :branch-value)) (cl-ana.generic-math:use-gmath :cl-ana.makeres-branch)
1,154
Common Lisp
.lisp
32
33.8125
70
0.708036
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
3d299516ffa72a2933098ed902b92d11c17df5b2b0532a4344de64fa243668dd
1,660
[ -1 ]
1,661
test2.lisp
ghollisjr_cl-ana/makeres-branch/tests/test2.lisp
(require 'cl-ana) (in-package :cl-ana) (defproject branch "/home/ghollisjr/test/makeres-branch/" (list #'branchtrans) (fixed-cache 5)) (defres (branching xs) (branch (list 1 2 3 4 5))) (defres (branching ys) (branch (list 6 7 8 9 10))) (defres double-x (branch (res (branching xs)) (* (branch) 2))) (defres double-y (branch (res (branching ys)) (* (branch) 2))) (defres exp-double-x (branch (res (branching xs)) (exp (res double-x)))) (defres sin-exp-double-x (branch (res (branching xs)) (sin (res exp-double-x)))) (defres exp-double-y (branch (res (branching ys)) (exp (res double-y)))) ;; double branching: (defres nils (branch (res (branching xs)) (branch (res (branching ys)) nil)))
800
Common Lisp
.lisp
30
21.933333
42
0.610526
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
41eb8dbec45add197c0a12f42fa401e12ff5d87daee1a92084e35750df706cb4
1,661
[ -1 ]
1,662
test.lisp
ghollisjr_cl-ana/makeres-branch/tests/test.lisp
(require 'cl-ana) (in-package :cl-ana) (defproject branch "/home/ghollisjr/test/makeres-branch/" (list #'branchtrans) (fixed-cache 5)) (defparameter *xs* (list 1 2 3 4 5)) (defparameter *ys* (list 6 7 8 9 10)) (defres double-x (branch *xs* (* (branch) 2))) (defres double-y (branch *ys* (* (branch) 2))) (defres exp-double-x (branch (res double-x) (exp (res double-x)))) (defres sin-exp-double-x (branch (res exp-double-x) (sin (res exp-double-x)))) (defres exp-double-y (branch (res double-y) (exp (res double-y)))) ;; double branching: (defres nils (branch *xs* (branch *ys* nil)))
648
Common Lisp
.lisp
30
18.466667
42
0.639803
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
5cad750e8644a16a14386d51dbd5385ec0ed29188f52e0dd7253b39968cd7c70
1,662
[ -1 ]
1,663
package.lisp
ghollisjr_cl-ana/gsl-cffi/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (defpackage #:cl-ana.gsl-cffi (:use :cl :cffi) (:export :gsl-ntuple-read :+GSL-EOF+)) ;;:gsl-multifit-fsolver-driver))
1,006
Common Lisp
.lisp
26
36.961538
70
0.699694
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
9cf310c3e2b42f67613cc668d3786f74dfa31131d07b689688762e4a86437429
1,663
[ -1 ]
1,664
gsl-cffi.lisp
ghollisjr_cl-ana/gsl-cffi/gsl-cffi.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.gsl-cffi) (defconstant +GSL-EOF+ 32 "End-of-file return value for gsl functions") (define-foreign-library gsl-cffi (:darwin (:or (:framework "libgsl") "libgsl.dylib")) (:windows "libgsl.dll" :convention :stdcall) (:unix (:or "libgsl.so" "libgsl.so.27" "libgsl.so.26" "libgsl.so.25")) (t (:default "libgsl"))) (defcfun "gsl_ntuple_read" :int (ntuple :pointer)) ; gsl_ntuple* ;;; Currently unused: (defcfun "gsl_multifit_fsolver_alloc" :pointer (gsl-multifit-fsolver-type :pointer) ; gsl_multifit_fsolver_type* (n-data :uint) (n-params :uint)) (defcfun "gsl_multifit_fsolver_free" :void (gsl-multifit-fsolver :pointer)) ; gsl_multifit_solver* (defcfun "gsl_multifit_fsolver_set" :int (solver :pointer) ; gsl_multifit_fsolver* (gsl-multifit-function :pointer) ; gsl_multifit_function* (initial-guess :pointer)) ; const gsl_vector*
1,794
Common Lisp
.lisp
44
38
70
0.697474
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
bad7a3562697d72587cc789dd2c27e4610b29d89e9f1c4bae02d8c5c2711fc30
1,664
[ -1 ]
1,665
binary-tree.lisp
ghollisjr_cl-ana/binary-tree/binary-tree.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.binary-tree) ;;; Binary Tree: (value left-child right-child numvalues) (defun node-leaf-p (node) (not (or (node-left-child node) (node-right-child node)))) (defun node-value (tree) (first tree)) (defun node-left-child (tree) (second tree)) (defun node-right-child (tree) (third tree)) (defun node-value-count (tree) (fourth tree)) (defun make-balanced-tree (list &key key sorted (comparison #'<) (test #'equal)) (if sorted (make-balanced-tree-sorted-compressed (compress list :key key :test test :singleton-pairs t)) (make-balanced-tree-sorted-compressed (compress (sort (copy-list list) comparison :key key) :key key :test test :singleton-pairs t)))) (defun make-balanced-tree-sorted-compressed (list) "Assumes the list is sorted & compressed with singleton-pairs enabled." (when list (let* ((median-position (median-position list)) (median (elt list median-position)) (leftnodes (if (zerop median-position) nil (subseq list 0 median-position))) (rightnodes (subseq list (1+ median-position)))) (list (car median) (make-balanced-tree-sorted-compressed leftnodes) (make-balanced-tree-sorted-compressed rightnodes) (cdr median))))) (defun compress-equal (x y) (labels ((get-value (z) (if (consp z) (car z) z))) (let ((xvalue (get-value x)) (yvalue (get-value y))) (equal xvalue yvalue)))) (defun median-position (list) (let ((length (length list))) (if (= 1 length) 0 (1- (floor (/ length 2)))))) ;;;; Access functions: (defun bref (tree val &key (key #'identity)) "Returns a cons pair of node values which form the most constraining interval around val using key." (labels ((rightmost (tree) (if (node-leaf-p tree) (node-value tree) (rightmost (node-right-child tree)))) (leftmost (tree) (if (node-leaf-p tree) (node-value tree) (leftmost (node-left-child tree)))) (rec (tree val &optional low hi) (let* ((tval (node-value tree)) (kval (funcall key tval))) (if (node-leaf-p tree) (if (= kval val) (values tval t) (values (cons (if (< kval val) tval low) (if (> kval val) tval hi)) nil)) (cond ((= kval val) (values tval t)) ((> kval val) (let ((left (node-left-child tree))) (if left (rec (node-left-child tree) val low tval) (values (cons low tval) nil)))) (t (let ((right (node-right-child tree))) (if right (rec (node-right-child tree) val tval hi) (values (cons tval hi) nil))))))))) (rec tree val))) ;;;; Utilities based on binary trees (defun interpolate-fn (alist &key overflow-val underflow-val) "Returns a function which interpolates the alist of points. Default overflow and underflow behavior is to return the last value present in the alist in that direction. Set overflow-val or underflow-val to a value or a function to allow specification of the out-of-bounds behavior." (let ((tree (make-balanced-tree alist :key #'car)) (overflow-fn (if overflow-val (if (functionp overflow-val) overflow-val (constantly overflow-val)) (constantly (cdr (maximum alist :key #'car))))) (underflow-fn (if underflow-val (if (functionp underflow-val) underflow-val (constantly underflow-val)) (constantly (cdr (minimum alist :key #'car)))))) (lambda (point) (multiple-value-bind (bounds match-p) (bref tree point :key #'car) (if match-p (cdr bounds) (if (or (null (car bounds)) (null (cdr bounds))) (if (null (car bounds)) ;; underflow (funcall underflow-fn point) ;; overflow (funcall overflow-fn point)) (destructuring-bind ((leftx . lefty) . (rightx . righty)) bounds (let ((slope (/ (- righty lefty) (- rightx leftx)))) (+ lefty (* slope (- point leftx)))))))))))
6,289
Common Lisp
.lisp
166
25.222892
74
0.502458
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
43e7058565d874475ab7821de4ba8b14c676c2a045b63ed8796a124013a4f9ca
1,665
[ -1 ]
1,666
package.lisp
ghollisjr_cl-ana/binary-tree/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (defpackage #:cl-ana.binary-tree (:use #:cl #:cl-ana.macro-utils #:cl-ana.list-utils #:cl-ana.functional-utils) (:export :make-balanced-tree :node-leaf-p :node-value :node-left-child :node-right-child :bref :interpolate-fn))
1,165
Common Lisp
.lisp
32
33.15625
70
0.678445
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
d905116979725ff0843f1249c98d8a00ea0cb8344f1b118f044a22a03ffe2cef
1,666
[ -1 ]
1,667
nonlinear-least-squares.lisp
ghollisjr_cl-ana/upstream/gsll/solve-minimize-fit/nonlinear-least-squares.lisp
;; Nonlinear least squares fitting. ;; Liam Healy, 2008-02-09 12:59:16EST nonlinear-least-squares.lisp ;; Time-stamp: <2016-08-07 21:32:38EDT nonlinear-least-squares.lisp> ;; ;; Copyright 2008, 2009, 2011, 2012, 2016 Liam M. Healy ;; Distributed under the terms of the GNU General Public License ;; ;; 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 :gsl) ;;; /usr/include/gsl/gsl_multifit_nlin.h ;;;;**************************************************************************** ;;;; Function-only solver object ;;;;**************************************************************************** ;;; Note that GSL currently provides no derivative-free solvers, ;;; so this is moot for now. (defmobject nonlinear-ffit "gsl_multifit_fsolver" ((solver-type :pointer) ((first dimensions) :sizet) ; number-of-observations ((second dimensions) :sizet)) ; number-of-parameters "nonlinear least squares fit with function only" :documentation ; FDL "The number of observations must be greater than or equal to parameters." :callbacks (callback (:struct fnstruct-fit) (number-of-observations number-of-parameters) (function :success-failure (:input :double :foreign-array dim1) :slug (:output :double :foreign-array dim0))) :initialize-suffix "set" :initialize-args ((callback :pointer) ((mpointer initial-guess) :pointer)) :singular (function)) (defmfun name ((solver nonlinear-ffit)) "gsl_multifit_fsolver_name" (((mpointer solver) :pointer)) :definition :method :c-return :string :documentation ; FDL "The name of the solver type.") ;;;;**************************************************************************** ;;;; Function and derivative solver object ;;;;**************************************************************************** (defmobject nonlinear-fdffit "gsl_multifit_fdfsolver" ((solver-type :pointer) ((first dimensions) :sizet) ; number-of-observations ((second dimensions) :sizet)) ; number-of-parameters "nonlinear least squares fit with function and derivative" :documentation ; FDL "The number of observations must be greater than or equal to parameters." :callbacks (callback (:struct fnstruct-fit-fdf) (number-of-observations number-of-parameters) (function :success-failure (:input :double :foreign-array dim1) :slug (:output :double :foreign-array dim0)) (df :success-failure (:input :double :foreign-array dim1) :slug (:output :double :foreign-array dim0 dim1)) (fdf :success-failure (:input :double :foreign-array dim1) :slug (:output :double :foreign-array dim0) (:output :double :foreign-array dim0 dim1))) :initialize-suffix "set" :initialize-args ((callback :pointer) ((mpointer initial-guess) :pointer))) (defmfun name ((solver nonlinear-fdffit)) "gsl_multifit_fdfsolver_name" (((mpointer solver) :pointer)) :definition :method :c-return :string :documentation ; FDL "The name of the solver type.") ;;;;**************************************************************************** ;;;; Iteration ;;;;**************************************************************************** (defmfun iterate ((solver nonlinear-ffit)) "gsl_multifit_fsolver_iterate" (((mpointer solver) :pointer)) :definition :method :documentation ; FDL "Perform a single iteration of the solver. The solver maintains a current estimate of the best-fit parameters at all times. ") (defmfun iterate ((solver nonlinear-fdffit)) "gsl_multifit_fdfsolver_iterate" (((mpointer solver) :pointer)) :definition :method :documentation ; FDL "Perform a single iteration of the solver. The solver maintains a current estimate of the best-fit parameters at all times. ") (defmfun solution ((solver nonlinear-ffit)) "gsl_multifit_fsolver_position" (((mpointer solver) :pointer)) :definition :method :c-return (crtn :pointer) :return ((make-foreign-array-from-mpointer crtn)) :documentation ; FDL "The current best-fit parameters.") (defmfun solution ((solver nonlinear-fdffit)) "gsl_multifit_fdfsolver_position" (((mpointer solver) :pointer)) :definition :method :c-return (crtn :pointer) :return ((make-foreign-array-from-mpointer crtn)) :documentation ; FDL "The current best-fit parameters.") ;;; Why doesn't GSL have functions to extract these values? (defmethod function-value ((solver nonlinear-fdffit)) (make-foreign-array-from-mpointer (cffi:foreign-slot-value (mpointer solver) '(:struct gsl-fdffit-solver) 'f))) (defmethod last-step ((solver nonlinear-fdffit)) ;; Raw pointer, because we presume we're passing it on to another GSL function. (cffi:foreign-slot-value (mpointer solver) '(:struct gsl-fdffit-solver) 'dx)) #-gsl2 (defun jacobian (solver) ;; Raw pointer, because we presume we're passing it on to another GSL function. (cffi:foreign-slot-value (mpointer solver) '(:struct gsl-fdffit-solver) 'jacobian)) ;;; This needs work to make matrix automatically allocated. #+gsl2 (defmfun jacobian (solver matrix) "gsl_multifit_fdfsolver_jac" (((mpointer solver) :pointer) ((mpointer matrix) :pointer)) :return (matrix) :documentation "The Jacobian matrix for the current iteration of the solver.") ;;;;**************************************************************************** ;;;; Search stopping ;;;;**************************************************************************** (defmfun fit-test-delta (solver absolute-error relative-error) "gsl_multifit_test_delta" (((last-step solver) :pointer) ((mpointer (solution solver)) :pointer) (absolute-error :double) (relative-error :double)) :c-return :success-continue :documentation ; FDL "Test for the convergence of the sequence by comparing the last step with the absolute error and relative error to the current position. The test returns T if |last-step_i| < absolute-error + relative-error |current-position_i| for each component i of current-position and returns NIL otherwise.") (defmfun fit-test-gradient (gradient absolute-error) "gsl_multifit_test_gradient" ((gradient :pointer) (absolute-error :double)) :c-return :success-continue :documentation ; FDL "Test the residual gradient against the absolute error bound. Mathematically, the gradient should be exactly zero at the minimum. The test returns T if the following condition is achieved: \sum_i |gradient_i| < absolute-error and returns NIL otherwise. This criterion is suitable for situations where the precise location of the minimum is unimportant provided a value can be found where the gradient is small enough.") (defmfun fit-gradient (jacobian function-values gradient) "gsl_multifit_gradient" ((jacobian :pointer) ((mpointer function-values) :pointer) (gradient :pointer)) :documentation ; FDL "Compute the gradient of \Phi(x) = (1/2) ||F(x)||^2 from the Jacobian matrix and the function values using the formula g = J^T f.") ;;;;**************************************************************************** ;;;; Minimization using derivatives ;;;;**************************************************************************** (defmpar +levenberg-marquardt+ "gsl_multifit_fdfsolver_lmsder" ;; FDL "A robust and efficient version of the Levenberg-Marquardt algorithm as implemented in the scaled lmder routine in Minpack, written by Jorge J. More', Burton S. Garbow and Kenneth E. Hillstrom. The algorithm uses a generalized trust region to keep each step under control. In order to be accepted a proposed new position x' must satisfy the condition |D (x' - x)| < \delta, where D is a diagonal scaling matrix and \delta is the size of the trust region. The components of D are computed internally, using the column norms of the Jacobian to estimate the sensitivity of the residual to each component of x. This improves the behavior of the algorithm for badly scaled functions. On each iteration the algorithm attempts to minimize the linear system |F + J p| subject to the constraint |D p| < \Delta. The solution to this constrained linear system is found using the Levenberg-Marquardt method. The proposed step is now tested by evaluating the function at the resulting point, x'. If the step reduces the norm of the function sufficiently, and follows the predicted behavior of the function within the trust region, then it is accepted and the size of the trust region is increased. If the proposed step fails to improve the solution, or differs significantly from the expected behavior within the trust region, then the size of the trust region is decreased and another trial step is computed. The algorithm also monitors the progress of the solution and returns an error if the changes in the solution are smaller than the machine precision. The possible errors signalled are: 'failure-to-reach-tolerance-f the decrease in the function falls below machine precision, 'failure-to-reach-tolerance-x the change in the position vector falls below machine precision, 'failure-to-reach-tolerance-g the norm of the gradient, relative to the norm of the function, falls below machine precision. These errors indicate that further iterations would be unlikely to change the solution from its current value.") (defmpar +levenberg-marquardt-unscaled+ "gsl_multifit_fdfsolver_lmder" ;; FDL "The unscaled version of *levenberg-marquardt*. The elements of the diagonal scaling matrix D are set to 1. This algorithm may be useful in circumstances where the scaled version of converges too slowly, or the function is already scaled appropriately.") ;;;;**************************************************************************** ;;;; Covariance ;;;;**************************************************************************** ;; ;; Original: ;; (defmfun ls-covariance ;; (solver relative-error &optional covariance ;; &aux (cov (or covariance ;; (grid:make-foreign-array 'double-float ;; :dimensions ;; (list (dim1 solver) (dim1 solver)))))) ;; "gsl_multifit_covar" ;; (((jacobian solver) :pointer) (relative-error :double) ((mpointer cov) :pointer)) ;; :return (cov) ;; :documentation ; FDL ;; "Compute the covariance matrix of the best-fit parameters ;; using the Jacobian matrix J. The relative error ;; is used to remove linear-dependent columns when J is ;; rank deficient. The covariance matrix is given by ;; C = (J^T J)^{-1} ;; and is computed by QR decomposition of J with column-pivoting. Any ;; columns of R which satisfy |R_{kk}| <= relative-error |R_{11}| ;; are considered linearly-dependent and are excluded from the covariance ;; matrix (the corresponding rows and columns of the covariance matrix are ;; set to zero). ;; If the minimisation uses the weighted least-squares function ;; f_i = (Y(x, t_i) - y_i) / sigma_i then the covariance ;; matrix above gives the statistical error on the best-fit parameters ;; resulting from the gaussian errors sigma_i on ;; the underlying data y_i. This can be verified from the relation ;; \delta f = J \delta c and the fact that the fluctuations in f ;; from the data y_i are normalised by sigma_i and ;; so satisfy <delta f delta f^T> = I. ;; For an unweighted least-squares function f_i = (Y(x, t_i) - ;; y_i) the covariance matrix above should be multiplied by the variance ;; of the residuals about the best-fit sigma^2 = sum (y_i - Y(x,t_i))^2 / (n-p) ;; to give the variance-covariance matrix sigma^2 C. ;; This estimates the statistical error on the ;; best-fit parameters from the scatter of the underlying data. ;; For more information about covariance matrices see the GSL documentation ;; Fitting Overview.") (defmfun ls-covariance (solver relative-error &optional covariance &aux (cov (or covariance (grid:make-foreign-array 'double-float :dimensions (list (dim1 solver) (dim1 solver))))) (jac (grid:make-foreign-array 'double-float :dimensions (list (dim0 solver) (dim1 solver))))) "gsl_multifit_covar" (((jacobian solver (mpointer jac)) :pointer) (relative-error :double) ((mpointer cov) :pointer)) :return (cov) :documentation ; FDL "Compute the covariance matrix of the best-fit parameters using the Jacobian matrix J. The relative error is used to remove linear-dependent columns when J is rank deficient. The covariance matrix is given by C = (J^T J)^{-1} and is computed by QR decomposition of J with column-pivoting. Any columns of R which satisfy |R_{kk}| <= relative-error |R_{11}| are considered linearly-dependent and are excluded from the covariance matrix (the corresponding rows and columns of the covariance matrix are set to zero). If the minimisation uses the weighted least-squares function f_i = (Y(x, t_i) - y_i) / sigma_i then the covariance matrix above gives the statistical error on the best-fit parameters resulting from the gaussian errors sigma_i on the underlying data y_i. This can be verified from the relation \delta f = J \delta c and the fact that the fluctuations in f from the data y_i are normalised by sigma_i and so satisfy <delta f delta f^T> = I. For an unweighted least-squares function f_i = (Y(x, t_i) - y_i) the covariance matrix above should be multiplied by the variance of the residuals about the best-fit sigma^2 = sum (y_i - Y(x,t_i))^2 / (n-p) to give the variance-covariance matrix sigma^2 C. This estimates the statistical error on the best-fit parameters from the scatter of the underlying data. For more information about covariance matrices see the GSL documentation Fitting Overview.") ;;;;**************************************************************************** ;;;; Example ;;;;**************************************************************************** ;;; The example from Section 37.9 of the GSL manual. ;;; See the GSL source tree, doc/examples/expfit.c for the functions ;;; and doc/examples/nlfit.c for the solver. (defstruct exponent-fit-data n y sigma) (defvar *nlls-example-data*) (defun generate-nlls-data (&optional (number-of-observations 40)) "Create the data used in the nonlinear least squares fit example." (make-exponent-fit-data :n number-of-observations :y (let ((arr (grid:make-foreign-array 'double-float :dimensions number-of-observations)) (rng (make-random-number-generator +mt19937+ 0))) (dotimes (i number-of-observations arr) (setf (grid:aref arr i) (+ 1 (* 5 (exp (* -1/10 i))) (sample rng :gaussian :sigma 0.1d0))))) :sigma (grid:make-foreign-array 'double-float :dimensions number-of-observations :initial-element 0.1d0))) (defun exponential-residual (x f) "Compute the negative of the residuals with the exponential model for the nonlinear least squares example." (let ((A (grid:aref x 0)) (lambda (grid:aref x 1)) (b (grid:aref x 2))) (symbol-macrolet ((y (exponent-fit-data-y *nlls-example-data*)) (sigma (exponent-fit-data-sigma *nlls-example-data*))) (dotimes (i (exponent-fit-data-n *nlls-example-data*)) (setf (grid:aref f i) ;; the difference model - observation = - residual (/ (- (+ (* A (exp (* (- lambda) i))) b) (grid:aref y i)) (grid:aref sigma i))))))) (defun exponential-residual-derivative (x jacobian) "Compute the partial derivatives of the negative of the residuals with the exponential model for the nonlinear least squares example." (let ((A (grid:aref x 0)) (lambda (grid:aref x 1))) (symbol-macrolet ((sigma (exponent-fit-data-sigma *nlls-example-data*))) (dotimes (i (exponent-fit-data-n *nlls-example-data*)) (let ((e (exp (* (- lambda) i))) (s (grid:aref sigma i))) (setf (grid:aref jacobian i 0) (/ e s) (grid:aref jacobian i 1) (* -1 i A (/ e s)) (grid:aref jacobian i 2) (/ s))))))) (defun exponential-residual-fdf (x f jacobian) "Compute the function and partial derivatives of the negative of the residuals with the exponential model for the nonlinear least squares example." (exponential-residual x f) (exponential-residual-derivative x jacobian)) (defun norm-f (fit) "Find the norm of the fit function f." (euclidean-norm (function-value fit))) (defun nonlinear-least-squares-example (&optional (number-of-observations 40) (method +levenberg-marquardt+) (print-steps t)) (let ((*nlls-example-data* (generate-nlls-data number-of-observations))) (let* ((init (grid:make-foreign-array 'double-float :initial-contents '(1.0d0 0.0d0 0.0d0))) (number-of-parameters 3) covariance (fit (make-nonlinear-fdffit method (list number-of-observations number-of-parameters) '(exponential-residual exponential-residual-derivative exponential-residual-fdf) init nil))) (macrolet ((fitx (i) `(grid:aref (solution fit) ,i)) (err (i) `(sqrt (grid:aref covariance ,i ,i)))) (when print-steps (format t "iter: ~d x = ~15,8f ~15,8f ~15,8f |f(x)|=~7,6g~&" 0 (fitx 0) (fitx 1) (fitx 2) (norm-f fit))) (loop for iter from 0 below 25 until (and (plusp iter) (fit-test-delta fit 1.0d-4 1.0d-4)) do (iterate fit) (setf covariance (ls-covariance fit 0.0d0 covariance)) (when print-steps (format t "iter: ~d x = ~15,8f ~15,8f ~15,8f |f(x)|=~7,6g~&" (1+ iter) (fitx 0) (fitx 1) (fitx 2) (norm-f fit))) finally (let* ((chi (norm-f fit)) (dof (- number-of-observations number-of-parameters)) (c (max 1.0d0 (/ chi (sqrt dof))))) (when print-steps (format t "chisq/dof = ~g~&" (/ (expt chi 2) dof)) (format t "A = ~,5f +/- ~,5f~&" (fitx 0) (* c (err 0))) (format t "lambda = ~,5f +/- ~,5f~&" (fitx 1) (* c (err 1))) (format t "b = ~,5f +/- ~,5f~&" (fitx 2) (* c (err 2)))) (return (list (fitx 0) (fitx 1) (fitx 2))))))))) (save-test nonlinear-least-squares (nonlinear-least-squares-example 40 +levenberg-marquardt+ nil))
19,318
Common Lisp
.lisp
402
43.475124
98
0.654865
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
888472ab17a5ca1810bfc91c4c7d5261bcfb17597416f06779658924cfc5b1f7
1,667
[ -1 ]
1,668
gnuplot-interface.lisp
ghollisjr_cl-ana/gnuplot-interface/gnuplot-interface.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.gnuplot-interface) (defun gnuplot-init () (let ((session (start "gnuplot" () :input :stream :output :stream :error :output :external-format :utf-8))) session)) (defun gnuplot-close (session) (close (process-input-stream session))) (defun gnuplot-cmd (session command-string) (let ((input-stream (process-input-stream session))) (format input-stream "~a~%" command-string) (finish-output input-stream)))
1,430
Common Lisp
.lisp
38
32.973684
70
0.658501
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
fd735fdd673efbf97e6249cab40cb2ad48f6ca7c086b9914e5ea1b75f7bc27ca
1,668
[ -1 ]
1,669
package.lisp
ghollisjr_cl-ana/fitting/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (defpackage #:cl-ana.fitting (:use :cl :alexandria :cl-ana.err-prop :cl-ana.map) (:export :fit :residuals :get-value-alist ;; standard fit functions: :polynomial :exponential :power :logarithm :sinusoid ;; distributions: :gaussian :skewed-gaussian :gaussian-skew-factor :gauss-amp :poisson :poisson-alist)) (cl-ana.gmath:use-gmath :cl-ana.fitting)
1,353
Common Lisp
.lisp
42
27.952381
70
0.661574
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
74b80bb94361533611d69cac405746c1f1a91e5d3853da633838ea777e9ab558
1,669
[ -1 ]
1,670
functions.lisp
ghollisjr_cl-ana/fitting/functions.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.fitting) ;;;; Defines various fit functions for use with the least squares ;;;; fitting function (defun polynomial (params x) "A general single-dimensional polynomial. Gets its order from the size of params; assumes parameters are given from least order term to greatest. Example: A line f(x) = A + B*x ==> (polynomial (list A B) x)" (labels ((polynomial-worker (params x xtmp nparams result) (if (zerop nparams) result (polynomial-worker (rest params) x (* x xtmp) (1- nparams) (+ result (* (first params) xtmp)))))) (polynomial-worker params x 1 (length params) 0))) (defun exponential (params x) "Exponential fitting function: f(x) = A * exp(B * x) ==> (exponential (list A B) x)" (let ((A (first params)) (B (second params))) (* A (exp (* B x))))) (defun power (params x) "Power fitting function: f(x) = A * B^x ==> (power (list A B) x)" (let ((A (first params)) (B (second params))) (* A (expt B x)))) (defun logarithm (params x) "A logarithmic fit function: f(x) = A + log(B * x) ==> (logarithm (list A B) x)" (let ((A (first params)) (B (second params))) (+ A (log (* B x))))) (defun sinusoid (params x) "A sinusoidal fit function: f(x) = A * sin(omega*x + phi) ==> (sinusoid (list A omega phi) x)" (let ((A (first params)) (omega (second params)) (phi (third params))) (* A (sin (+ (* omega x) phi))))) (defun gaussian (params x) "Gaussian fit function: f(x) = A/(sigma*sqrt(2*pi)) * exp(-((x-mu)/sigma)^2/2) ==> (gaussian (A mu sigma) x)" (let ((A (first params)) (mu (second params)) (sigma (third params))) (* (/ A (* sigma (sqrt (* 2 pi)))) (exp (- (/ (expt (/ (- x mu) sigma) 2) 2)))))) (defun gaussian-skew-factor (x mu sigma skew) "Factor which skews a Gaussian or any function convoluted with a Gaussian using the mean and standard deviation of the Gaussian component along with a skewing parameter skew. Multiplying a Gaussian or Gaussian-convoluted function with this skew factor preserves normalization." (+ 1d0 (gsll:erf (/ (* skew (- x mu)) (* sigma (sqrt 2d0)))))) (defun skewed-gaussian (params x) "Skewed Gaussian fit function. Parameters are (A mu sigma skew) where skew controls the skewing. Changing skew does not change normalization." (destructuring-bind (A mu sigma skew) params (* (gaussian (list A mu sigma) x) (gaussian-skew-factor x mu sigma skew)))) ;; a helper function for guessing the appropriate value of the ;; gaussian amplitude: (defun gauss-amp (peak sigma) "The relationship between the peak of a gaussian and the amplitude is complicated by sigma, so this function computes the amplitude given the peak height and sigma estimate." (* (sqrt (* 2 pi)) peak sigma)) (defun poisson (p n) "Poisson distribution: (poisson (A lambda) n) ==> A * lambda^n * exp(-lambda) / n!" (destructuring-bind (A l) p (* A (exp (- l)) (let ((res 1d0)) (do ((i 1 (1+ i))) ((>= i n) res) (setf res (* res (/ l (float i 0d0))))))))) (defun poisson-alist (p n) "Since computing poisson distribution is relatively inefficient point-by-point, but there is an efficient algorithm for computing a range of values of the poisson distribution, this function provides this functionality, returning an alist mapping each integer from 0 to n to the poisson distribution value." (destructuring-bind (A l) p (let ((f (* A (exp (- l))))) (do ((i 1 (1+ i)) (r (* f l) (* r l (/ (float (1+ i) 0d0)))) (result (list (cons 0 f)) (cons (cons i r) result))) ((> i n) (nreverse result))))))
4,759
Common Lisp
.lisp
139
29.805755
70
0.630619
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
d602fa51aa374e8b93b956bca81888d27712044a49ca444cab7d057723da944b
1,670
[ -1 ]
1,671
fitting.lisp
ghollisjr_cl-ana/fitting/fitting.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.fitting) ;;;; Provides function fit which is a high level interface to the GSLL ;;;; nonlinear-least-squares functionality. Includes numeric ;;;; calculation of the jacobian instead of having to do tedious hand ;;;; calculations or write automatic/symbolic differentiation ;;;; routines. ;;;; ;;;; Also allows for weighted fitting if one uses err-num values as ;;;; the dependent variable values in the data to be fitted against ;;;; (uncertainty in the independent variable is not currently ;;;; supported, but theoretically this is outside the scope of the ;;;; technique itself. ;;;; ;;;; To be able to call the fit function for your data object, just ;;;; define a specialization on the generic function map->alist ;;;; which returns an alist mapping the independent values to the ;;;; dependent value (which must be either a regular common lisp ;;;; number or an err-num). (defun alist-to-arrays (alist) (let ((xarray (map 'vector #'car alist)) (yarray (map 'vector #'cdr alist))) (values xarray yarray))) (defun list-to-grid (list) (let ((result (grid:make-foreign-array 'double-float :dimensions (length list)))) (loop for l in list for i from 0 do (setf (grid:aref result i) (float l 0d0))) result)) (defun grid-to-list (grid) (let ((dim (first (grid:dimensions grid)))) (loop for i from 0 below dim collect (grid:aref grid i)))) (defun fit (data-source fn init-params &key (max-iterations 25) (prec 1.0d-6) (derivative-delta 1d-11) post-residual) "Fits a function fn against data from data-source using the initial parameters init-params. Use err-num data type in the dependent variable's value if you want to do a weighted least squares fit. data-source: A generic object which has a map->alist function defined for it. This is the data which will be fitted against. fn: A function which takes two arguments: 1. A fit parameter list (must be a list), 2. The independent variable value which will come from the data to be fitted against. There is however one restriction when using err-num values as the dependent variable value: You must either use err-num values for every datum or none; I don't know of a good way to handle mixing err-num values with non-err-num values which wouldn't be more cumbersome than having the user decide. init-params: a list of the initial parameter values. post-residual: an optional function called on the residual. This allows for vector/list dependent values of fit function and data. E.g. euclidean-norm2 will result in fitting the norm squared of the vector residuals. The return values of fit are: 1. fn with the best-fit parameters applied, 2. The list of best-fit parameters, 3. The list of uncertainties in the best-fit parameters, 4. The value of chi^2/(degrees of freedom) for the fit, 5. The number of iterations it took to converge on the solution." (let* ((data (map->alist data-source)) (xlist (mapcar #'car data)) (ylist (mapcar #'cdr data)) (n-params (length init-params)) (n-data (length data)) (init-param-grid (list-to-grid init-params)) covariance num-iterations) (let ((residual-fn (flet ((->df (x) (cl-ana.math-functions:->double-float x))) (let ((res (if (subtypep (type-of (first ylist)) 'err-num) (lambda (param-list x y) (->df (/ (- (funcall fn param-list x) (err-num-value y)) (err-num-error y)))) (lambda (param-list x y) (->df (- (funcall fn param-list x) y)))))) (if post-residual (lambda (&rest xs) (->df (funcall post-residual (apply res xs)))) res))))) (labels ((residual (param-grid result-grid) (let ((param-list (grid-to-list param-grid))) (loop for i from 0 below n-data for x in xlist for y in ylist do (setf (grid:aref result-grid i) (funcall residual-fn param-list x y))))) (make-residual-jacobian (fn n-data n-params) (lambda (param-grid jacobian) (let ((param-list (grid-to-list param-grid))) (loop for i from 0 below n-data for x in xlist for y in ylist do (loop for j from 0 below n-params do (let* ((changed-param-list (loop for k from 0 for p in param-list collect (if (= k j) (+ p derivative-delta) p)))) (setf (grid:aref jacobian i j) (/ (- (funcall fn changed-param-list x y) (funcall fn param-list x y)) derivative-delta))))))))) (let* ((residual-jacobian (make-residual-jacobian residual-fn n-data n-params)) (fit (gsll:make-nonlinear-fdffit gsll:+levenberg-marquardt+ (list n-data n-params) (list #'residual residual-jacobian (lambda (x f jacobian) (funcall #'residual x f) (funcall residual-jacobian x jacobian))) init-param-grid nil))) (macrolet ((fitx (i) `(grid:aref (gsll:solution fit) ,i)) (err (i) `(sqrt (grid:aref covariance ,i ,i)))) (loop for iter from 0 below max-iterations until (and (plusp iter) ;;(gsll:fit-test-delta fit prec prec)) (gsll:fit-test-delta fit 0d0 prec)) do (gsll:iterate fit) finally (progn (setf covariance (gsll:ls-covariance fit 0.0d0 covariance)) (setf num-iterations iter))) (let* ((chi (gsll::norm-f fit)) (dof (- n-data n-params)) ;(c (max 1.0d0 (/ chi (sqrt dof))))) ;; not sure why ;they made the cutoff ;;(c (/ chi (sqrt dof))) (c (protected-/ chi (sqrt dof))) ) (let ((fit-params (loop for i from 0 below n-params collect (fitx i))) (fit-errors (loop for i from 0 below n-params collect (* c (err i))))) (values (curry fn fit-params) fit-params fit-errors (expt c 2) num-iterations))))))))) (defun residuals (data fn) "Computes the residuals from the fit to data (- data fit)" (mapcar (lambda (d) (destructuring-bind (x . y) d (cons x (- y (funcall fn x))))) data))
8,475
Common Lisp
.lisp
198
30.792929
83
0.545202
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
ceefc3f21decf3e3ab45bd1abc3aedb4d41a795e1621681d7b92957583e0cdce
1,671
[ -1 ]
1,672
test.lisp
ghollisjr_cl-ana/fitting/test.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (defun test (num-data) (let ((data (loop for i below num-data collect (cons i (+ i (- (/ (random 30) 30) 5d-1)))))) (cl-ana.fitting:fit (lambda (p x) (let ((A (first p)) (B (second p))) (+ (* A x) B))) data (list 0.0 1.0) :prec 1d-6)))
1,280
Common Lisp
.lisp
32
33.5
70
0.590545
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
bbfb20607abea9f88186211e88186b8032a051de10db078d2dc0240a6b5656f4
1,672
[ -1 ]
1,673
package.lisp
ghollisjr_cl-ana/makeres-table/package.lisp
(defpackage #:cl-ana.makeres-table (:use :cl :cl-ana.memoization :cl-ana.list-utils :cl-ana.macro-utils :cl-ana.table :cl-ana.reusable-table :cl-ana.hdf-utils :cl-ana.csv-table :cl-ana.ntuple-table :cl-ana.hdf-table :cl-ana.hash-table-utils :cl-ana.string-utils :cl-ana.makeres :cl-ana.makeres-macro) (:export ;; table reduction operators: :srctab :dotab :ltab :tab ;; field macros :deflfields :deflfieldsfn :field :push-fields ;; implementation macro: :table-pass ;; transformations :tabletrans ;; openers: :hdf-opener :hdf-chain-opener :ntuple-opener :csv-opener :plist-opener ;; macro expansion: :ensure-table-binding-ops :ensure-table-op-expanders ;; progress printing: :*print-progress* ;; expression utilities: :resform? :unres :mkres :table-reduction? :tab? :ltab? :dotab? :table-reduction-source ;; Special operators: :defhist ;; Copy utils: :copy-lfields ;; Utilities: :table-target? ;;; For implementing other tabletrans-like operators: ;; Backbone of the algorithm, grouping ids into passes :group-ids-by-pass ;; source tables, immediate, and necessary reductions :ultimate-source-tables :immediate-reductions :immediate-reductions-map :necessary-pass-reductions ;; reduction chains :chainmap :invert-chainmap :chained-edge-map :chained-reductions ;; ltab chains :ltab-chainmap :ltab-chain-edge-map :ltab-chained-reductions :ltab-chains ;; Dependency map functions for use with group-ids-by-pass :invert-depmap :removed-source-depmap :removed-source-dep< :removed-ltab-source-depmap :removed-ltab-source-dep< ;; res-macros that are commonly useful :dotab-nrows :dotab-mean :dotab-standard-deviation ))
1,928
Common Lisp
.lisp
85
17.976471
61
0.670646
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
cdaa489bc3289dd4349119e6672c4b9307146d77a3bd61c10ea220446f8d0133
1,673
[ -1 ]
1,674
table-operators.lisp
ghollisjr_cl-ana/makeres-table/table-operators.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.makeres-table) (defvar *proj->tab->lfields* (make-hash-table :test 'equal) "Map from table id to any lfields defined via deflfields.") ;; logical lfield definition: (defun deflfieldsfn (table-id lfields &key (op :add)) "function version of deflfields" (when (not (gethash (project) *proj->tab->lfields*)) (setf (gethash (project) *proj->tab->lfields*) (make-hash-table :test 'equal))) (symbol-macrolet ((lfs (gethash table-id (gethash (project) *proj->tab->lfields*)))) (case op (:set (setf lfs lfields)) (:add (setf lfs (reduce (lambda (result next) (adjoin next result :key #'first :test #'eq)) lfields :initial-value (remove-if (lambda (lf) (member (first lf) lfields :key #'first :test #'eq)) lfs)))))) nil) ;; and the macro: (defmacro deflfields (table-id lfields &key (op :add)) "Sets logical fields for table-id; can be referenced via field by any reductions of the table. op can be :add or :set, resulting in adding lfields or setting lfields respectively." `(deflfieldsfn ',table-id ',lfields :op ,op)) ;; Source tables: (defmacro srctab (opener &optional bootstrap) "Operator for denoting a source table. Necessary for logging." `(funcall ,opener :read)) ;; General table reduction: (defmacro dotab (source-table init-bindings return &body body) "Operator used for denoting a loop over a table. init-bindings are placed in a let* outside the loop body, which executes body once per row in a context where the macro field is defined which has access to any physical or logical fields by their symbol. return is the return value of the dotab, executed inside the init-bindings let form." `(table-pass ,source-table ,init-bindings ,return () ,@body)) ;; Physical table reductions: (defmacro tab (source inits opener &body body) "Operator for generating physical tables via table-pass. Returns a table-pass form (so you can run macroexpand on it in a graph transformation). source is the source table to be iterated over. opener should be a closure which accepts a single keyword argument. When given keyword argument :read it should return an open table object ready for reading, and when given keyword argument :write should return a table object ready for writing. opener should handle all necessary calls to table-close as well as managing e.g. open files. inits are used for bindings outside the table-pass loop. body will be placed in a macrolet which macrolets push-fields, accepting all arguments to table-push-field minus the destination table (will be supplied the result table)." (let ((closure (gsym 'tabletrans)) (result (gsym 'tabletrans))) `(table-pass ,source (,@inits (,closure ,opener) (,result (funcall ,closure :write))) (funcall ,closure :read) () (macrolet ((push-fields (&rest fields) `(table-push-fields ,',result ,@fields))) ,@body)))) ;; Logical table reductions: (defmacro ltab (source inits &body body) "Like tab, but for logical tables. Returns nil. Requires special treatment since logical tables don't yield a result. Arguments are simply for tracking the logical table." nil) ;;;; NOTES ;;;; ;;;; * The lfields argument is necessary in the way the merge ;;;; algorithm is currently written. There is however latent ;;;; functionality which allows for individual table-pass form ;;;; specific lfields in the algorithm which is unavailable to the ;;;; user if they use the dotab operator; it is not a loss due to ;;;; being able to use the let operator in the loop body, but this ;;;; note is for future reference if concerns about lfields arise. ;; general purpose table iteration, more functional than do-table, ;; used as implementation backbone for all makeres-table ;; transformations (defmacro table-pass (table inits result lfields &body body) "Loops over table with external bindings inits and result form result, executing body once per row. macro field yields the field value of current row. macro row-number yields the row number of current row. Limitations: Make sure no forms (field X) occur which are not meant to reference the field value. I've tried various options to make this work via macros but nothing short of code walking looks viable, and this is my naive code walking strategy's fault. When used with makeres, each table-pass is guaranteed to have independent lfields and inits, no matter what symbol names you choose. If you need a common lfield, use deflfields. If you need a common init binding, at the moment the only solution is to combine the targets manually (usually more conceptually clear incidentally)." ;; local macro fields will accept either symbol or string, and will ;; convert a symbol into a lower-case string for use in fields. ;; Having difficulties expanding the body to get the fields which ;; are present, trying to use &environment with expand macro but not ;; much luck so far. (let ((lfield->gsym (let ((result (make-hash-table :test 'equal))) (loop for i in lfields do (setf (gethash (first i) result) (gsym 'tabletrans))) result))) (let ((ri (gsym 'tabletrans))) `(macrolet ((field (field-sym) (or (gethash field-sym ,lfield->gsym) field-sym))) (let* ,inits (do-table (,ri ,table) ,(list->set (mapcar #'string (remove-if (lambda (x) (gethash x lfield->gsym)) (append (cl-ana.makeres::find-dependencies lfields 'field) (cl-ana.makeres::find-dependencies body 'field)))) #'string=) (olet ,(loop for i in lfields collect `(,(gethash (first i) lfield->gsym) ,(second i))) ,@(remove-if-not (lambda (x) (and (listp x) (eq (first x) 'declare))) body) (flet ((row-number () ,ri)) ,@(remove-if (lambda (x) (and (listp x) (eq (first x) 'declare))) body)))) ,result))))) ;;;; Special operators (defmacro defhist (id src expr init &key (test nil test-supplied-p) weight) "Defines a histogram reduction of table src with expr inserted into the result histogram. test is a form which, when evaluated in the table pass body should return non-nil for events to be inserted into the histogram. Supply expression for weight when events need reweighting." (alexandria:with-gensyms (hist) `(defres ,id (dotab (res ,src) ((,hist ,init)) ,hist ,(if test-supplied-p `(when ,test (hins ,hist ,expr ,@(when weight `(weight)))) `(hins ,hist ,expr ,@(when weight `(weight)))))))) ;;;; Copy utils: (defun copy-lfields (source dest &optional lfields) "Copies logical fields from source to dest" (let ((source-lfields (gethash source (gethash (project) *proj->tab->lfields*)))) (eval `(deflfields ,dest ,(if (null lfields) source-lfields (loop for f in source-lfields when (member (car f) lfields :test #'eq) collect f)))))) ;;;; Res-macros: (define-res-macro dotab-nrows (src) "Counts the number of rows in table." `(dotab ,src ((count 0)) count (incf count))) (define-res-macro dotab-mean (src expr) "Computes mean for some expression in the table. Set protected to some numerical value to use protected-div with that value." `(dotab ,src ((count 0) (sum 0)) (handler-case (/ sum count) (error nil nil)) (incf count) (incf sum ,expr))) (define-res-macro dotab-standard-deviation (src expr) "Computes single pass standard deviation for some expression in the table. Set protected to some numerical value to use protected-div with that value." `(dotab ,src ((count 0) (sum 0) (ssum 0)) (handler-case (sqrt (/ (- ssum (/ (expt sum 2) count)) (1- count)))) (let ((expr ,expr)) (incf count) (incf sum expr) (incf ssum (expt expr 2)))))
10,145
Common Lisp
.lisp
240
33.1875
84
0.607573
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
0797c6bc3cc27fa239de0a4813d918a302f7419d2302535d34ec49954824be7f
1,674
[ -1 ]
1,675
logging.lisp
ghollisjr_cl-ana/makeres-table/logging.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.makeres-table) ;; Default behavior for tables: do nothing, they're usually stored via ;; files which should go in the work/ directory. ;;;; So far, the cleanest approach to handling non-tab-generated ;;;; tables is to provide operators for source tables. This way, ;;;; save-target and load-target could inspect the form to determine ;;;; how to re-open a table once it's been closed by save-target or ;;;; cleanup. ;;;; ;;;; Alternatives: ;;;; ;;;; source and bootstrap operators are not technically needed, as ;;;; tables which do not originate from a tab reduction could simply ;;;; have their expressions reevaluated to re-open them after they are ;;;; closed by save-object. This would carry the penalty of breaking ;;;; future operators however, if they were to do fancy things inside ;;;; the table creation form. ;;;; ;;;; Or, save-target when called on a non-tab-generated table could ;;;; unset the target-stat for the source table, meaning that ;;;; subsequent calls to makeres would be required to access the ;;;; source table. This would carry the penalty of not having ;;;; guaranteed access to previously computed results however. ;;;; ;;;; Also, since this functionality needs to be built into ;;;; save-target, this file actually needs to be moved to ;;;; makeres-table to avoid circular dependencies. logres-table will ;;;; then be absorbed into makeres-table. ;; (define-load-target-method table id ;; (or (cl-ana.makeres-table::tab? ;; (target-expr (gethash id (target-table)))) ;; (cl-ana.makeres-table::srctab? ;; (target-expr (gethash id (target-table))))) ;; (let* ((tar (gethash id (target-table))) ;; (expr (target-expr tar)) ;; (opener ;; (eval ;; (if (cl-ana.makeres-table::srctab? ;; (target-expr (gethash id (target-table)))) ;; (destructuring-bind (progn (srctab opener ;; &optional bootstrap)) expr ;; opener) ;; (destructuring-bind (progn ;; (tab source inits opener &rest body)) ;; expr ;; opener))))) ;; (setf (target-val tar) ;; (funcall opener :read)))) ;; (defmethod save-object ((tab table) path) ;; (table-close tab)) ;; (defmethod load-object ((type (eql 'table)) path) ;; nil) ;; (defmethod destruct-on-save? ((tab table)) ;; t) ;; (defmethod cleanup ((tab table)) ;; (table-close tab)) ;; reusable-table technically not a table: ;; (define-load-target-method reusable-table id ;; (or (cl-ana.makeres-table::tab? ;; (target-expr (gethash id (target-table)))) ;; (cl-ana.makeres-table::srctab? ;; (target-expr (gethash id (target-table))))) ;; (let* ((tar (gethash id (target-table))) ;; (expr (target-expr tar)) ;; (opener ;; (eval ;; (if (cl-ana.makeres-table::srctab? ;; (target-expr (gethash id (target-table)))) ;; (destructuring-bind (progn (srctab opener ;; &optional bootstrap)) expr ;; opener) ;; (destructuring-bind (progn ;; (tab source inits opener &rest body)) ;; expr ;; opener))))) ;; (setf (target-val tar) ;; (funcall opener :read)))) ;; Old versions: ;; (defmethod save-object ((tab reusable-table) path) ;; (table-close tab)) ;; (defmethod load-object ((type (eql 'reusable-table)) path) ;; nil) ;; New versions: (defmethod printable ((tab reusable-table)) nil) (defmethod save-object ((tab reusable-table) path) ;; Write opener form to file: (with-open-file (file path :direction :output :if-does-not-exist :create :if-exists :supersede) (let ((opener-form (reusable-table-opener-form tab))) (format file "~s~%" opener-form))) (table-close tab)) (defmethod load-object ((type (eql 'reusable-table)) path) (let* ((opener-form (with-open-file (file path :direction :input) (read file))) (opener (eval opener-form))) (funcall opener :read))) (defmethod destruct-on-save? ((tab reusable-table)) t) (defmethod cleanup ((tab reusable-table)) (table-close tab))
5,350
Common Lisp
.lisp
126
39.960317
79
0.61506
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
f94874a4ac5091ba363a7cb7af06170873b5377963d01e6f18ca78a7523d9646
1,675
[ -1 ]
1,676
tabletrans.lisp
ghollisjr_cl-ana/makeres-table/tabletrans.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.makeres-table) (defvar *print-progress* nil "Set this to nil if you don't want to see progress messages printed; set this to an integer value to specify the number of rows at which to print a progress update message. Note that this should only be used for tables which know their size (so CSV tables don't work with this).") (defun table-reduction? (expr) "True if expr is a dotab, ltab or tab expression" (when (and expr (listp expr)) (destructuring-bind (progn &rest forms) expr (when (listp (first forms)) (let ((tab-op (first (first forms)))) (member tab-op (list 'table-pass 'dotab 'ltab 'tab) :test 'eq)))))) (defun table-target? (id) (let ((tar (gethash id (target-table)))) (and (target-stat tar) (or (tab? (target-expr tar)) (ltab? (target-expr tar)) (typep (target-val tar) 'table) (typep (target-val tar) 'reusable-table))))) (defun table-pass? (expr) "True if expr is a table-pass expression" (when expr (destructuring-bind (progn &rest forms) expr (let ((tab-op (first (first forms)))) (eq tab-op 'table-pass))))) (defun srctab? (expr) "True if expr is a srctab expression" (when (and expr (listp expr) (listp (second expr))) (destructuring-bind (progn &rest forms) expr (let ((tab-op (first (first forms)))) (eq tab-op 'srctab))))) (defun dotab? (expr) "True if expr is a dotab expression" (when expr (destructuring-bind (progn &rest forms) expr (let ((tab-op (first (first forms)))) (eq tab-op 'dotab))))) (defun tab? (expr) "True if expr is a tab expression" (when (and expr (listp expr)) (destructuring-bind (progn &rest forms) expr (when (listp (first forms)) (let ((tab-op (first (first forms)))) (eq tab-op 'tab)))))) (defun ltab? (expr) "True if expr is an ltab expression" (when (and expr (listp expr)) (destructuring-bind (progn &rest forms) expr (when (listp (first forms)) (let ((tab-op (first (first forms)))) (eq tab-op 'ltab)))))) (eval-when (:compile-toplevel :load-toplevel :execute) ;; Very useful functions, adding to package external symbols (defun resform? (expr) "Returns true if expr is of the form (res x)" (and (listp expr) (eq (first expr) 'res))) (defun unres (expr) "Gets id from a res form if it is a res form, if not, returns expr." (if (resform? expr) (second expr) expr)) (defun mkres (expr) "Ensures that expr is a res form" (if (resform? expr) expr (list 'res expr)))) (defun table-reduction-source (expr) "Returns source for table reduction, nil if expr is not of a table-reduction." (when (table-reduction? expr) (cadadr expr))) (defun (setf table-reduction-source) (value expr) (when (table-reduction? expr) (setf (cadadr expr) value))) (defun table-reduction-inits (expr) "Returns init bindings when expr is a table-reduction, nil otherwise." (when (table-reduction? expr) (destructuring-bind (progn tab-form) expr (elt tab-form 2)))) ;; call on table-pass or dotab only (defun table-reduction-return (expr) (when (or (dotab? expr) (table-pass? expr)) (destructuring-bind (progn tab-form) expr (elt tab-form 3)))) (defun table-reduction-body (expr) (when (table-reduction? expr) (destructuring-bind (progn tab-form) expr (cond ((table-pass? expr) (nthcdr 5 tab-form)) ((dotab? expr) (nthcdr 4 tab-form)) ((tab? expr) (nthcdr 4 tab-form)) ((ltab? expr) (nthcdr 3 tab-form)))))) ;; Needs to have its memo map reset periodically to free space. Best ;; practice is to place the reset at the top of your transformation if ;; you use this function. (defun-memoized immediate-reductions-old (target-table tab &key (reduction-test-fn #'table-reduction?) (reduction-source-fn #'table-reduction-source)) "Returns list of immediately dependent table reductions for a table" (remove-if-not (lambda (id) (let* ((tar (gethash id target-table)) (expr (target-expr tar))) (and (funcall reduction-test-fn expr) (equal (unres (funcall reduction-source-fn expr)) tab)))) (hash-keys target-table))) (defun-memoized immediate-reductions-map (target-table &key (reduction-test-fn #'table-reduction?) (reduction-source-fn #'table-reduction-source)) "Returns a hash-table mapping from table to reductions. It's much more efficient to use a single map than looping over the entire target table repeatedly." (let* ((result (make-hash-table :test 'equal))) (loop for id being the hash-keys in target-table do (let* ((tar (gethash id target-table)) (expr (target-expr tar))) (when (funcall reduction-test-fn expr) (let* ((tab (unres (funcall reduction-source-fn expr)))) (push id (gethash tab result)))))) result)) (defun immediate-reductions (target-table tab &rest key-args &key (reduction-test-fn #'table-reduction?) (reduction-source-fn #'table-reduction-source)) "Returns list of immediately dependent table reductions for a table" (let* ((ht (apply #'immediate-reductions-map target-table key-args))) (gethash tab ht))) ;; Testing this new ltab-chains function (defun ltab-chains (target-table chain-edge-map src &key (tab-test-fn #'tab?) (ltab-test-fn #'ltab?) (dotab-test-fn #'dotab?)) "Returns all ltab chains stemming from src. A ltab chain is simply a list of ltab ids which are chained reductions of either ltabs or the source table with id src along with the first non-ltab id which is a reduction of the last ltab in the chain." (labels ((chains (s &optional context) (let* ((children (gethash s chain-edge-map)) (filtered-children ;; Only accept dotabs and ltabs (remove-if-not (lambda (id) (and (gethash id target-table) (let ((expr (target-expr (gethash id target-table)))) (or (funcall tab-test-fn expr) (funcall dotab-test-fn expr) (funcall ltab-test-fn expr))))) children))) (if filtered-children (apply #'append (mapcar (lambda (c) (chains c (cons s context))) filtered-children)) (list (cons s context)))))) (mapcar #'reverse (chains src)))) (defun ltab-chained-reductions (target-table ltab-chain-edge-map src &key (tab-test-fn #'tab?) (ltab-test-fn #'ltab?) (dotab-test-fn #'dotab?)) "Returns all reductions directly from ltab chains stemming from src" (mapcar #'alexandria:last-elt (ltab-chains target-table ltab-chain-edge-map src :tab-test-fn tab-test-fn :ltab-test-fn ltab-test-fn :dotab-test-fn dotab-test-fn))) (defun necessary-pass-reductions (target-table chain-edge-map tab &key (tab-test-fn #'tab?) (ltab-test-fn #'ltab?) (dotab-test-fn #'dotab?) (reduction-test-fn #'table-reduction?) (reduction-source-fn #'table-reduction-source)) "Returns list of reductions of a table which must be computed via a pass over the table; equivalent to the union set of all immediate non-ltab reductions and any reductions chained directly to tab via logical tables." (list->set (append (remove-if (lambda (id) (funcall ltab-test-fn (target-expr (gethash id target-table)))) (immediate-reductions target-table tab :reduction-test-fn reduction-test-fn :reduction-source-fn reduction-source-fn)) (ltab-chained-reductions target-table chain-edge-map tab :tab-test-fn tab-test-fn :ltab-test-fn ltab-test-fn :dotab-test-fn dotab-test-fn)) #'equal)) (defun chained-edge-map (target-table &key (reduction-test-fn #'table-reduction?) (reduction-source-fn #'table-reduction-source)) "Returns an edgemap which only describes the chains of table reductions." (let* ((uncompressed nil)) ;; Generate uncompressed table dependency edges (loop for id being the hash-keys in target-table for tar being the hash-values in target-table when (funcall reduction-test-fn (target-expr tar)) do (push (cons (unres (funcall reduction-source-fn (target-expr tar))) id) uncompressed)) (compress-edge-map uncompressed))) (defun chained-reductions (chained-edge-map src) "Returns list of ids for targets from target-table which are connected via a chain of reductions from src." (let ((imm-reds (gethash src chained-edge-map))) (when imm-reds (append imm-reds (mapcan (lambda (red) (copy-list (chained-reductions chained-edge-map red))) imm-reds))))) (defun group-ids-by-pass (chained-edge-map src depsorted-ids dep< &key (test (constantly t))) "Groups all ids from target-table according the the pass required over src, optionally using the dependency checker dep< and keeping only targets for which test returns t." (let* ((chained (chained-reductions chained-edge-map src)) (sorted-ids (let ((depsorted depsorted-ids)) (remove-if-not (lambda (x) (and (member x chained :test #'equal) (funcall test x))) depsorted)))) (when sorted-ids (let ((pass (list (pop sorted-ids))) (result nil)) (labels ((rec () (dolist (i sorted-ids) (when (every (lambda (p) (funcall dep< i p)) pass) (push i pass))) (push (reverse pass) result) (setf sorted-ids (remove-if (lambda (sid) (member sid pass :test #'equal)) sorted-ids)) (if sorted-ids (progn (setf pass (list (pop sorted-ids))) (rec)) (nreverse result)))) (rec)))))) (defun ultimate-source-tables (target-table &key ignore (reduction-test-fn #'table-reduction?) (reduction-source-fn #'table-reduction-source)) "Returns list of source table ids which are not table reductions of non-ignored sources." (let ((srcs nil) (reds nil)) (loop for id being the hash-keys in target-table for tar being the hash-values in target-table do (let ((expr (target-expr tar))) (when (funcall reduction-test-fn expr) (let* ((raw-src (funcall reduction-source-fn expr)) (src (if (and (listp raw-src) (eq (first raw-src) 'res)) (second raw-src) raw-src))) (when (not (member src ignore :test #'equal)) (push id reds) (setf srcs (adjoin src srcs :test #'equal))))))) (set-difference srcs reds :test #'equal))) (defun ultimate-source-tables-new (target-table &key ignore (reduction-test-fn #'table-reduction?) (reduction-source-fn #'table-reduction-source)) "Returns list of source table ids which are not table reductions of non-ignored sources." (let ((srcs nil) (reds nil)) (loop for id being the hash-keys in target-table for tar being the hash-values in target-table do (let ((expr (target-expr tar))) (when (funcall reduction-test-fn expr) (let* ((raw-src (funcall reduction-source-fn expr)) (src (if (and (listp raw-src) (eq (first raw-src) 'res)) (second raw-src) raw-src)) (srcexpr (target-expr (gethash src target-table)))) (when (and (not (member src ignore :test #'equal)) (not (ltab? srcexpr))) (push id reds) (setf srcs (adjoin src srcs :test #'equal))))))) (set-difference srcs reds :test #'equal))) ;; Need to modify the removed-*-dep< functions due to the new ;; topological sort algorithm added to makeres. The concepts of these ;; still apply, but they must be implemented in a new way. ;; ;; As a quick-fix, the depmap needs to be inverted, i.e., instead of ;; finding dependencies, you find dependents. Then this inverted map ;; can be returned as a compressed version of the edges of a directed ;; acyclic graph. ;; I'm trying a new version of the removed-*-depmap algorithms that I ;; think will be much clearer. ;; ;; The concept is this: ;; ;; When merging reductions, the chain of source tables must not be ;; considered dependencies of the reductions. ;; ;; When merging reductions through logical tables, the contiguous ;; chain of logical tables back to the first non-logical table must ;; not be considered dependencies of the reductions. The source table ;; itself can and likely should remain a dependency however. ;; ;; Each reduction has a single chain of tables sources, so I should ;; ;; 1. Calculate the full dependency map of the relevant subsection of ;; the target table ;; ;; 2. Calculate the source table chains for the relevant subsection of ;; the target table ;; ;; 3. Remove whatever subset of the table chain from the dependency ;; map for each reduction (defun chainmap (target-table &key (reduction-test-fn #'table-reduction?) (reduction-source-fn #'table-reduction-source)) "Returns a hash table mapping from reduction to the chain of source tables producing the reduction." (memolet (;; Returns full list of sources up the chain (sources (id &optional context) (let* ((tar (gethash id target-table)) (expr (target-expr tar))) (if (funcall reduction-test-fn expr) (let ((src (unres (funcall reduction-source-fn expr)))) (sources src (cons src context))) context)))) (let ((result (make-hash-table :test 'equal))) (loop for id being the hash-keys in target-table for tar being the hash-values in target-table when (funcall reduction-test-fn (target-expr tar)) do (setf (gethash id result) (sources id))) result))) (defun ltab-chainmap (target-table chainmap &key (ltab-test-fn #'ltab?)) "Returns the ltab chains for each reduction in the target-table. An ltab-chain is the chain of tables from the reduction to the nearest non-logical table source." (let ((result (make-hash-table :test 'equal))) (loop for red being the hash-keys in chainmap do (let* ((chain (gethash red chainmap)) (spos (position-if-not (lambda (i) (funcall ltab-test-fn (target-expr (gethash i target-table)))) chain :from-end t)) (lchain (subseq chain spos))) (setf (gethash red result) lchain))) result)) ;; I'm trying this without the non-reductions in the table for now (defun removed-source-depmap (depmap chainmap) "Returns a new depmap which does not contain the table sources in the depmap." (let ((result (make-hash-table :test 'equal))) (loop for id being the hash-keys in depmap do (let* ((deps (gethash id depmap)) (chain (gethash id chainmap))) (when chain (setf (gethash id result) (set-difference deps chain :test #'equal))))) result)) (defun removed-source-dep< (depmap) (lambda (x y) (not (member y (gethash x depmap) :test #'equal)))) (defun removed-ltab-source-depmap (depmap lchainmap) (let ((result (make-hash-table :test 'equal))) (loop for k being the hash-keys in depmap do (let* ((deps (gethash k depmap)) (lchain (gethash k lchainmap)) (ltabs (rest lchain))) (when lchain (setf (gethash k result) (set-difference deps ltabs :test #'equal))))) result)) (defun removed-ltab-source-dep< (depmap) (lambda (x y) (not (member y (gethash x depmap) :test #'equal)))) ;; Inverting chainmaps to yield maps from the source to the full ;; chain: (defun invert-chainmap (chainmap) "Returns a map from the source table to the list of chains associated with that table." (let ((result (make-hash-table :test 'equal))) (loop for red being the hash-keys in chainmap do (let* ((chain (gethash red chainmap)) (src (first chain))) (push chain (gethash src result)))) result)) ;;; Table pass expression components ;; Context tree functions: (defun node (id content &rest children) (apply #'list id content children)) (defun node-id (node) (first node)) (defun (setf node-id) (value node) (setf (first node) value)) (defun node-content (node) (second node)) (defun (setf node-content) (value node) (setf (second node) value)) (defun node-children (node) (cddr node)) (defun (setf node-children) (value node) (setf (cddr node) value)) (defun tree-ids (node) "Returns list of ids stored in node" (let ((result nil)) (labels ((rec (n) (let ((id (node-id n))) (setf result (adjoin id result :test #'equal)) (mapcar #'rec (node-children n))))) (rec node)) result)) (defun node-subcontent (node) "Returns set of contents contained by node and all its children" (list->set (append (node-content node) (mapcan (lambda (x) (copy-list (node-subcontent x))) (node-children node))) #'equal)) ;; must be given complete target graph, not just the null-stat targets (defun table-reduction-context-tree (graph src ids) "Returns tree of contexts each pass would be inside if collapsed up to src. Physical table reductions are treated as reductions with themselves as context." (let (;; map from source to immediate reductions used by ids (source->reds (make-hash-table :test 'equal))) (labels ((build-source->reds (id) ;; builds map from source table to immediate reductions (when (and (gethash id graph) (not (equal id src))) (let ((source (unres (table-reduction-source (target-expr (gethash id graph)))))) (setf (gethash source source->reds) (adjoin id (gethash source source->reds) :test #'equal)) (when (not (equal source src)) (build-source->reds source))))) (source->tree (source) ;; generates context tree for ids from source ;; ;; context tree nodes consist of source, content, and ;; child nodes. ;; ;; content is list of immediate reduction ids (let* (;; all reductions encountered (reds (gethash source source->reds)) ;; reductions which need to be placed in contexts (need-context-reds (append (remove-if (lambda (red) (or (target-stat (gethash red graph)) (ltab? (target-expr (gethash red graph))))) reds) (when (and (gethash source graph) (tab? (target-expr (gethash source graph))) (member source ids :test #'equal)) (list source)))) ;; reductions used as sources (source-reds (remove-if-not (lambda (red) (gethash red source->reds)) reds)) ;; child nodes: (children (mapcar #'source->tree source-reds))) (apply #'node source ;; remove any reds needing context which are ;; covered by some child node: (let ((subcontent (list->set (mapcan (lambda (x) (copy-list (node-subcontent x))) children) #'equal))) (remove-if (lambda (r) (member r subcontent :test #'equal)) need-context-reds)) children))) (tab-cleanup (tree) ;; Ensures that the tree obtained from source->tree ;; properly stores physical table nodes. Physical ;; table nodes should never be content of the immediate ;; source table, they should be child nodes which ;; contain at least themselves as content. (let* ((source (node-id tree)) (content (node-content tree)) (newcontent (remove-if (lambda (id) (and (tab? (target-expr (gethash id graph))) (not (equal id source)))) content)) (tabs (remove-if-not (lambda (id) (and (tab? (target-expr (gethash id graph))) (not (equal id source)))) content)) (children (copy-tree (node-children tree)))) ;; modify children appropriately (loop for tab in tabs do (loop for child in children when (and (equal (node-id child) tab) (not (member tab (node-content child)))) do (progn (push tab (node-content child)) (return)) finally (push (node tab (list tab)) children))) ;; return result (apply #'node source newcontent (mapcar #'tab-cleanup children))))) (mapcar #'build-source->reds ids) (tab-cleanup (source->tree src))))) ;; some shitty code walking (defun find-push-fields (form) "Returns the list of all argument lists given to all instances of push-fields in the form which are not within a macrolet definition." (when (and form (listp form)) (cond ((eq (first form) 'push-fields) (list (copy-list (rest form)))) ((eq (first form) 'macrolet) (mapcan #'find-push-fields (rest (rest form)))) (t (append (find-push-fields (car form)) (find-push-fields (cdr form))))))) (defun replace-push-fields (form replacements) "Replaces push-fields within form with replacement as long as it's not inside a macrolet definition" (let ((replacements (copy-tree replacements))) (labels ((rec (frm) (if (and frm (listp frm)) (cond ((eq (first frm) 'push-fields) (pop replacements)) ((eq (first frm) 'macrolet) `(macrolet ,(second frm) ,@(mapcar #'rec (rest (rest frm))))) (t (cons (rec (first frm)) (rec (rest frm))))) frm))) (rec form)))) ;; must be given complete target graph, not just the null-stat targets (defun make-pass-target-expr (graph src pass) "Return expression for pass target over src, collapsing all results from pass up to src." (flet ((htref (ht &rest keys) ;; looks up values stored in nested hash tables, one key ;; per hash table layer (reduce (lambda (h k) (gethash k h)) keys :initial-value ht))) ;; Context handling: (let* (;; tree of contexts, each node contains context name, ;; reduction ids needing to be placed in this context, and ;; sub context trees. (context-tree (table-reduction-context-tree graph src pass)) ;; set of reductions generated: (nodes (remove src (list->set (labels ((rec (n) (cons (node-id n) (append (node-content n) (mapcan #'rec (node-children n)))))) (rec context-tree))))) (reductions (remove src (list->set (labels ((rec (n) (let ((subcontent (append (node-content n) (mapcan #'rec (node-children n))))) (if (tab? (target-expr (gethash (node-id n) graph))) subcontent (cons (node-id n) subcontent))))) (rec context-tree))))) ;; map from reduction id to map from init binding variable ;; to gsym (reduction->initsym->gsym (make-hash-table :test 'equal)) ;; map from reduction id to map from init binding variable to ;; form. (reduction->initsym->expr (make-hash-table :test 'equal)) ;; map from reduction to return form: (reduction->return (make-hash-table :test 'equal)) ;; map from tab reduction to expanded form (needed due to ;; with-gensyms in the body) (tab-expanded-expr (make-hash-table :test 'equal))) ;; Initialize context maps: (macrolet ((setht (place k) `(setf (gethash ,k ,place) (make-hash-table :test 'equal)))) (loop for r in nodes do (progn (setht reduction->initsym->gsym r) (setht reduction->initsym->expr r) (setht reduction->return r)))) ;; Make maps from initsyms to gsyms and expressions for each ;; reduction (reduction->initsym->gsym, ;; reduction->initsym->expr) as well as map from reduction to ;; return form (loop for r in nodes do (let ((initsym->gsym (gethash r reduction->initsym->gsym)) (initsym->expr (gethash r reduction->initsym->expr)) (tar (gethash r graph)) (processed-initsym-bindings nil)) ;; returns: (setf (gethash r reduction->return) (let ((expr (target-expr tar))) (when (not (ltab? expr)) (let ((res (table-reduction-return (if (tab? expr) (setf (gethash r tab-expanded-expr) `(progn ,(macroexpand-1 (second expr)))) expr)))) res)))) ;; inits: (loop for (initsym . initexpr) in (table-reduction-inits (let ((expr (target-expr tar))) (if (tab? expr) (gethash r tab-expanded-expr) expr))) do (progn (setf (gethash initsym initsym->gsym) (gsym 'tabletrans)) (setf (gethash initsym initsym->expr) (copy-list ;; symbol-macrolet to use gsym bindings `(symbol-macrolet ,(loop for s in processed-initsym-bindings collect `(,s ,(gethash s initsym->gsym))) ,@initexpr))) (push initsym processed-initsym-bindings))))) ;; Make body via recursing through context tree ;; * Make sure to make use of gsymed inits via symbol-macrolets in ;; pass bodies (let* (;; gsymed init bindings for all reductions in pass: (inits (loop for r in reductions appending (let ((initsym->gsym (gethash r reduction->initsym->gsym)) (initsym->expr (gethash r reduction->initsym->expr))) (loop for s being the hash-keys in initsym->gsym for gsym being the hash-values in initsym->gsym collect (list gsym (gethash s initsym->expr)))))) ;; list of result forms making use of any gsymed values: (result-list (progn `(list ,@(loop for r in pass collect (let ((initsym->gsym (gethash r reduction->initsym->gsym))) `(symbol-macrolet ,(loop for s being the hash-keys in initsym->gsym for gsym being the hash-values in initsym->gsym collect (list s gsym)) ,(gethash r reduction->return))))))) ;; map from table to lfields for table: (tab->lfields (gethash (project) *proj->tab->lfields*)) ;; lfields expanded: (lfields ;; lfields from source (when tab->lfields (mapcar (lambda (binding) (cons (first binding) (mapcar #'expand-res-macros (rest binding)))) (gethash src tab->lfields)))) ;; resulting pass body: (body (labels ((rec (node) (let* ((c (node-id node)) (expr (target-expr (gethash c graph))) ;; push-field-bindings is a list of the ;; different bindings as found via ;; find-push-fields in the table pass body (push-field-bindings-list (cond ((and (tab? expr) (not (equal c src))) (find-push-fields (gethash c tab-expanded-expr))) ((ltab? expr) (find-push-fields (table-reduction-body expr))) ;; Source table special case: (t (list nil)))) (push-field-syms-list (mapcar #'cars push-field-bindings-list)) (push-field-gsyms-list (loop for bs in push-field-syms-list collecting (loop for b in bs collecting (gsym 'tabletrans)))) ;; list of maps, one per push-fields form (push-field->gsym-list (loop for push-field-syms in push-field-syms-list for push-field-gsyms in push-field-gsyms-list collecting (let ((ht (make-hash-table :test 'eq))) (loop for sym in push-field-syms for gsym in push-field-gsyms do (setf (gethash sym ht) gsym)) ht))) (lfields (let ((tab->lfields (gethash (project) *proj->tab->lfields*))) (when tab->lfields (gethash c tab->lfields)))) (lfield-syms (cars lfields)) (lfield-gsyms (loop for l in lfield-syms collecting (gsym 'tabletrans))) (lfield->gsym (let ((ht (make-hash-table :test 'eq))) (loop for lfield in lfield-syms for gsym in lfield-gsyms do (setf (gethash lfield ht) gsym)) ht)) (lfield-bindings (when lfields (loop for push-field-syms in push-field-syms-list for push-field->gsym in push-field->gsym-list appending (mapcar (lambda (binding) (cons (first binding) (sublis (append (loop for lfield in lfield-syms when (not (eq (first binding) lfield)) collecting (cons `(field ,lfield) (gethash lfield lfield->gsym))) (loop for push-field in push-field-syms collecting (cons `(field ,push-field) (gethash push-field push-field->gsym)))) (mapcar #'expand-res-macros (rest binding)) :test #'equal))) lfields)))) (olet-field-bindings-list (loop for push-field-bindings in push-field-bindings-list collecting (append push-field-bindings lfield-bindings))) (olet-field-gsyms-list (loop for push-field-gsyms in push-field-gsyms-list collecting (append push-field-gsyms lfield-gsyms))) (children-exprs (when (node-children node) (mapcar #'rec (node-children node)))) (content-tab->push-field-vector (let ((result (make-hash-table :test 'equal))) (loop for content in (node-content node) do (setf (gethash content result) (map 'vector #'identity (loop for push-field->gsym in push-field->gsym-list for push-fields in (find-push-fields (table-reduction-body (gethash content tab-expanded-expr))) collecting (loop for (field binding) in push-fields collecting (list field (gethash field push-field->gsym))))))) result)) (sub-bodies (loop for olet-field-bindings in olet-field-bindings-list for olet-field-gsyms in olet-field-gsyms-list for content-index from 0 collect ;; create push-fields and lfields bindings: `(olet ,(loop for (field form) in olet-field-bindings for gsym in olet-field-gsyms collect `(,gsym ,form)) ;; replace (field x) with x for x for every ;; x in the push-field-bindings ,@(sublis (loop for gsym in olet-field-gsyms for (field form) in olet-field-bindings collect (cons `(field ,field) gsym)) (append (mapcar (lambda (id) `(symbol-macrolet ,(let ((initsym->gsym (gethash id reduction->initsym->gsym))) (when initsym->gsym (loop for s being the hash-keys in initsym->gsym for gsym being the hash-values in initsym->gsym collecting (list s gsym)))) ,@(let ((expr (target-expr (gethash id graph)))) (if (tab? expr) `((push-fields ,@(aref (gethash id content-tab->push-field-vector) content-index))) (table-reduction-body expr))))) (node-content node)) children-exprs) :test #'equal))))) (if (and (not (equal c src)) (table-reduction? expr)) (let ((result (replace-push-fields `(progn (symbol-macrolet ,(awhen (gethash c reduction->initsym->gsym) (loop for s being the hash-keys in it for gsym being the hash-values in it collecting (list s gsym))) ,@(table-reduction-body (if (tab? expr) (gethash c tab-expanded-expr) expr)))) sub-bodies))) result) (first sub-bodies))))) (rec context-tree))) (row-var (gsym 'table-pass)) (nrows-var (gsym 'table-pass)) (print-pass-targets (when *print-progress* `((let ((*print-pretty* nil)) (format t "Pass over ~a to compute:~%" ',src) ,@(loop for r in pass collecting `(format t "~a~%" ',r)))))) (print-pass-targets-var (gsym 'table-pass)) (print-progress-inits (when *print-progress* `((,row-var 0) (,nrows-var (table-nrows ,(if (and (listp src) (eq (first src) 'res)) src `(res ,src)))) ;; message specifying what the pass will accomplish (,print-pass-targets-var ,@print-pass-targets)))) (print-progress (when *print-progress* `((progn (when (zerop (the fixnum (mod ,row-var (the fixnum ,*print-progress*)))) (when ,nrows-var (format t "Event ~a, ~$% complete~%" ,row-var (* 1f2 (/ (float ,row-var) (float ,nrows-var)))))) (incf ,row-var)))))) `(progn (table-pass ,(if (and (listp src) (eq (first src) 'res)) src `(res ,src)) (,@inits ,@print-progress-inits) ,result-list ,lfields ,@print-progress ,body)))))) (defun set-pass-result-targets! (result-graph id pass) "Sets result-graph targets from pass so that they make use of the returned results for the pass target id." (loop for p in pass for i from 0 do (setf (gethash p result-graph) (make-target p `(elt (res ,id) ,i) :val (target-val (gethash p result-graph)) :stat (target-stat (gethash p result-graph))))) nil) (defun ht-filter (fn ht) "Returns a new hash table with entries from ht only when fn returns true when given the key and value from ht." (let ((result (make-hash-table :test (hash-table-test ht)))) (loop for k being the hash-keys in ht for v being the hash-values in ht when (funcall fn k v) do (setf (gethash k result) v)) result)) (defparameter *table-binding-ops* (list 'tab 'ltab 'dotab 'push-fields)) (defun ensure-table-binding-ops () (ensure-binding-ops) (symbol-macrolet ((binding-ops (gethash (project) *proj->binding-ops*))) (setf binding-ops (list->set (append binding-ops *table-binding-ops*))))) (defun ensure-table-op-expanders () (symbol-macrolet ((op->expander (gethash (project) *proj->op->expander*))) ;; Create table & set expanders for cl: (ensure-op-expanders) ;; Set table expanders: ;; ltab (setf (gethash 'ltab op->expander) (lambda (expander form) (destructuring-bind (op source inits &rest body) form (list* op (funcall expander source) (mapcar (lambda (lst) (destructuring-bind (var binding) lst (list var (funcall expander binding)))) inits) (mapcar expander body))))) ;; tab (setf (gethash 'tab op->expander) (lambda (expander form) (destructuring-bind (op source inits opener &rest body) form (list* op (funcall expander source) (mapcar (lambda (lst) (destructuring-bind (var binding) lst (list var (funcall expander binding)))) inits) (funcall expander opener) (mapcar expander body))))) ;; dotab (setf (gethash 'dotab op->expander) (lambda (expander form) (destructuring-bind (op source inits return &rest body) form (list* op (funcall expander source) (mapcar (lambda (lst) (destructuring-bind (var binding) lst (list var (funcall expander binding)))) inits) (funcall expander return) (mapcar expander body))))) ;; push-fields (setf (gethash 'push-fields op->expander) (lambda (expander form) (destructuring-bind (push-fields &rest fields) form (list* push-fields (loop for f in fields collect (if (listp f) (list (first f) (funcall expander (second f))) f)))))))) (defun tabletrans (target-table) "Performs necessary graph transformations for table operators" ;; Reset memo maps: ;; old ;; (reset-memo-map #'immediate-reductions) ;; new (reset-memo-map #'immediate-reductions-map) ;; Close any open tables needing recomputation: (loop for id being the hash-keys in target-table for tar being the hash-values in target-table do (let ((val (target-val tar)) (stat (target-stat tar))) (when (and (not stat) (or (typep val 'table) (typep val 'reusable-table)) (table-open-p val)) (table-close val)))) ;; initialize operator expansion (ensure-table-binding-ops) (ensure-table-op-expanders) ;; clear gsyms (clrgsym 'tabletrans) ;; establish *proj->tab->lfields*: (when (not (gethash (project) *proj->tab->lfields*)) (setf (gethash (project) *proj->tab->lfields*) (make-hash-table :test 'equal))) ;; save lfield definitions (save-lfields) (let* ((graph (if *copy-target-table-p* (copy-target-table target-table) target-table)) ;; chained reduction and ltab chain edge maps (chained-edge-map (chained-edge-map graph :reduction-test-fn #'table-reduction? :reduction-source-fn #'table-reduction-source)) ;; Complete dependency map (depmap (depmap graph)) ;; Chain maps: (chainmap (chainmap graph)) (lchainmap (ltab-chainmap graph chainmap :ltab-test-fn #'ltab?)) ;; Removed source depmaps (remsrc-depmap (removed-source-depmap depmap chainmap)) (remsrc-dep< (removed-source-dep< remsrc-depmap)) ;; (remsrc-depsorted-ids (depsort-graph graph remsrc-dep<)) (remsrc-depsorted-ids (topological-sort (invert-edge-map remsrc-depmap))) ;; special dep< which only adds ltabs sources as dependencies ;; when used somewhere other than as the source additionally. (remltab-depmap (removed-ltab-source-depmap depmap lchainmap)) (remltab-dep< (removed-ltab-source-dep< remltab-depmap)) ;; (remltab-depsorted-ids (depsort-graph graph remltab-dep<)) (remltab-depsorted-ids (topological-sort (invert-edge-map remltab-depmap))) ;; result (result-graph (copy-target-table target-table)) ;; list of source targets already processed (processed-srcs nil) ;; list of reduction targets already processed: (processed-reds nil)) (labels ((trans () (let ((srcs ;; not sure if subtracting processed-srcs is really ;; necessary, but I'm leaving it in until further ;; testing confirms it's unnecessary (set-difference (ultimate-source-tables graph :ignore processed-srcs) processed-srcs))) (when srcs (dolist (src srcs) (push src processed-srcs) (let ((ltabs (list->set (alexandria:flatten (mapcar #'butlast (mapcar #'rest (ltab-chains graph chained-edge-map src :ltab-test-fn #'ltab? :dotab-test-fn #'dotab?)))))) ) (setf processed-srcs (list->set (append processed-srcs ltabs))) ) (let* (;; reductions which must be computed via a ;; pass over src (nec-reds (remove-if (lambda (k) (target-stat (gethash k graph))) (remove-if (lambda (k) (member k processed-reds :test #'equal)) (necessary-pass-reductions graph chained-edge-map src :dotab-test-fn #'dotab? :ltab-test-fn #'ltab? :reduction-test-fn #'table-reduction? :reduction-source-fn #'table-reduction-source)))) ;; necessary passes: (nec-passes (remove nil (mapcar (lambda (pass) (remove-if (lambda (p) (ltab? (target-expr (gethash p graph)))) pass)) (mapcar (lambda (pass) (remove-if-not (lambda (p) (member p nec-reds :test #'equal)) pass)) (group-ids-by-pass chained-edge-map src remltab-depsorted-ids remltab-dep< :test (lambda (i) (not (or (not (member i nec-reds :test #'equal)) (ltab? (target-expr (gethash i graph))) (target-stat (gethash i graph)))))))))) ;; passes relative to ultimate source: (ult-passes (remove nil (mapcar (lambda (pass) (remove-if (lambda (p) (target-stat (gethash p graph))) pass)) (mapcar (lambda (pass) (remove-if (lambda (p) (ltab? (target-expr (gethash p graph)))) pass)) (mapcar (lambda (pass) (remove-if (lambda (p) (member p processed-reds :test #'equal)) pass)) (group-ids-by-pass ;; must remove logical tables and previously ;; processed reduction targets: chained-edge-map src remsrc-depsorted-ids remsrc-dep< :test (lambda (i) (not (or (member i processed-reds :test #'equal) (ltab? (target-expr (gethash i graph))) (target-stat (gethash i graph))))))))))) ;; collapsible reductions of src: (collapsible-passes (mapcar (lambda (x y) y) nec-passes ult-passes))) (dolist (pass collapsible-passes) (dolist (p pass) (push p processed-reds)) (let ((id (gsym 'tabletrans))) (setf (gethash id result-graph) (make-target id (make-pass-target-expr target-table src pass))) (set-pass-result-targets! result-graph id pass))))) ;; process next sources: (trans))))) (trans)) ;; unmodified results are already present, so return result-graph result-graph)) ;; BUGGY VERSION ;; ;; This version attempts to recurse through the lfield maps, but this ;; is completely unnecessary once the table-pass expression is ;; available. All that needs to be done is to find the (res ...) ;; dependencies in the table-pass body, and add any additional ;; dependencies to the deps list. ;; ;; (defun lfield-dependencies (graph id) ;; "Returns full list of dependencies caused by lfields" ;; (labels ((lfield-deps (id) ;; ;; Returns the res dependencies directly imposed by ;; ;; reference to an lfield from a table reduction ;; (when (and (not (target-stat (gethash id graph))) ;; (table-reduction? ;; (target-expr (gethash id graph)))) ;; (let* ((tar (gethash id graph)) ;; (expr (target-expr tar)) ;; (src (unres (table-reduction-source expr))) ;; (lfields ;; (gethash src ;; (gethash (project) ;; *proj->tab->lfields*))) ;; (lfield-map ;; (let ((result (make-hash-table :test 'eq))) ;; (loop ;; for lfield in lfields ;; do (setf (gethash (first lfield) result) ;; `(progn ,@(rest lfield)))) ;; result))) ;; (labels ((rec (lfield) ;; ;; finds all lfields referred to by lfield ;; ;; expression including the lfield itself ;; (let* ((expr (gethash lfield lfield-map)) ;; (referred ;; (remove-if-not ;; (lambda (field) ;; (gethash field lfield-map)) ;; (cl-ana.makeres::find-dependencies ;; expr ;; 'field)))) ;; (when referred ;; (append referred ;; (mapcan #'rec referred)))))) ;; (let* ((lfield-deps ;; (list->set ;; (mapcan ;; #'rec ;; (remove-if-not ;; (lambda (field) ;; (gethash field lfield-map)) ;; (cl-ana.makeres::find-dependencies ;; expr ;; 'field))) ;; #'eq)) ;; (lfield-dep-merged-expr ;; `(progn ;; ,@(loop ;; for ld in lfield-deps ;; collecting (gethash ld lfield-map)))) ;; (lfield-res-deps ;; (cl-ana.makeres::find-dependencies ;; lfield-dep-merged-expr ;; 'res))) ;; (remove-if ;; (lambda (i) ;; (target-stat (gethash i graph))) ;; (list->set ;; lfield-res-deps ;; #'equal))))))) ;; (lfdrec (id) ;; ;; Finds lfield dependencies to an id both directly and ;; ;; from any possible dependency path ;; (when (not (target-stat (gethash id graph))) ;; (let ((imm-deps ;; (append (lfield-deps id) ;; (target-deps (gethash id graph))))) ;; (list->set ;; (append imm-deps ;; (mapcan #'lfdrec ;; imm-deps)) ;; #'equal))))) ;; (lfdrec id))) ;;; Propogation: ;; Propogation strategy: Create new targets for each lfield and set ;; its status based on whether it has been changed. (defpropogator #'tabletrans (lambda (graph) (let ((graph (copy-target-table graph)) (changed-lfields (changed-lfields)) (tab-lfield->gsym (make-hash-table :test 'equal))) ;; Create tab-lfield->gsym map (loop for tab being the hash-keys in (gethash (project) *proj->tab->lfields*) for lfields being the hash-values in (gethash (project) *proj->tab->lfields*) do (loop for lf in lfields do (setf (gethash (list tab (car lf)) tab-lfield->gsym) (gsym 'tabletrans)))) ;; Create lfield targets (loop for tab-lfield being the hash-keys in tab-lfield->gsym for gsym being the hash-values in tab-lfield->gsym do (destructuring-bind (tab lfield) tab-lfield (let* ((lfields (gethash tab (gethash (project) *proj->tab->lfields*))) (lfield-map (let ((result (make-hash-table :test 'eq))) (loop for lfield in lfields do (setf (gethash (first lfield) result) `(progn ,@(rest lfield)))) result))) (labels ((lfield-deps (lfield) ;; finds all lfields referred to by lfield ;; expression including the lfield itself (let* ((expr (gethash lfield lfield-map)) (referred (remove-if-not (lambda (field) (gethash field lfield-map)) (cl-ana.makeres::find-dependencies expr 'field)))) (when referred (append referred (mapcan #'lfield-deps referred)))))) (setf (gethash gsym graph) (make-target gsym `(progn ',lfield ,@(loop for lfdep in (lfield-deps lfield) collecting `(res ,(gethash (list tab lfdep) tab-lfield->gsym)))) :stat ;; (not (not x)) is an easy way of only getting ;; T or NIL from x (not (not (not (member lfield (gethash tab changed-lfields) :test #'eq)))))))))) (loop for id being the hash-keys in graph for tar being the hash-values in graph when (table-reduction? (target-expr tar)) do (let* ((expr (target-expr tar)) (src (unres (table-reduction-source expr))) (lfields (gethash src (gethash (project) *proj->tab->lfields*))) (lfield-map (let ((result (make-hash-table :test 'eq))) (loop for lfield in lfields do (setf (gethash (first lfield) result) `(progn ,@(rest lfield)))) result))) (labels ((lfield-deps (lfield) ;; finds all lfields referred to by lfield ;; expression including the lfield itself (let* ((expr (gethash lfield lfield-map)) (referred (remove-if-not (lambda (field) (gethash field lfield-map)) (cl-ana.makeres::find-dependencies expr 'field)))) (when referred (append referred (mapcan (lambda (x) (lfield-deps x)) referred)))))) (let* ((lfield-deps (list->set (mapcan (lambda (x) (cons x (lfield-deps x))) (remove-if-not (lambda (field) (gethash field lfield-map)) (cl-ana.makeres::find-dependencies expr 'field))) #'eq)) (lfield-dep-merged-expr `(progn ,@(loop for ld in lfield-deps collecting (gethash ld lfield-map)))) (lfield-res-deps (append (mapcar (lambda (lf) (gethash (list src lf) tab-lfield->gsym)) lfield-deps) (cl-ana.makeres::find-dependencies lfield-dep-merged-expr 'res)))) (symbol-macrolet ((deps (target-deps tar))) (setf deps (list->set (append deps lfield-res-deps) #'equal))))))) graph))) ;; Logging lfields (defun lfield-log-path () (merge-pathnames "makeres-table/lfield-log" (current-path))) (defun save-lfields () "Saves the current lfield definitions for the project to disk" (let* ((path (lfield-log-path)) (tab->lfields (gethash (project) *proj->tab->lfields*)) (*print-pretty* nil)) (ensure-directories-exist path) (with-open-file (file path :direction :output :if-exists :supersede :if-does-not-exist :create) (loop for tab being the hash-keys in tab->lfields for lfields being the hash-values in tab->lfields do (format file "~s ~s~%" tab lfields))))) (defun load-lfields () "Returns hash-table mapping table to lfield definitions stored on disk" (let* ((path (lfield-log-path)) (result-alist nil)) (with-open-file (file path :direction :input :if-does-not-exist nil) (when file (do ((line (read-line file nil nil) (read-line file nil nil))) ((null line)) (with-input-from-string (s line) (push (cons (read s) (read s)) result-alist)))) (cl-ana.map:map->hash-table result-alist 'equal)))) (defun changed-lfields () "Returns lfields which are different from those logged. Result is a hash-table mapping from table to a list of changed lfield symbols." (when (not (gethash (project) *proj->tab->lfields*)) (setf (gethash (project) *proj->tab->lfields*) (make-hash-table :test 'equal))) (let* ((tab->lfields (gethash (project) *proj->tab->lfields*)) (tab->logged-lfields (load-lfields)) (result nil)) (loop for tab being the hash-keys in tab->lfields do (let* ((logged (gethash tab tab->logged-lfields)) (logged-ht (cl-ana.map:map->hash-table logged 'equal)) (current (gethash tab tab->lfields)) (current-ht (cl-ana.map:map->hash-table current 'equal)) (res nil)) (loop for lf being the hash-keys in current-ht do (let ((defcurrent (gethash lf current-ht)) (deflogged (gethash lf logged-ht))) (when (not (equal defcurrent deflogged)) (push lf res)))) (when res (push (cons tab (nreverse res)) result)))) (cl-ana.map:map->hash-table result 'equal)))
75,441
Common Lisp
.lisp
1,661
26.02348
101
0.418272
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
8713e3cbc6a838f708fea4f475ed028f8737b1f26a4503ef60dc794a8f7b16f8
1,676
[ -1 ]
1,677
smart-gensym.lisp
ghollisjr_cl-ana/makeres-table/smart-gensym.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.makeres-table) ;;;; Defines gensym tables which allows the reuse of gensyms (eval-when (:compile-toplevel :load-toplevel :execute) (defvar *gsym-tables* (make-hash-table :test 'equal) "Map from id to gsym table") ;; structure for storing gsym table info (defstruct gsym-table symbols available-symbols) (defun gsym (id) (when (not (gethash id *gsym-tables*)) (setf (gethash id *gsym-tables*) (make-gsym-table :symbols (list (gensym)) :available-symbols nil))) (symbol-macrolet ((gsym-tab (gethash id *gsym-tables*)) (available (gsym-table-available-symbols gsym-tab)) (all (gsym-table-symbols gsym-tab))) (if available (pop available) (let ((gsym (gensym))) (push gsym all) gsym)))) (defun clrgsym (id) "Frees gsyms for reuse" (symbol-macrolet ((gsym-tab (gethash id *gsym-tables*))) (when gsym-tab (setf (gsym-table-available-symbols gsym-tab) (copy-list (gsym-table-symbols gsym-tab))))) nil))
2,000
Common Lisp
.lisp
52
33.307692
70
0.654143
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
f316f91aa904b689d1a97c991a814607c911d76564621e225b6ea49e0246fce7
1,677
[ -1 ]
1,678
openers.lisp
ghollisjr_cl-ana/makeres-table/openers.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.makeres-table) ;;;; This file defines openers for use with tab for various tables ;;;; provided by cl-ana. ;;;; ;;;; Openers are functions which return closures to automate the ;;;; reading and writing of tables. ;;;; ;;;; The function returned by an opener should accept a single keyword ;;;; argument used as follows: ;;;; ;;;; :read requests that a table object be returned ready for reading ;;;; whatever was last written to the table object owned by the ;;;; opener, appropriately storing/closing any resources necessary. ;;;; ;;;; :write requests that a table object be returned ready for ;;;; writing, erasing whatever results were previously in the table. ;; hdf-table & hdf-table-chain: (defun hdf-opener (path fields-specs &key buffer-size (group "/table")) "Returns a closure which, when given a single keyword argument, returns an hdf-table ready for reading/writing, automatically managing file access and calling table-close when necessary." (let ((file nil) (table nil)) (lambda (op) (case op (:read (when (and table (table-open-p table)) (table-close table)) (when file (close-hdf-file file)) (setf file nil) (setf table (wrap-for-reuse (open-hdf-table-chain (list path) group) `(hdf-opener ',path ',fields-specs :buffer-size ',buffer-size :group ',group))) table) (:write (when (and table (table-open-p table)) (table-close table)) (when file (close-hdf-file file)) (setf file (open-hdf-file path :direction :output :if-exists :supersede :if-does-not-exist :create)) (setf table (apply #'create-hdf-table file group fields-specs (when buffer-size (list :buffer-size buffer-size)))) table))))) (defun hdf-chain-opener (paths &key (group "/table")) "Returns a closure which returns an hdf-table-chain for reading and nil for writing." (let ((table nil)) (lambda (op) (case op (:read (when (and table (table-open-p table)) (table-close table)) (setf table (wrap-for-reuse (open-hdf-table-chain paths group) `(hdf-chain-opener ',paths :group ',group))) table) (:write nil))))) ;; PAW ntuple: (defun ntuple-opener (path fields-specs) "Returns a closure which, when given a single keyword argument, returns an ntuple-table ready for reading/writing, automatically managing file access and calling table-close when necessary." (let ((table nil)) (lambda (op) (case op (:read (when (and table (table-open-p table)) (table-close table)) (setf table (wrap-for-reuse (open-ntuple-table path fields-specs) `(ntuple-opener ',path ',fields-specs))) table) (:write (when (and table (table-open-p table)) (table-close table)) (setf table (create-ntuple-table path fields-specs)) table))))) ;; CSV: (defun csv-opener (path &key field-names read-from-string (delimeter #\,)) "Returns a closure which, when given a single keyword argument, returns an ntuple-table ready for reading/writing, automatically managing file access and calling table-close when necessary." (let ((table nil)) (lambda (op) (case op (:read (when (and table (table-open-p table)) (table-close table)) (setf table (wrap-for-reuse (open-csv-table path :read-from-string read-from-string :delimeter delimeter) `(csv-opener ',path :field-names ',field-names :read-from-string ',read-from-string :delimeter ',delimeter))) table) (:write (when (and table (table-open-p table)) (table-close table)) (setf table (create-csv-table path field-names delimeter)) table))))) ;; plist-table: (defun plist-opener (plists) (let* ((plists plists) (opener-form `(plist-opener ',plists)) (table (wrap-for-reuse (open-plist-table plists) opener-form)) (field-names (mapcar #'first (group (first plists) 2)))) (lambda (op) (case op (:read (when (and table (table-open-p table)) (table-close table)) (setf plists (coerce (plist-table-plists (if (typep table 'reusable-table) (internal-table table) table)) 'list)) (setf table (wrap-for-reuse (open-plist-table plists) opener-form)) table) (:write (when (and table (table-open-p table)) (table-close table)) (setf table (create-plist-table field-names)) table)))))
6,732
Common Lisp
.lisp
189
24.671958
70
0.535272
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
4af11f91bc0d87f6ba500de9912f3f29707a80a50438c04edf776673a9bbb19c
1,678
[ -1 ]
1,679
merge-test.lisp
ghollisjr_cl-ana/makeres-table/tests/merge-test.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; This file demonstrates a bug when you ;;;; ;;;; 1. Run the project ;;;; 2. Restart Lisp ;;;; 3. Load the project ;;;; 4. (makeres) ;;;; ;;;; There seems to be a problem in pass merging. (require 'cl-ana) (in-package :cl-ana) (defproject merge-test "/home/ghollisjr/test/merge-test" (list #'macrotrans #'tabletrans #'progresstrans) (fixed-cache 1)) (setf *print-progress* nil) (defres src (srctab (plist-opener '((:x 1 :y 2) (:x 2 :y 3))))) (defres (src sum) (dotab (res src) ((sum 0)) sum (incf sum (+ (field x) (field y))))) ;;(logres-ignore (src sum)) (defres (src sum2) (expt (res (src sum)) 2)) ;;(logres-ignore (src sum2)) (defres proc (tab (res src) () (csv-opener (work-path "proc.csv") :field-names (list "X" "Y" "Z") :read-from-string t) (push-fields (x (field x)) (y (field y)) (z (/ (field x) (field y)))))) (defres (proc sum) (dotab (res proc) ((sum 0)) sum (incf sum (+ (field x) (field y) (field z))))) ;;(logres-ignore (proc sum)) (defres (proc sum2) (expt (res (proc sum)) 2)) ;;(logres-ignore (proc sum2)) (defres ult (tab (res proc) () (csv-opener (work-path "ult.csv") :field-names (list "X") :read-from-string t) (when (res (src sum)) (push-fields (x (field x)))))) (defres (ult sum) (dotab (res ult) ((sum 0)) sum (incf sum (field x)))) ;;(logres-ignore (ult sum))
2,529
Common Lisp
.lisp
87
23.804598
70
0.578839
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
81fe21c06b0bf09ec5ea7a94b4f48afa3183e25607e9ce7c14f67746c1c4ca25
1,679
[ -1 ]
1,680
lfield-logging-test.lisp
ghollisjr_cl-ana/makeres-table/tests/lfield-logging-test.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (require 'cl-ana) (in-package cl-ana) (defproject lfield-logging-test "/home/ghollisjr/test/lfield-logging-test/" (list #'macrotrans #'tabletrans #'progresstrans) (fixed-cache 5)) (defres src (srctab (plist-opener (list (list :x 1) (list :x 2) (list :x 3))))) (deflfields src ((y (* (field x) 2)) (z (/ (field y) (sqrt 2))) (w (sqrt (field z))))) (defres xmean (dotab (res src) ((sum 0) (count 0)) (/ sum count) (incf sum (field x)) (incf count))) (defres skim (ltab (res src) () (when (< (field x) (field w)) (push-fields)))) (defres (skim xmean) (dotab (res skim) ((sum 0) (count 0)) (/ sum count) (incf sum (field x)) (incf count)))
1,700
Common Lisp
.lisp
55
26.327273
70
0.61515
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
fafe2e41c18eb39461219ca2dce7b9bf7df7053728c8d79b45d9b1ffbf0599e5
1,680
[ -1 ]
1,681
simple-test.lisp
ghollisjr_cl-ana/makeres-table/tests/simple-test.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (require 'cl-ana) (in-package cl-ana) (in-project simple-test) (settrans (list #'tabletrans) :op :set) (defres source (wrap-for-reuse (open-plist-table (loop for i below 10000000 collecting (list :x i))))) (deflfields source ((y (* 2 (field x))))) (defres sum (dotab (res source) ((sum (progn (format t "starting sum~%") 0))) sum (incf sum (field x)))) (defres count (dotab (res source) ((count (progn (format t "starting count~%") 0))) count (incf count))) (defres mean (format t "starting mean~%") (/ (res sum) (res count))) (defres filtered (ltab (res source) () (when (< (field x) (res mean)) (push-fields (x (field x)))))) ;; works up to this point, breaks after the following: (defres (filtered sum) (dotab (res filtered) ((sum (progn (format t "starting filtered sum~%") 0))) sum (incf sum (field x)))) (defres (filtered count) (dotab (res filtered) ((count (progn (format t "starting filtered count~%") 0))) count (incf count))) (defres (filtered mean) (format t "starting filtered mean~%") (/ (res (filtered sum)) (res (filtered count))))
2,190
Common Lisp
.lisp
74
24.891892
70
0.620362
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
3e2f74f0202ff46e9166d8641624d878184fdfd330b56b2cd2cde6f20c16ff4a
1,681
[ -1 ]
1,682
csv-test.lisp
ghollisjr_cl-ana/makeres-table/tests/csv-test.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (require 'cl-ana) (in-package :cl-ana) ;; Basic tests (defun csv-test () (let* ((opener (csv-opener "/home/ghollisjr/test.csv" :field-names (list "a") :read-from-string t)) tab) (setf tab (funcall opener :write)) (loop for i below 5 do (table-push-fields tab (|a| i))) (setf tab (funcall opener :read)) tab)) ;; Project test (defproject csv-test "/home/ghollisjr/test/makeres-table/csv-test" (list #'macrotrans #'branchtrans #'tabletrans #'progresstrans) (fixed-cache 5)) (setf *print-progress* nil) (defres bootstrap (let ((table (create-csv-table (work-path "src.csv") (list "X" "Y" "Z")))) (loop for i below 100 do (let* ((x (->double-float i)) (y (sqrt x)) (z (sqrt y))) (table-push-fields table (x x) (y y) (z z)))) (table-close table))) (defres src (srctab (csv-opener (work-path "src.csv") :field-names (list "X" "Y" "Z") :read-from-string t) (res bootstrap))) (defres proc (tab (res src) () (csv-opener (work-path "proc.csv") :field-names (list "X" "Y" "Z" "W" "Q") :read-from-string t) (when (< (field x) 50) (push-fields (x (field x)) (y (field y)) (z (field z)) (w (+ (field x) (field y) (field z))) (q (* (field x) (field y) (field z))))))) (defres subset (tab (res proc) () (csv-opener (work-path "subset.csv") :field-names (list "X" "Y") :read-from-string t) (when (< (field x) 4) (push-fields (x (field x)) (y (field y)))))) (defres subset-data (dotab (res subset) ((data nil)) (nreverse data) (push (list :x (field x) :y (field y)) data)))
2,921
Common Lisp
.lisp
94
23.712766
70
0.543162
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
1b06161c4bd7f163d09c106abf4632ee46db47dc1d548f3a0c535e77df74a985
1,682
[ -1 ]
1,683
tabletrans-test.lisp
ghollisjr_cl-ana/makeres-table/tests/tabletrans-test.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (require 'cl-ana) (in-package :cl-ana) (defproject tabletrans-test "/home/ghollisjr/test/makeres-table/tabletrans-test" (list #'macrotrans #'tabletrans #'progresstrans) (fixed-cache 5)) ;; (setf *print-progress* t) (defres source (srctab (plist-opener '((:x 1) (:x 2) (:x 3))))) (defres filtered (ltab (res source) () (when (< (field x) 4) ;; you only have to add new fields, all source ;; fields not shadowed are still available: (push-fields ;; new field y, x is still accessible, unshadowed (y (* 2 (field x))))))) (defres (filtered sum) (dotab (res filtered) ((sum 0)) sum (incf sum (field y)))) (defres filtered2 (ltab (res source) () (when (< (field x) 5) (push-fields ;; shadow field x: (x (sqrt (field x))) ;; new field y: (y (field x)))))) (defres canon (tab (res filtered) () (hdf-opener "/home/ghollisjr/canon.h5" '(("X" . :int) ("Y" . :float) ("Z" . :float))) (push-fields (x (field x)) (y (sqrt (field y))) (z (float (expt (field y) 2)))))) (defres (canon (sum x)) (dotab (res canon) ((sum 0)) sum (incf sum (field x)))) (defres (canon count) (dotab (res canon) ((count 0)) count (incf count))) (defres (canon (mean x)) (/ (res (canon (sum x))) (res (canon count)))) (defres (filter canon) (ltab (res canon) () (when (< (field x) (res (canon (sum x)))) (push-fields (x (field x)))))) (defres (filter source) (ltab (res source) () (when (< (field x) (res (canon (sum x)))) (push-fields (x (field x)))))) (defres other (tab (res filtered2) () (hdf-opener "/home/ghollisjr/other.h5" '(("X" . :int))) (push-fields (x (field y))))) (defres (canon (variance x)) (dotab (res canon) ((sum 0) (count 0)) (/ sum (- count 1)) (incf sum (expt (- (field x) (res (canon (mean x)))) 2)))) ;; Pass deconstruction should be: ;; ;; source: ;; ;; 1. canon, other, (canon count), (canon (sum x)) ;; ;; canon: ;; ;; 1. (canon (variance x))
3,288
Common Lisp
.lisp
119
21.689076
70
0.54981
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
69fea830ef97c1f55e7884a07aff186d39cd0f66ef3492487ef028f388761d95
1,683
[ -1 ]
1,684
push-fields.lisp
ghollisjr_cl-ana/makeres-table/tests/push-fields.lisp
(require 'cl-ana) (in-package :cl-ana) (defproject push-fields "/home/ghollisjr/test/makeres-table/push-fields" (list #'macrotrans #'tabletrans #'progresstrans) (fixed-cache 5)) (setf *print-pretty* 10) (with-open-hdf-file (file (work-path "src.h5") :direction :output :if-does-not-exist :create :if-exists :supersede) (let ((result (create-hdf-table file "/table" (list (cons "X" :double) (cons "Y" :double))))) (loop for i below 100 for j downfrom 99 do (table-push-fields result (x (->double-float i)) (y (->double-float j)))) (table-close result) t)) (defres (src) (srctab (hdf-chain-opener (list (work-path "src.h5")) :group "/table"))) (defres (src scrambled) (tab (res (src)) () (hdf-opener (work-path "src-scrambled.h5") (list (cons "X" :double) (cons "Y" :double))) (if (< (field x) 50) (push-fields (x (field x)) (y (field y))) (push-fields (x (field y)) (y (field x))))))
1,245
Common Lisp
.lisp
39
21.641026
55
0.488333
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
65e014ccc96b1c9ab2d258b45d6c4ae5ce7e3de572247227366fcd1899f904ca
1,684
[ -1 ]
1,685
lfield-dep-test.lisp
ghollisjr_cl-ana/makeres-table/tests/lfield-dep-test.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (require 'cl-ana) (in-package :cl-ana) (defproject lfield-dep-test "/home/ghollisjr/test/lfield-dep-test" (list #'macrotrans #'tabletrans #'progresstrans) (fixed-cache 5)) ;; To perform this test, redefine a and call ;; ;; (makeres-propagate!) and then ;; (makeres) ;; ;; to see if b gets recalculated (defres a 5) (defres src (srctab (plist-opener '((:x 1) (:x 2) (:x 3))))) (deflfields src ((z (+ (field x) (res a))))) (defres b (dotab (res src) ((z-sum 0)) z-sum (incf z-sum (field z))))
1,462
Common Lisp
.lisp
46
28.521739
70
0.65625
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
aa7a9f4afe82e2f9aeb463885e122d818721145cb07e67740021d1f4da138884
1,685
[ -1 ]
1,686
lfields.lisp
ghollisjr_cl-ana/makeres-table/tests/lfields.lisp
(require 'cl-ana) (in-package :cl-ana) (defproject lfields "/home/ghollisjr/test/makeres-table/lfields/" (list #'macrotrans #'tabletrans) (fixed-cache 5)) (setf *print-progress* 10) (defres (bootstrap src) (with-open-hdf-file (file (work-path "src.h5") :direction :output :if-does-not-exist :create :if-exists :supersede) (let ((tab (create-hdf-table file "/table" (list (cons "X" :double) (cons "Y" (list :array :double 2)))))) (loop for i from 1 to 100 do (let* ((x (->double-float i)) (y (vector (log x) (exp x)))) (table-push-fields tab (x x) (y y)))) (table-close tab)))) (defres (src) (srctab (hdf-chain-opener (list (work-path "src.h5"))) (res (bootstrap src)))) (deflfields (src) ((ysum (sum (field y))) (sum (+ (field x) (field ysum))) (z (sqrt (field sum))))) (defres (proc) (tab (res (src)) () (hdf-opener (work-path "proc.h5") (list (cons "X" :double) (cons "Y" (list :array :double 2)) (cons "Z" :double))) (push-fields (x (field x)) (y (field y)) (z (field z))))) (deflfields (proc) ((ysum (sum (field y))) (sum (+ (field x) (field ysum))))) (defres (filtered) (ltab (res (proc)) () (when (< (field x) 50) (push-fields (x (field x)) (y (field y)) (sum (field sum)) (z (field z)))))) (defres (filtered total-sum) (dotab (res (filtered)) ((sum 0)) sum (incf sum (field sum)))) (load-project) (makeres)
1,948
Common Lisp
.lisp
68
18.323529
72
0.441948
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
29886ee6f7dfe9e817aacb8c097528b6cdf70a0643e8d6d900483954622eab59
1,686
[ -1 ]
1,687
lfields-test.lisp
ghollisjr_cl-ana/makeres-table/tests/lfields-test.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (require 'cl-ana) (in-package :cl-ana) (defproject lfields-test "/home/ghollisjr/lfields-test" (list #'macrotrans #'tabletrans) (fixed-cache 20)) (defres src (wrap-for-reuse (open-plist-table (list (list :|x| 1) (list :|x| 2) (list :|x| 3))))) (logres-ignore src) (deflfields src ((|y| (+ (field |x|) 1)))) (defres tab (tab (res src) () (hdf-opener (work-path "lfields-test.h5") (list (cons "x" :int) (cons "y" :int))) (print (field |x|)) (print (field |y|)) (push-fields (|x| (field |x|)) (|y| (field |y|))))) (deflfields tab ((|z| (+ (field |x|) (field |y|))))) (defres (mean tab z) (dotab (res tab) ((sum 0) (count 0)) (/ sum count) (incf sum (field |z|)) (incf count)))
1,759
Common Lisp
.lisp
56
26.535714
70
0.596222
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
9e3a1a7f7ba7ec1b3517f9f0c31eda5e50e330925b967aabe49dca68a8c56632
1,687
[ -1 ]
1,688
resmacrotest.lisp
ghollisjr_cl-ana/makeres-table/tests/resmacrotest.lisp
(require 'cl-ana) (in-package :cl-ana) ;; Project settings. Change the path to something that works for you (defproject resmacrotest "/home/ghollisjr/test/makeres-table/resmacrotest/" (list #'macrotrans #'tabletrans #'progresstrans) (fixed-cache 5)) (setf *print-progress* 100) ;; Source data (defres npoints 1000) (defres bootstrap (loop for i below (res npoints) collecting (let* ((x (shaped-random #'normal-cdf-inv)) (y (expt x 2))) (list :x x :y y)))) (defres data (srctab (plist-opener (res bootstrap)))) ;; Test the nrows, mean, and standard deviation res-macros (defres (data nrows) (dotab-nrows (res data))) (defres (bootstrap nrows) (length (res bootstrap))) (defres (data x mean) (dotab-mean (res data) (field x))) (defres (bootstrap x mean) (mean (mapcar (lambda (x) (getf x :x)) (res bootstrap)))) (defres (data x standard-deviation) (dotab-standard-deviation (res data) (field x))) (defres (bootstrap x standard-deviation) (standard-deviation (mapcar (lambda (x) (getf x :x)) (res bootstrap)))) ;; Try something weird: (defres (data (* x y) standard-deviation) (dotab-standard-deviation (res data) (* (field x) (field y)))) ;; Should be equal to: (defres (data (expt x 3) standard-deviation) (dotab-standard-deviation (res data) (expt (field x) 3)))
1,581
Common Lisp
.lisp
49
24.77551
68
0.586614
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
fd40811244d6ceae16c3c156d0c313e91a3f87dfebfdad003281a324a447bbc9
1,688
[ -1 ]
1,689
lfields-dep-test.lisp
ghollisjr_cl-ana/makeres-table/tests/lfields-dep-test.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2016 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (require 'cl-ana) (in-package :cl-ana) ;;;; This project should not run properly, since there is a res form ;;;; in an lfield. This functionality used to be supported, but was ;;;; very difficult to implement accurately and efficiently. Maybe ;;;; someone will add it back in the future, but there is no loss in ;;;; functionality, since creating a logical table and loading a ;;;; result as an init is a practical equivalent. (defproject lfields-dep-test ;; change this to something that makes sense "/home/ghollisjr/lfields-dep-test" (list #'progresstrans #'macrotrans #'tabletrans) (fixed-cache 20)) (defres src (wrap-for-reuse (open-plist-table (list (list :|x| 1) (list :|x| 2) (list :|x| 3))))) (defres (mean src x) (dotab (res src) ((sum 0) (count 0)) (/ sum count) (incf sum (field |x|)) (incf count))) ;; New table to support logical fields based on previous calculations (defres proc (ltab (res src) () (push-fields))) (deflfields proc ((delta-x (- (field |x|) (res (mean src x)))))) ;; should be 0 (defres (mean proc delta-x) (dotab (res proc) ((sum 0) (count 0)) (/ sum count) (incf sum (field delta-x)) (incf count)))
2,159
Common Lisp
.lisp
60
32.25
70
0.661406
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
e3090e2c8dbfe50d6ca00647b6de049be744c1759e35ba644be9dd05009dfb5c
1,689
[ -1 ]
1,690
test.lisp
ghollisjr_cl-ana/makeres-table/tests/test.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (require 'cl-ana) (in-package :cl-ana) ;; NOTE: tabletrans is an example of a graph transformation which ;; needs to have makeres run even when the only thing updated is the ;; input parameters. ;; Demo of tabletrans (in-project tabletrans-simple-test) (settrans (list #'macrotrans #'tabletrans)) (defpars ((nrows 5))) ;; source table (defres table (wrap-for-reuse (open-plist-table (mapcar (lambda (x) (list :x x)) (loop for i below (par nrows) collecting i))))) (deflfields table ((y (* 2 (field x))))) (defres test (dotab (res table) () nil (let ((z (sqrt (field x)))) (print (field z))))) ;;(print 'test))) ;; average: (defres mean (dotab (res table) ((sum 0) (count 0)) (progn (print 'return-mean) (the float (float (/ sum count)))) (print 'loop-mean) (incf sum (field x)) (incf count))) (defres ymean (dotab (res table) ((sum 0) (count 0)) (/ sum count) (print 'ymean) (incf sum (field y)) (incf count))) (defres max (dotab (res table) ((max nil)) max (if (not max) (setf max (field x)) (when (> (field x) max) (setf max (field x)))))) (defres min (dotab (res table) ((min nil)) min (if (not min) (setf min (field x)) (when (< (field x) min) (setf min (field x)))))) (defres variance (dotab (res table) ((sum-squares 0) (count 0)) ; safe since variance happens in second pass (the float (float (/ sum-squares (1- count)))) (incf sum-squares (expt (- (field x) (res mean)) 2)) (incf count))) (defres sigma (sqrt (res variance)))
2,701
Common Lisp
.lisp
97
22.731959
70
0.596986
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
e1351eaeb705b1cb2e500bbeef3c575220ed9d239e97ccce1452377828d3fb90
1,690
[ -1 ]
1,691
package.lisp
ghollisjr_cl-ana/generic-math/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (defpackage #:cl-ana.generic-math (:nicknames :cl-ana.gmath) (:use :cl :cl-ana.package-utils :cl-ana.list-utils) (:shadow :incf :decf :+ :- :* :/ :sqrt :expt :exp :log :sin :cos :tan :sinh :cosh :tanh) (:export :*gmath-generic-map* :use-gmath :defmath :defmethod-commutative :incf :decf :+ :sum :product :add :- :sub :unary-sub :* :mult :/ :protected-/ :div :unary-div :protected-div :protected-unary-div :sqrt :expt :exp :log :sin :cos :tan :sec :csc :cot :sinh :cosh :tanh :sech :csch :coth))
1,625
Common Lisp
.lisp
78
16.474359
70
0.602846
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
7c5ad9684b5912693445212d9e040ae2e88781d8e780b218cdc69e31bc9f986f
1,691
[ -1 ]
1,692
generic-math.lisp
ghollisjr_cl-ana/generic-math/generic-math.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; generic-math.lisp ;;;; IMPORTANT NOTES ;;;; ;;;; To use the symbols from generic-math in your program, just place ;;;; (cl-ana.gmath:use-gmath <package-designator>) above your code to ;;;; shadowing-import gmath functions into the package you specify. ;;;; It's the best way I've come up with so far for easily replacing ;;;; the cl functions like +, -, .... My usual routine is to place it ;;;; at the tail end of my package files since it has to do with the ;;;; package. ;;;; ;;;; Note that you will have to use cl:... from this point on if you ;;;; want access to the shadowed symbols however. ;;;; ;;;; Also: Since common lisp defines the basic number class, but ;;;; doesn't give us a way to extend it: If you want to handle generic ;;;; scalar types in your program, one approach is to just define a ;;;; method for your function which is unspecialized on scalar type ;;;; arguments. As long as the most basic operations are ultimately ;;;; scalar, this should work. ;;;; TODO: ;;;; * Implement the inverse trig functions (in-package :cl-ana.generic-math) (defun use-gmath (package) "shadowing-imports all the exported symbols from gmath into the current package" (shadowing-use-package :cl-ana.generic-math package)) (defvar *gmath-generic-map* (make-hash-table :test 'equal) "Hash table mapping generic function symbols to the argument specification for the function.") ;; Macro for defining new gmath generics (defmacro defmath (fname (&rest args) &body body) "Defines a generic function for use in generic-math. Necessary to allow for programmatically generated methods of certain mathematical types. Can use body just like with defgeneric to specify methods etc." `(progn (setf (gethash ',fname *gmath-generic-map*) ',args) (defgeneric ,fname ,args ,@body))) ;; for all those cases where you want a commutative operator (defmacro defmethod-commutative (method-name (left-arg right-arg) &body body) `(progn (defmethod ,method-name (,left-arg ,right-arg) ,@body) (defmethod ,method-name (,right-arg ,left-arg) ,@body))) ;; this macro replaces the oft repeated code for creating a function ;; which calls the generic binary operator to reduce an arbitrary ;; number of arguments. (defmacro reduce-defun (fname reduce-fname) `(defun ,fname (&rest xs) (reduce #',reduce-fname xs))) ;; To allow use of incf (since we're touching +) (defmacro incf (place &optional (delta 1)) `(setf ,place (add ,place ,delta))) ;; To allow use of decf (since we're touching -) (defmacro decf (place &optional (delta 1)) `(setf ,place (sub ,place ,delta))) (reduce-defun + add) (defun sum (xs) "Convenience function for summing a list of values (it's reducing + across them)." (reduce #'+ xs)) (defun product (xs) "Convenience function for multiplying a list of values" (reduce #'* xs)) (defmath add (x y) (:documentation "Binary addition function")) (defun - (&rest xs) (if (single xs) (unary-sub (first xs)) (reduce #'sub xs))) (defmath sub (x y) (:documentation "Binary subtraction function")) (defmath unary-sub (x) (:documentation "Unary subtraction function.")) (reduce-defun * mult) (defmath mult (x y) (:documentation "Binary multiplication function")) (defun / (&rest xs) (if (single xs) (unary-div (first xs)) (reduce #'div xs))) (defun protected-/ (&rest xs) (if (single xs) (protected-unary-div (first xs)) (reduce #'protected-div xs))) (defmath div (x y) (:documentation "Binary division function")) (defmath unary-div (x) (:documentation "Unary division function. Also known as multiplicative inversion.")) (defmath protected-div (x y &key protected-value) (:documentation "Binary division protected from division by zero; returns protected-value whenever y is zero") (:method (x y &key (protected-value 0)) (if (zerop y) protected-value (div x y)))) (defmath protected-unary-div (x &key protected-value) (:documentation "Protected unary division function. Returns protected-value whenever x is zero.") (:method (x &key (protected-value 0)) (if (zerop x) protected-value (unary-div x)))) (defmath sqrt (x) (:documentation "Square root function")) (defmath expt (x y) (:documentation "Raises x to the y power")) (defmath exp (x) (:documentation "e^x")) (defmath log (x) (:documentation "Natural logarithm function")) (defmath sin (x) (:documentation "Sine, in radians")) (defmath cos (x) (:documentation "Cosine, in radians")) (defmath tan (x) (:documentation "Tangent, in radians")) (defmath sec (x) (:documentation "Secant, in radians") (:method (x) (unary-div (cos x)))) (defmath csc (x) (:documentation "Cosecant, in radians") (:method (x) (unary-div (sin x)))) (defmath cot (x) (:documentation "Cotangent, in radians") (:method (x) (unary-div (tan x)))) (defmath sinh (x) (:documentation "Hyperbolic sine function")) (defmath cosh (x) (:documentation "Hyperbolic cosine function")) (defmath tanh (x) (:documentation "Hyperbolic tangent function")) (defmath sech (x) (:documentation "Hyperbolic secant function") (:method (x) (unary-div (cosh x)))) (defmath csch (x) (:documentation "Hyperbolic cosecant function") (:method (x) (unary-div (sinh x)))) (defmath coth (x) (:documentation "Hyperbolic cotangent function") (:method (x) (unary-div (tanh x))))
6,316
Common Lisp
.lisp
173
33.901734
77
0.707145
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
0f3d56411ac2ac888e55430da030a7ef18db7f1f966787bf3030a16ab6045bd3
1,692
[ -1 ]
1,693
number.lisp
ghollisjr_cl-ana/generic-math/number.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.generic-math) ;;;; Implements generic math functions for numbers ;;; I know I could create a macro to automate this redundant code, ;;; maybe I will at some point, but I don't want to obfuscate the code ;;; too much for the poor readers. (declaim (optimize (speed 3) (safety 0) (compilation-speed 0) (debug 0))) (defmethod add ((x number) (y number)) (cl:+ x y)) (defmethod sub ((x number) (y number)) (cl:- x y)) (defmethod unary-sub ((x number)) (cl:- x)) (defmethod mult ((x number) (y number)) (cl:* x y)) (defmethod div ((x number) (y number)) (cl:/ x y)) (defmethod unary-div ((x number)) (cl:/ x)) (defmethod protected-div (x (y number) &key (protected-value 0)) (if (zerop y) protected-value (div x y))) (defmethod protected-unary-div ((x number) &key (protected-value 0)) (if (zerop x) protected-value (unary-div x))) (defmethod sqrt ((x number)) (cl:sqrt x)) (defmethod expt ((x number) (y number)) (cl:expt x y)) (defmethod exp ((x number)) (cl:exp x)) (defmethod log ((x number)) (cl:log x)) (defmethod sin ((x number)) (cl:sin x)) (defmethod cos ((x number)) (cl:cos x)) (defmethod tan ((x number)) (cl:tan x)) ;; methods for sec, csc, cot are handled well by defaults (defmethod sinh ((x number)) (cl:sinh x)) (defmethod cosh ((x number)) (cl:cosh x)) (defmethod tanh ((x number)) (cl:tanh x)) ;; methods for sech, csch, tanh are handled well by defaults ;;; can add more as I think of them/look up what should be included
2,493
Common Lisp
.lisp
76
29.592105
70
0.662207
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
ed4264a55e99bab5c0fc487b6fc5876c0c0351f3e14f111f1a46b8330698cf1e
1,693
[ -1 ]
1,694
package.lisp
ghollisjr_cl-ana/linear-algebra/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (defpackage #:cl-ana.linear-algebra (:use #:cl #:cl-ana.tensor #:cl-ana.list-utils #:cl-ana.math-functions) (:export :make-vector :make-matrix :vector->matrix :lisp-2d-array->tensor :euclidean-dot :euclidean-norm :euclidean-norm2 :matrix-transpose :matrix-mult :phi :theta :cross-product :linsolve :lu-solve :lu-invert :lu-determinant :eigen-decomposition)) (cl-ana.gmath:use-gmath :cl-ana.linear-algebra)
1,429
Common Lisp
.lisp
43
28.627907
70
0.657514
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
429f0d9c8708118a4988e5dd7561f635ceb254df86b0279a6b2f3ed624312a42
1,694
[ -1 ]
1,695
linear-algebra.lisp
ghollisjr_cl-ana/linear-algebra/linear-algebra.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.linear-algebra) ;;;; Matrices/vectors are simply sequences of sequences/sequences ;;;; since the tensor library provides the more general functionality. (defun make-matrix (nrows ncols &key (initial-element 0d0)) (make-tensor (list nrows ncols) :initial-element initial-element)) (defun make-vector (nelts &key (initial-element 0d0)) (make-tensor (list nelts) :initial-element initial-element)) (defun matrix-transpose (matrix &optional (type 'vector)) (let* ((matrix-dims (tensor-dimensions matrix)) (result (make-tensor (reverse matrix-dims) :type type))) (loop for indices in (apply #'cartesian-product (loop for dim in matrix-dims collect (range 0 (1- dim)))) do (setf (apply #'tensor-ref result (reverse indices)) (apply #'tensor-ref matrix indices))) result)) (defun vector->matrix (vector &key (orientation :column) (type 'vector)) (let* ((vector-length (first (tensor-dimensions vector)))) (if (equal orientation :column) ;; column (let ((result (make-tensor (list vector-length 1) :type type))) (loop for i below vector-length do (setf (tensor-ref result i 0) (tensor-ref vector i))) result) ;; row (let ((result (make-tensor (list 1 vector-length) :type type))) (loop for i below vector-length do (setf (tensor-ref result 0 i) (tensor-ref vector i))) result)))) (defun matrix-mult (x y &optional (type 'vector)) (tensor-contract (list (cons x 1) (cons y 0)) :type type)) (defun euclidean-dot (x y) (tensor-contract (list (cons x 0) (cons y 0)))) (defun euclidean-norm2 (x) (euclidean-dot x x)) (defun euclidean-norm (x) (sqrt (euclidean-norm2 x))) ;; 3-d vector functions: (defun phi (vector) (atan (elt vector 1) (elt vector 0))) (defun theta (vector) (acos (/ (elt vector 2) (euclidean-norm vector)))) (defun cross-product (a b) "Returns cross product of vectors a and b" (let ((ax (elt a 0)) (ay (elt a 1)) (az (elt a 2)) (bx (elt b 0)) (by (elt b 1)) (bz (elt b 2))) (vector (- (* ay bz) (* by az)) (- (- (* ax bz) (* bx az))) (- (* ax by) (* bx ay))))) ;; Solving linear equations via Gauss-Jordan Elimination. Of course ;; this is not the most efficient algorithm, but all the generally ;; available linear algebra libraries are focused on floating point ;; arithmetic. This simple implementation of Gaussian Elimination ;; will represent data as integers, rational values, or floating point ;; values depending on the input given, which is useful for ;; academic/educatonal examples. (defun linsolve (A B) "Solves the linear equation A x = B for x using Gaussian Elimination. A should be a 2-D tensor containing the coefficients, and B should be a 2-D column tensor or a 1-D tensor of values for the right-hand-side. Returns a list of the solution values x if solvable, or nil if no solution is possible, e.g. singular matrix." (when (and A B) (let* ((coefs (map 'vector (lambda (x) (coerce x 'vector)) A)) (rhs (coerce (if (= (tensor-rank B) 1) (loop for i below (length B) collecting (tensor-ref B i)) (loop for i below (length B) collecting (tensor-ref B i 0))) 'vector)) (dims (tensor-dimensions A)) (nrows (first dims)) (ncols (second dims))) (labels ((leading (col) ;; returns index to first row with non-zero entry at col dimension (loop for i upfrom col below nrows when (not (zerop (tensor-ref coefs i col))) do (return i) finally (return nil))) (normalize-row (row col) ;; normalizes row using value at col (let* ((val (tensor-ref coefs row col))) (loop for i below ncols do (setf (tensor-ref coefs row i) (/ (tensor-ref coefs row i) val))) (setf (aref rhs row) (/ (aref rhs row) val)))) (eliminate-row (row col basis) ;; eliminates row using the (normalized) basis row for col (let* ((ratio (tensor-ref coefs row col))) (loop for j upfrom col below ncols do (setf (tensor-ref coefs row j) (- (tensor-ref coefs row j) (* ratio (tensor-ref coefs basis j))))) (setf (aref rhs row) (- (aref rhs row) (* ratio (aref rhs basis)))))) (swap-rows (r1 r2) ;; swaps rows r1 and r2 (when (not (= r1 r2)) (loop for j below ncols for tmp = (tensor-ref coefs r1 j) do (setf (tensor-ref coefs r1 j) (tensor-ref coefs r2 j)) (setf (tensor-ref coefs r2 j) tmp)) (let* ((tmp (aref rhs r1))) (setf (aref rhs r1) (aref rhs r2)) (setf (aref rhs r2) tmp))))) (loop for j below ncols for leading = (leading j) do (when (null leading) ; singular matrix (return-from linsolve nil)) (normalize-row leading j) (loop for i below nrows when (not (= i leading)) do (eliminate-row i j leading)) (swap-rows j leading)) (coerce rhs 'list))))) (defun lisp-2d-array->tensor (arr) (let* ((dims (array-dimensions arr)) (n (product dims)) (result (make-tensor dims))) (loop for i below n do (setf (tensor-flat-ref result i) (apply #'aref arr (cl-ana.tensor::unflatten-index i dims)))) (map 'list (lambda (x) (coerce x 'list)) result))) ;; Frontend to GSLL's lu-solve: (defun lu-solve (A B) "Frontend to GSLL. Solves linear equation A x = B. A should be a list of lists, and B should be a list." (let* ((matA (grid:make-foreign-array 'double-float :initial-contents (->double-float A))) (matB (grid:make-foreign-array 'double-float :initial-contents (->double-float B)))) (multiple-value-bind (matrix perm) (gsll:lu-decomposition matA) (let* ((solution (gsll:lu-solve matrix matB perm))) (coerce (grid:cl-array solution) 'list))))) ;; Frontend to GSLL's lu-invert: (defun lu-invert (matrix) "Frontend to GSLL. Inverts matrix. matrix should be a list of lists." (let* ((mat (grid:make-foreign-array 'double-float :initial-contents (->double-float matrix)))) (multiple-value-bind (matrix perm) (gsll:lu-decomposition mat) (let* ((result (gsll:lu-invert matrix perm))) (map 'list (lambda (x) (coerce x 'list)) (lisp-2d-array->tensor (grid:cl-array result))))))) ;; Frontend to GSLL's LU-determinant (defun lu-determinant (matrix) "Frontend to GSLL. matrix should be a list of lists." (let* ((mat (grid:make-foreign-array 'double-float :initial-contents (->double-float matrix)))) (multiple-value-bind (matrix perm signum) (gsll:lu-decomposition mat) (gsll:lu-determinant matrix signum)))) ;; Eigendecomposition: (defun eigen-decomposition (matrix) "Returns eigen values and eigen vectors of the matrix. Frontend to GSLL. Returns: * eigenvalue list * eigenvector list" (let* ((mat (grid:make-foreign-array 'double-float :dimensions (tensor-dimensions matrix) :initial-contents matrix))) (multiple-value-bind (values vectors) (gsll:eigenvalues-eigenvectors-nonsymm mat) (values (coerce (grid:cl-array values) 'list) (transpose (map 'list (lambda (x) (coerce x 'list)) (lisp-2d-array->tensor (grid:cl-array vectors))))))))
9,804
Common Lisp
.lisp
251
28.49004
83
0.547849
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
55c900847ddce9e499c826e95b89a704b20d53460081964dc29a8a998760714a
1,695
[ -1 ]
1,696
package.lisp
ghollisjr_cl-ana/calculus/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (defpackage #:cl-ana.calculus (:use :cl :cl-ana.linear-algebra) (:export :diff :multidiff :newton :multinewton :invert :rk4)) (cl-ana.gmath:use-gmath :cl-ana.calculus)
1,109
Common Lisp
.lisp
30
33.533333
70
0.675023
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
9e3ab8c5db8f2ecbae9926f89128210e5b50da379bd7395921dc0a39cb24092a
1,696
[ -1 ]
1,697
differentiation.lisp
ghollisjr_cl-ana/calculus/differentiation.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.calculus) (defun diff (fn &key (prec 1d-9)) "Returns the one-sided numerical derivative of a function." (lambda (x) (/ (- (funcall fn (+ x prec)) (funcall fn x)) prec))) (defun multidiff (fn &key (prec 1d-9)) "Returns function to compute the matrix of derivatives of a many-valued function of multiple inputs. Assumes fn uses the same input and output sequence types. Return type of the generated function is a 2-D array." (lambda (v) (let* ((type (type-of v)) (len (length v)) (deltas (loop for i below len collecting (let* ((s (make-sequence type len :initial-element 0d0))) (setf (elt s i) prec) s))) (base (funcall fn v)) (outlen (length base)) (result (make-array (list outlen len) :element-type 'double-float))) (loop for j below len for delta in deltas do (let* ((y (funcall fn (+ v delta))) (diff (/ (- y base) prec))) (loop for i below outlen do (setf (aref result i j) (elt diff i))))) result)))
2,276
Common Lisp
.lisp
60
28.933333
70
0.561681
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
8f83f9fa1ef65dbb6504c3ab75ebc51475f91f4518e8d0a64e721522f8d58eae
1,697
[ -1 ]
1,698
rk4.lisp
ghollisjr_cl-ana/calculus/rk4.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2021 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.calculus) ;;;; Runge-Kutta 4th-order solver in Lisp (defun rk4 (dy/dx y0 x0 xN N) "Applies the 4th-order Runge Kutta method (RK4) to solve dy/dx = f(x,y) where y(x0) = y0. xN is the last value of x, and N is the number of x values to find approximations for y(x). dy/dx should be a function (lambda (x y) ...) returning dy/dx for given (x,y). y can have numerical values or sequence values." (cond ((<= N 0) NIL) ((= N 1) (list (cons x0 y0))) (t (let* ((result (list (cons x0 y0))) (x x0) (y y0) (h (/ (- xN x0) (1- N))) (h2 (* 0.5d0 h)) (h6 (/ h 6d0))) (labels ((stepfn () (let* ((k1 (funcall dy/dx x y)) (k2 (funcall dy/dx (+ x h2) (+ y (* h2 k1)))) (k3 (funcall dy/dx (+ x h2) (+ y (* h2 k2)))) (k4 (funcall dy/dx (+ x h) (+ y (* h k3))))) (incf y (* h6 (+ k1 (* 2d0 k2) (* 2d0 k3) k4))) (incf x h) (push (cons x y) result)))) (loop for i below (1- N) do (stepfn)) (nreverse result))))))
2,439
Common Lisp
.lisp
62
27.612903
70
0.477675
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
89bdf66fe2ad18978e31d5ca2889b530bc1315f4126396a58213be439ed5bc55
1,698
[ -1 ]
1,699
newton.lisp
ghollisjr_cl-ana/calculus/newton.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.calculus) (defun newton (fn guess &key (step-scale 1) (value 0) (maxtries 50) (prec 1d-4) (diff-prec 1d-9)) "1-D Newton's method for solving an equation. If the method converges, returns the values of x_sol, fn(x_sol), and the number of iterations it took to converge. If the method does not converge, returns the values of nil and the number of iterations on failure. value is the value that fn should evaluate to. maxtries is the maximum number of iterations to attempt a solution. prec is the precision in the residue, below which convergence is assumed. diff-prec is the precision to use in calculating the derivative of fn via diff." (let ((df (diff fn :prec diff-prec)) (func (lambda (x) (- (funcall fn x) value)))) (do ((x guess (- x (* step-scale (/ (funcall func x) (funcall df x))))) (i 0 (1+ i)) (difference (* 10 prec) (abs (funcall func x)))) ((or (<= difference prec) (>= i maxtries)) (if (> difference prec) (values nil i) (values x (funcall fn x) i)))))) (defun invert (fn &key (guess-fn (constantly 1)) (newton-prec 1d-4) (diff-prec 1d-9)) "Inverts a function numerically using Newton's method. Returns the inverse function using the precision parameters given. guess-fn is a function which evaluates to a guess value for each input value to the inverse function to use in Newton's method. newton-prec is the precision argument to give to Newton's method for the precision in the residue of the result. diff-prec is the precision to give to diff during Newton's method." (lambda (x) (newton fn (funcall guess-fn x) :value x :prec newton-prec :diff-prec diff-prec))) ;; I've kept a few pieces of code in this function that aren't used ;; because more investigration is needed as to which strategy is best ;; for general use. ;; ;; LU decomposition is used to either invert the derivative matrix or ;; solve a matrix equation involving that matrix. Inversion of the ;; matrix provides more stability as the same matrix is used to ;; multiply as many inputs as desired, but lu-solve can be more ;; efficient depending on the derivative matrix. (defun multinewton (fn guess &key (step-scale 1) (value 0) (maxtries 50) (prec 1d-4) (diff-prec 1d-9) (metric :norm2)) "Multi-dimensional Newton's method for solving a system of equations. Dimensionality of inputs and outputs is handled as per multidiff. Note that the input and output dimensionality must match as this attempts to find an exact solution to a system of N equations in N variables. If the method converges, returns the values of x_sol, fn(x_sol), and the number of iterations it took to converge. If the method does not converge, returns the values of nil and the number of iterations on failure. value is the value that fn should evaluate to. Note that scalar values are interpreted as vectors with all elements equal to the scalar value. This is particularly convenient for the default value of 0. maxtries is the maximum number of iterations to attempt a solution. prec is the precision in the residue, below which convergence is assumed. diff-prec is the precision to use in calculating the derivative of fn via diff. metric can be one of: :max for maximum of differences :norm for euclidean-norm of difference vector :norm2 for euclidean-norm2 of difference vector" (let* ((mfn (case metric (:max (lambda (x) (reduce #'max (map 'list #'abs x)))) (:norm (lambda (x) (sqrt (reduce #'+ (map 'list (lambda (y) (expt y 2)) x))))) (:norm2 (lambda (x) (reduce #'+ (map 'list (lambda (y) (expt y 2)) x)))))) (df (multidiff fn :prec diff-prec)) (inverse (lambda (v) (lu-invert (lisp-2d-array->tensor (funcall df v))))) (func (lambda (x) (- (funcall fn x) value))) (solver (lambda (v) (lu-solve (lisp-2d-array->tensor (funcall df v)) (coerce (funcall func v) 'list)))) ) (do ((x guess (- x ;; (funcall solver x) ;; (lu-solve (lisp-2d-array->tensor ;; (funcall df x)) ;; (coerce (funcall func x) 'list)) (* step-scale (matrix-mult (funcall inverse x) (funcall func x))) )) (i 0 (1+ i)) (difference (* 10 prec) (funcall mfn (funcall func x)))) ((or (<= difference prec) (>= i maxtries)) (if (> difference prec) (values nil i) (values x (funcall fn x) i))))))
6,666
Common Lisp
.lisp
155
31.509677
73
0.557251
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
8840a6af5332bac62777d4f83744823352b1df74686f3dd4429ee040cffc7f2d
1,699
[ -1 ]
1,700
package.lisp
ghollisjr_cl-ana/table-viewing/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (defpackage #:cl-ana.table-viewing (:use #:cl #:alexandria #:cl-ana.list-utils #:cl-ana.string-utils #:cl-ana.macro-utils #:cl-ana.table #:cl-ana.histogram #:cl-ana.plotting) (:export :table-view :table-easy-view)) (cl-ana.gmath:use-gmath :cl-ana.table-viewing)
1,200
Common Lisp
.lisp
32
34.3125
70
0.679245
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
d79967b5d9c0929eaf9f4d6cf82c19ae4a3b58ca9227288427d3e06183a0f8a4
1,700
[ -1 ]
1,701
table-viewing.lisp
ghollisjr_cl-ana/table-viewing/table-viewing.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.table-viewing) (defun table-view (table fields bin-specs &key (processor #'list) (filter (constantly t))) "table-view plots & histograms processed data from a table; note that a reusable-table should be used generally since this does exhaust the table. It plots & returns (via multiple values) the histogram (contiguous) & page for the plot. fields is a list of fields to select from the table. bin-specs is a list of bin-spec lists: Each bin-spec is a plist with slots :name, :nbins, :low and :high. These are passed directly to make-contiguous-hist. processor generates the list of values suitable for insertion into the histogram. It should take as many arguments as the fields selected; the fields will be applied to fn in the order specified. By default it simply returns the list of selected fields. filter is an optional function which takes the selected fields as arguments and returns t whenever the event should be included in the viewing. By default it always returns t." (let* ((field-symbols (mapcar (compose #'intern #'lispify) fields)) (hist (make-contiguous-hist bin-specs))) (table-reduce table fields (lambda (&rest xs) (when (apply filter (rest xs)) (hist-insert hist (mklist (apply processor (rest xs))))))) (values hist (draw hist)))) (defmacro table-easy-view (table fields bin-specs &key processor filter) "Similar to table-view, but allows processor and filter to be expressions which will be used as a body in the appropriate lambda functions when specified. fields is not evaluated. bin-specs is evaluated." (let ((field-symbols (mapcar (compose #'intern #'lispify #'string) fields))) `(apply #'table-view ,table ',fields ,bin-specs (list ,@(when-keywords (:processor (when processor `(lambda (,@field-symbols) ,processor))) (:filter (when filter `(lambda (,@field-symbols) ,filter))))))))
3,344
Common Lisp
.lisp
67
39.432836
75
0.610771
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
d33037dc583b511575f102d4fc23eb5c43d9d7b1eb03f5ef57ef1061f31a6948
1,701
[ -1 ]
1,702
test.lisp
ghollisjr_cl-ana/table-viewing/test.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (require 'cl-ana) (in-package :cl-ana) (defparameter *table* (wrap-for-reuse (open-plist-table (loop for i below 10000 collecting (list 'x (random 30) 'y (random 30)))))) (defparameter *hist* (table-view *table* (list (list :name "x" :nbins 30 :low 0d0 :high 30d0)))) (print (hist-bin-values *hist*))
1,319
Common Lisp
.lisp
37
30.594595
70
0.634299
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
d10ff16fd3bd13be4f09d5f721e018477b58e71891dfaeac2099dca3c25caf2d
1,702
[ -1 ]
1,703
package.lisp
ghollisjr_cl-ana/error-propogation/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; package.lisp (defpackage #:cl-ana.error-propogation (:nicknames #:cl-ana.err-prop) (:use :cl :cl-ana.math-functions) (:export :*err-num-pretty-print* ; for print style :err-num :+- :err-num-value :err-num-error ;; These functions are provided in the event that one wants ;; to supply a lot of arguments to the generic +, -, *, or ;; / functions, since this would be inefficient the way it ;; is implemented currently: :err-num-+ :err-num-- :err-num-* :err-num-/)) (cl-ana.gmath:use-gmath :cl-ana.error-propogation)
1,457
Common Lisp
.lisp
39
34.589744
70
0.683616
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
3bc956a47b323c730c8da1109bff3ed62e9b3537d746f17052d135d1ec891495
1,703
[ -1 ]
1,704
error-propogation.lisp
ghollisjr_cl-ana/error-propogation/error-propogation.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.err-prop) (eval-when (:compile-toplevel :load-toplevel :execute) (defclass err-num () ((val :accessor err-num-value :initarg :value :initform 0) (err :accessor err-num-error :initarg :error :initform 0))) ;; Old method: ;; (defmethod print-object ((e err-num) stream) ;; (labels ((rec (e result) ;; (if (subtypep (type-of e) ;; 'err-num) ;; (with-slots (val err) ;; e ;; (rec err (cons val result))) ;; (nreverse (cons e result))))) ;; (format stream "~a" (cons "+-" (rec e nil))))) ;; New method: (defun err-num-list (e) "Returns list of values and errors for an err-num with nested errors." (labels ((rec (e result) (if (subtypep (type-of e) 'err-num) (with-slots (val err) e (rec err (cons val result))) (nreverse (cons e result))))) (rec e nil))) (defmethod print-object ((e err-num) stream) (format stream "#~~~a" (err-num-list e))) (defun err-num-transformer-reader-macro (stream subchar arg) (let* ((expr (read stream t))) (apply #'+- expr))) (set-dispatch-macro-character #\# #\~ #'err-num-transformer-reader-macro) (defmethod make-load-form ((self err-num) &optional environment) `(+- ,@(err-num-list self))) ;; The constructor for err-nums: (defun +- (&rest val-errs) "Constructs a numerical value along with errors. Note that the structure allows for errors in errors to arbitrary depth." (when val-errs (let ((val (first val-errs)) (errs (rest val-errs))) (if errs (make-instance 'err-num :value val :error (apply #'+- errs)) val)))) (defun err-num-+ (&rest err-nums) (+- (reduce #'+ (mapcar #'err-num-value err-nums)) (sum-in-quadrature (mapcar #'err-num-error err-nums)))) (defmethod add ((x err-num) (y err-num)) (+- (apply #'add (mapcar #'err-num-value (list x y))) (sum-in-quadrature (mapcar #'err-num-error (list x y))))) (defmethod-commutative add ((x err-num) (y number)) (add x (+- y 0))) (defun err-num-- (&rest err-nums) (+- (apply #'- (mapcar #'err-num-value err-nums)) (sum-in-quadrature (mapcar #'err-num-error err-nums)))) (defmethod sub ((x err-num) (y err-num)) (+- (apply #'sub (mapcar #'err-num-value (list x y))) (sum-in-quadrature (mapcar #'err-num-error (list x y))))) (defmethod sub ((x err-num) (y number)) (sub x (+- y 0))) (defmethod sub ((x number) (y err-num)) (sub (+- x 0) y)) (defmethod unary-sub ((x err-num)) (with-accessors ((val err-num-value) (err err-num-error)) x (+- (unary-sub val) err))) (defun err-num-* (&rest err-nums) (let* ((values (mapcar #'err-num-value err-nums)) (errors (mapcar #'err-num-error err-nums)) (relative-errors (mapcar #'div errors values)) (result-value (apply #'mult values))) (+- result-value (* result-value (sum-in-quadrature relative-errors))))) ;; OLD VERSION ;; ;; This version suffers from lack of foresight, although it is ;; mathematically beautiful. The relative error does not exist when ;; the value is zero, so I have to resort to the ugly formula for ;; the calculation instead. ;; ;; (defmethod mult ((x err-num) (y err-num)) ;; (let* ((values (mapcar #'err-num-value (list x y))) ;; (errors (mapcar #'err-num-error (list x y))) ;; (relative-errors (mapcar #'div errors values)) ;; (result-value (apply #'mult values))) ;; (+- result-value ;; (mult result-value ;; (sum-in-quadrature ;; relative-errors))))) (defmethod mult ((x err-num) (y err-num)) (let* ((values (mapcar #'err-num-value (list x y))) (errors (mapcar #'err-num-error (list x y))) (result-value (apply #'mult values))) (+- result-value (sum-in-quadrature (list (* (first values) (second errors)) (* (second values) (first errors))))))) (defmethod-commutative mult ((x err-num) (y number)) (mult x (+- y 0))) (defun err-num-/ (&rest err-nums) (let* ((values (mapcar #'err-num-value err-nums)) (errors (mapcar #'err-num-error err-nums)) (relative-errors (mapcar #'/ errors values)) (result-value (reduce #'/ values))) (+- result-value (* result-value (sum-in-quadrature relative-errors))))) ;; OLD VERSION ;; ;; As noted in the mult method above, this doesn't work for zero ;; values even in the numerator. The relative error needs a ;; non-zero value. So, I have to resort to the full expression ;; instead. ;; ;; (defmethod div ((x err-num) (y err-num)) ;; (let* ((arglist (list x y)) ;; (values (mapcar #'err-num-value arglist)) ;; (errors (mapcar #'err-num-error arglist)) ;; (relative-errors (mapcar #'div errors values)) ;; (result-value (apply #'div values))) ;; (+- result-value ;; (* result-value ;; (sum-in-quadrature ;; relative-errors))))) (defmethod div ((x err-num) (y err-num)) (let* ((arglist (list x y)) (values (mapcar #'err-num-value arglist)) (errors (mapcar #'err-num-error arglist)) (result-value (apply #'div values))) (+- result-value (sum-in-quadrature (list (/ (first errors) (second values)) (/ (* (first values) (second errors)) (expt (second values) 2))))))) (defmethod div ((x err-num) (y number)) (div x (+- y 0))) (defmethod div ((x number) (y err-num)) (div (+- x 0) y)) (defmethod unary-div ((x err-num)) (let ((result-value (unary-div (err-num-value x)))) (+- result-value (mult result-value (err-num-error x))))) (defmethod protected-div ((x err-num) (y number) &key (protected-value 0)) (if (zerop y) protected-value (div x y))) (defmethod protected-div ((x number) (y err-num) &key (protected-value 0)) (if (zerop (err-num-value y)) protected-value (div x y))) (defmethod protected-div ((x err-num) (y err-num) &key (protected-value 0)) (if (zerop (err-num-value y)) protected-value (div x y))) (defmethod protected-unary-div ((x err-num) &key (protected-value 0)) (if (zerop (err-num-value x)) protected-value (unary-div x))) (defmethod sqrt ((err-num err-num)) (let ((result-value (sqrt (err-num-value err-num)))) (+- result-value (/ (err-num-error err-num) 2 result-value)))) (defmethod expt ((x err-num) (y err-num)) (let* ((value1 (err-num-value x)) (value2 (err-num-value y)) (error1 (err-num-error x)) (error2 (err-num-error y)) (result-value (expt value1 value2)) (result-error1 (* error1 value2 (expt value1 (- value2 1)))) (result-error2 ;; had to handle limits more carefully with this (if (zerop value1) 0 (* error2 result-value (log value1))))) (+- result-value (sum-in-quadrature (list result-error1 result-error2))))) (defmethod expt ((x number) (y err-num)) (expt (+- x 0) y)) (defmethod expt ((x err-num) (y number)) (expt x (+- y 0))) (defmethod exp ((err-num err-num)) (let ((result-value (exp (err-num-value err-num)))) (+- result-value (* result-value (err-num-error err-num))))) (defmethod log ((err-num err-num)) (with-accessors ((val err-num-value) (err err-num-error)) err-num (+- (log val) (/ err val)))) (defmethod sin ((err-num err-num)) (with-accessors ((val err-num-value) (err err-num-error)) err-num (+- (sin val) (* err (abs (cos val)))))) (defmethod cos ((err-num err-num)) (with-accessors ((val err-num-value) (err err-num-error)) err-num (+- (cos val) (* err (abs (sin val)))))) (defmethod tan ((err-num err-num)) (with-accessors ((val err-num-value) (err err-num-error)) err-num (+- (tan val) (/ err (expt (cos val) 2))))) (defmethod sinh ((err-num err-num)) (with-accessors ((val err-num-value) (err err-num-error)) err-num (+- (sinh val) (* err (cosh val))))) (defmethod cosh ((err-num err-num)) (with-accessors ((val err-num-value) (err err-num-error)) err-num (+- (cosh val) (* err (abs (sinh val)))))) (defmethod tanh ((err-num err-num)) (with-accessors ((val err-num-value) (err err-num-error)) err-num (+- (tanh val) (/ err (expt (cosh val) 2))))) (defun sum-in-quadrature (xs) (sqrt (apply #'+ (mapcar (lambda (x) (expt x 2)) xs))))) ;;;; Utility functions (defmethod ->double-float ((x err-num)) (+- (->double-float (err-num-value x)) (->double-float (err-num-error x))))
10,962
Common Lisp
.lisp
299
28.317726
70
0.528503
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
e6d86e3672c33ce56e102266831f00c32a75f8c4ad756d23ce02d047b5ebce67
1,704
[ -1 ]
1,705
large-example.lisp
ghollisjr_cl-ana/tutorials/dop/large-example.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2016 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (require 'cl-ana) (in-package :cl-ana) (defproject large-example "/home/ghollisjr/dop-large-example/logged-results" (list #'macrotrans #'branchtrans #'tabletrans #'progresstrans) (fixed-cache 5)) (ensure-table-binding-ops) (ensure-table-op-expanders) (setf *print-progress* 10000) (defun project-graph->png () (dot->png (dot-compile "/home/ghollisjr/dop-large-example/graph.dot" :if-exists :supersede) "/home/ghollisjr/dop-large-example/graph.png")) ;;; Source data generation ;; Number of rows in the dataset (defres (dataset nrows) 1000000) ;; Background contamination (background/(background + signal)) (defres background-ratio 0.5) (defres (background nrows) (floor (* (res (dataset nrows)) (res background-ratio)))) (defres (signal nrows) (- (res (dataset nrows)) (res (background nrows)))) ;; X sigmas (defres (signal x sigma) 1d0) (defres (background x sigma) 3d0) ;; Y slopes and offsets (defres (signal slope) 0.2) (defres (signal offset mean) 5d0) (defres (signal offset sigma) 0.5d0) (defres (background slope) -0.2) (defres (background offset mean) 0d0) (defres (background offset sigma) 1d0) ;; Source data bootstrap (defres bootstrap (with-open-hdf-file (file (work-path "data.h5") :direction :output :if-exists :supersede :if-does-not-exist :create) (let ((tab (create-hdf-table file "/table" '(("X" . :double) ("Y" . :double))))) ;; Signal (loop for i below (res (signal nrows)) do (let* ((x (* (res (signal x sigma)) (alexandria:gaussian-random -5d0 5d0))) (b (+ (* (res (signal offset sigma)) (alexandria:gaussian-random -5d0 5d0)) (res (signal offset mean)))) (y (+ (* (res (signal slope)) x) b))) (table-push-fields tab x y))) ;; Background (loop for i below (res (background nrows)) do (let* ((x (* (res (background x sigma)) (alexandria:gaussian-random -5d0 5d0))) (b (+ (* (res (background offset sigma)) (alexandria:gaussian-random -5d0 5d0)) (res (background offset mean)))) (y (+ (* (res (background slope)) x) b))) (table-push-fields tab x y))) (table-close tab)))) ;;; Analyzing data ;; Source data (defres src (srctab (hdf-chain-opener (list (work-path "data.h5"))) (res bootstrap))) ;; contaminated X histogram (defres (src x hist) (dotab (res src) ((hist (make-shist '((:name "X" :low -9d0 :high 9d0 :nbins 100))))) hist (hins hist (list (field x))))) (defres (plot (src x hist)) (draw (page (list (plot2d (list (line (res (src x hist)) :style "boxes" :color "red" :fill-style "solid" :fill-density 0.3 :title "Contaminated X Distribution")) :x-title "X" :y-title "Count")) :output (work-path "plots/src/x-hist.png") :terminal (png-term)))) ;; Model fitting: (defun model (params x) (destructuring-bind (sigA sigMu sigSigma bacA bacMu bacSigma) params (+ (gaussian (list sigA sigMu sigSigma) x) (gaussian (list bacA bacMu bacSigma) x)))) (defres (model fit-results) (let* ((hist (res (src x hist))) (peak (maximum (cdrs (map->alist hist))))) (rest (multiple-value-list (fit (res (src x hist)) #'model (list ;; Signal guess parameters (gauss-amp (* 0.5 peak) 1d0) 0d0 1d0 ;; Background guess parameters (gauss-amp (* 0.5 peak) 1d0) 0d0 3d0)))))) (defres (model fit-params) (first (res (model fit-results)))) (defres (model fit) (let ((params (res (model fit-params)))) (lambda (x) (model params x)))) ;; Signal fit (defres (model signal fit-params) (subseq (res (model fit-params)) 0 3)) (defres (model signal fit) (let ((params (res (model signal fit-params)))) (lambda (x) (gaussian params x)))) ;; Background fit (defres (model background fit-params) (subseq (res (model fit-params)) 3)) (defres (model background fit) (let ((params (res (model background fit-params)))) (lambda (x) (gaussian params x)))) ;; Model plot: (defres (plot (model signal background)) (let* ((hist (res (src x hist))) (hist-alist (map->alist hist)) (xmin (minimum (cars hist-alist))) (xmax (maximum (cars hist-alist))) (ymax (maximum (cdrs hist-alist))) (model (res (model fit))) (signal (res (model signal fit))) (signal-params (res (model signal fit-params))) (background (res (model background fit))) (background-params (res (model background fit-params)))) (draw (page (list (plot2d (list (line hist :style "boxes" :fill-style "solid" :fill-density 0.3 :color "red" :title "Contaminated X Distribution") (line model :sampling (list :nsamples 1000 :low xmin :high xmax) :style "lines" :color "black" :line-width 2 :title "Model Signal+Background") (line signal :sampling (list :nsamples 1000 :low xmin :high xmax) :style "lines" :color "blue" :line-width 2 :title (format nil "Signal (A=~,2e,mu=~,2e,sigma=~,2e)" (first signal-params) (second signal-params) (third signal-params))) (line background :sampling (list :nsamples 1000 :low xmin :high xmax) :style "lines" :color "green" :line-width 2 :title (format nil "Background (A=~,2e,mu=~,2e,sigma=~,2e)" (first background-params) (second background-params) (third background-params)))) :x-title "X" :y-title "Count" :y-range (cons 0 (* 1.2 ymax)))) :output (work-path "plots/model.png") :terminal (png-term))))) ;;; Cut on Y (defres (src x-y hist) (dotab (res src) ((hist (make-shist '((:name "X" :low -9d0 :high 9d0 :nbins 100) (:name "Y" :low -5d0 :high 8d0 :nbins 100))))) hist (hins hist (list (field x) (field y))))) ;; plot (defres (plot (src x-y hist)) (let* ((hist (res (src x-y hist)))) (draw (page (list (plot2d (list (line hist)) :title "X-Y Distribution" :x-title "X" :y-title "Y")) :output (work-path "plots/src/x-y-hist.jpg") :terminal (jpeg-term))))) ;;;; TODO: ;;;; ;;;; * Use branching to experiment with different X-Y cuts to isolate signal ;;;; ;;;; * Includes branching on ltabs and a final selection ;;;; ;;;; * Plot different cuts all together in cut plot (defres (y-cut slices) (hslice (res (src x-y hist)) "X")) (defres (y-cut x-range) (cons -2 2)) (defres (y-cut y-range) (cons 3 8)) (defres (y-cut slices filtered) (let* ((slices (res (y-cut slices))) (x-range (res (y-cut x-range))) (y-range (res (y-cut y-range))) (result (make-hash-table :test 'equal))) (loop for key being the hash-keys in slices for h being the hash-values in slices when (<= (car x-range) (first key) (cdr x-range)) do (setf (gethash key result) (hist-filter (lambda (count &key y) (<= (car y-range) y (cdr y-range))) h))) result)) (defres (y-cut fit-results) (let* ((filtered (res (y-cut slices filtered))) (result (make-hash-table :test 'equal))) (loop for key being the hash-keys in filtered for h being the hash-values in filtered do (let* ((alist (map->alist h)) (peak (maximum alist :key #'car)) (xpeak (car peak)) (ypeak (cdr peak))) (setf (gethash key result) (rest (multiple-value-list (fit h #'gaussian (list (gauss-amp ypeak 0.5d0) xpeak 0.5d0))))))) result)) (defres (y-cut fit-params) (let* ((fit-results (res (y-cut fit-results))) (result (make-hash-table :test 'equal))) (loop for key being the hash-keys in fit-results for fr being the hash-values in fit-results do (setf (gethash key result) (first fr))) result)) (defres (y-cut fits) (let* ((fit-params (res (y-cut fit-params))) (result (make-hash-table :test 'equal))) (loop for key being the hash-keys in fit-params for fp being the hash-values in fit-params do (setf (gethash key result) (let ((pars (copy-list fp))) (lambda (x) (gaussian pars x))))) result)) (logres-ignore (y-cut fits)) ;; Plot of slice fits: (defres (plot (y-cut slice fits)) (let* ((filtered (res (y-cut slices filtered))) (fits (res (y-cut fits))) (fit-params (res (y-cut fit-params)))) (loop for key being the hash-keys in filtered for h being the hash-values in filtered do (let* ((x (first key)) (alist (map->alist h)) (xmin (minimum (cars alist))) (xmax (maximum (cars alist))) (ymax (maximum (cdrs alist))) (fit (gethash key fits)) (params (gethash key fit-params)) (A (first params)) (mu (second params)) (sigma (third params))) (draw (page (list (plot2d (list (line h :title "Y Distribution" :color "red" :style "boxes" :fill-style "solid" :fill-density 0.3) (line fit :title (format nil "Gaussian Fit (A=~,2e,mu=~,2e,sigma=~,2e)" A mu sigma) :sampling (list :nsamples 1000 :low xmin :high xmax) :color "black" :style "lines" :line-width 2)) :title (format nil "Y Slice Fit for X=~,2e" x) :x-title "Y" :x-range (cons xmin xmax) :y-title "count" :y-range (cons 0 (* 1.2 ymax)))) :output (work-path "plots/y-cut/slices/X_~,4f.jpg" x) :terminal (jpeg-term))))))) ;;; Branching on nsigma (defres (branching y-cut-nsigmas) (branch (range 1 3 1))) (defres (branching y-cut lower-bounds) (branch (res (branching y-cut-nsigmas)) (let ((fit-params (res (y-cut fit-params)))) (sort (loop for key being the hash-keys in fit-params for fp being the hash-values in fit-params collecting (let ((mu (second fp)) (sigma (third fp))) (cons (first key) (- mu (* (branch) sigma))))) #'< :key #'car)))) (defres (branching y-cut upper-bounds) (branch (res (branching y-cut-nsigmas)) (let ((fit-params (res (y-cut fit-params)))) (sort (loop for key being the hash-keys in fit-params for fp being the hash-values in fit-params collecting (let ((mu (second fp)) (sigma (third fp))) (cons (first key) (+ mu (* (branch) sigma))))) #'< :key #'car)))) ;; lower fit (defres (branching y-cut lower-bounds fit-results) (branch (res (branching y-cut-nsigmas)) (rest (multiple-value-list (fit (res (branching y-cut lower-bounds)) #'polynomial (list 1d0 1d0)))))) (defres (branching y-cut lower-bounds fit-params) (branch (res (branching y-cut-nsigmas)) (first (res (branching y-cut lower-bounds fit-results))))) (defres (branching y-cut lower-bounds fit) (branch (res (branching y-cut-nsigmas)) (let ((ps (res (branching y-cut lower-bounds fit-params)))) (lambda (x) (polynomial ps x))))) (logres-ignore (branching y-cut lower-bounds fit)) ;; upper fit (defres (branching y-cut upper-bounds fit-results) (branch (res (branching y-cut-nsigmas)) (rest (multiple-value-list (fit (res (branching y-cut upper-bounds)) #'polynomial (list 1d0 1d0)))))) (defres (branching y-cut upper-bounds fit-params) (branch (res (branching y-cut-nsigmas)) (first (res (branching y-cut upper-bounds fit-results))))) (defres (branching y-cut upper-bounds fit) (branch (res (branching y-cut-nsigmas)) (let ((ps (res (branching y-cut upper-bounds fit-params)))) (lambda (x) (polynomial ps x))))) (logres-ignore (branching y-cut upper-bounds fit)) ;; y-cut plot (defres (plot (y-cut branching)) (let* ((lower-bounds (res (branching y-cut lower-bounds))) (upper-bounds (res (branching y-cut upper-bounds))) (lower-fit (res (branching y-cut lower-bounds fit))) (upper-fit (res (branching y-cut upper-bounds fit))) (x-range (res (y-cut x-range))) (y-range (res (y-cut y-range))) (hist (res (src x-y hist))) (hist-alist (map->alist hist)) (xs (cars (cars hist-alist))) (xmin (minimum xs)) (xmax (maximum xs)) (ys (cars (cdrs (cars hist-alist)))) (ymin (minimum ys)) (ymax (maximum ys))) (draw (page (list (plot2d (append ;; Non-branching (list ;; histogram (line hist) ;; left edge (line (list (cons (car x-range) (car y-range)) (cons (car x-range) (cdr y-range))) :title "Fit Area" :color "black" :style "lines" :line-width 2) ;; right edge (line (list (cons (cdr x-range) (car y-range)) (cons (cdr x-range) (cdr y-range))) :title "" :color "black" :style "lines" :line-width 2) ;; top edge (line (list (cons (car x-range) (cdr y-range)) (cons (cdr x-range) (cdr y-range))) :title "" :color "black" :style "lines" :line-width 2) ;; bottom edge (line (list (cons (car x-range) (car y-range)) (cons (cdr x-range) (car y-range))) :title "" :color "black" :style "lines" :line-width 2) ;; Function legend entry (line (list (cons -100 -100)) :title "Upper Cut Functions" :color "red" :style "lines" :line-width 2) (line (list (cons -100 -100)) :title "Lower Cut Functions" :color "green" :style "lines" :line-width 2)) ;; Branching (loop for key being the hash-keys in lower-bounds for lb being the hash-values in lower-bounds for i from 1 appending (let* ((ub (gethash key upper-bounds)) (lowfit (gethash key lower-fit)) (upfit (gethash key upper-fit))) (list ;; Upper bounds (line ub :title (format nil "Cut Bounds (nsigma=~,2f)" key) :style "points" :point-type i :color "orange" :point-size 1) ;; Lower bounds (line lb :title "" :style "points" :point-type i :color "orange" :point-size 1) ;; Upper fit (line upfit :sampling (list :nsamples 1000 :low (car x-range) :high (cdr x-range)) :title "" :style "lines" :color "red" :line-width 2) ;; Lower fit (line lowfit :sampling (list :nsamples 1000 :low (car x-range) :high (cdr x-range)) :title "" :style "lines" :color "green" :line-width 2))))) :legend (legend :location (cons :left :top)) :x-title "X" :x-range (cons xmin xmax) :y-title "Y" :y-range (cons ymin (* 2 ymax)))) :output (work-path "plots/y-cut/branching-cuts.jpg") :terminal (jpeg-term))))) ;; Cut function: (defres (branching y-cut) (branch (res (branching y-cut-nsigmas)) (let ((lower-fit (res (branching y-cut lower-bounds fit))) (upper-fit (res (branching y-cut upper-bounds fit)))) (lambda (x y) (and (<= (car (res (y-cut x-range))) x (cdr (res (y-cut x-range)))) (<= (funcall lower-fit x) y (funcall upper-fit x))))))) (logres-ignore (branching y-cut)) ;; y-cut table (defres (branching src y-cut) (branch (res (branching y-cut-nsigmas)) (ltab (res src) () (when (funcall (res (branching y-cut)) (field x) (field y)) (push-fields))))) (defres (branching src y-cut x hist) (branch (res (branching y-cut-nsigmas)) (dotab (res (branching src y-cut)) ((hist (make-shist '((:name "X" :low -9d0 :high 9d0 :nbins 100))))) hist (hins hist (list (field x)))))) (defres (plot (y-cut x hist branching normalized)) (let* ((hists (res (branching src y-cut x hist))) (x-range (res (y-cut x-range))) ;; Peak normalization for shape comparison (peaks (loop for nsigmas being the hash-keys in hists for h being the hash-values in hists collecting (let* ((alist (map->alist h)) (peak (maximum (cdrs alist)))) (cons nsigmas peak)))) (fact-alist (mapcar (lambda (cons) (cons (car cons) (/ (cdr cons)))) peaks)) (factors (map->hash-table fact-alist 'equal))) (draw (page (list (plot2d (append (list ;; X fit-range bounds (line (list (cons (car x-range) 0) (cons (car x-range) 1e9)) :title "X fit-range" :style "lines" :color "black") (line (list (cons (cdr x-range) 0) (cons (cdr x-range) 1e9)) :title "" :style "lines" :color "black")) (loop for nsigmas being the hash-keys in hists for hist being the hash-values in hists for point-type from 1 for color in (list "blue" "green" "red" ;; some extras in case we try more values "orange" "purple" "yellow" "brown") collecting (line (* (gethash nsigmas factors) hist) :color color :point-type point-type :point-size 2 :title (format nil "X Distribution (nsigma=~a)" nsigmas) :style "points"))) :title "Comparison of Y-cut effects on X distribution" :legend (legend :front-p t :location (cons :right :top) :box t :width-inc 0.5) :x-title "X" :x-range (cons "*" "*") :y-title "Peak-Normalized Count" :y-range (cons 0 1.3))) :output (work-path "plots/X-hist-y-cut-branching.jpg") :terminal (jpeg-term))))) (defres y-cut-nsigmas 3) (defres y-cut (gethash (res y-cut-nsigmas) (res (branching y-cut)))) (logres-ignore y-cut) ;; y-cut table (defres (src y-cut) (tab (res src) () (hdf-opener (work-path "y-cut.h5") (list (cons "X" :double) (cons "Y" :double))) (when (funcall (res y-cut) (field x) (field y)) (push-fields (x (field x)) (y (field y)))))) (defres (src y-cut x hist) (gethash (res y-cut-nsigmas) (res (branching src y-cut x hist)))) (defres (src y-cut x-y hist) (dotab (res (src y-cut)) ((x-range (res (y-cut x-range))) (y-range (res (y-cut y-range))) (hist (make-shist (list (list :name "X" :low (car x-range) :high (cdr x-range) :nbins 100) (list :name "Y" :low (car y-range) :high (cdr y-range) :nbins 100))))) hist (hins hist (list (field x) (field y)))))
26,948
Common Lisp
.lisp
672
23.604167
85
0.427732
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
422b8c1b598929c5ec2bdf793b0646f4385d233847345cd213a5c20f4b9408c7
1,705
[ -1 ]
1,706
package.lisp
ghollisjr_cl-ana/file-utils/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (defpackage #:cl-ana.file-utils (:use :cl :external-program :split-sequence) (:export ;; read-utils :read-lines-from-file :read-lines-from-pathname :read-fields-from-file :read-fields-from-pathname ;; write-utils :write-lines-to-file :write-lines-to-pathname ;; stat-utils :file-last-changed ;; sha :sha1 :sha1-from-pathname))
1,255
Common Lisp
.lisp
38
30.447368
70
0.697368
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
62091a3efcd1094931301717d01f736e1e880916006bfd6b5218fc6273bca85e
1,706
[ -1 ]
1,707
stat-utils.lisp
ghollisjr_cl-ana/file-utils/stat-utils.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.file-utils) (defun file-last-changed (pathname-or-string) "Returns time in seconds since epoch of when the file data was changed." (values (read-from-string (with-output-to-string (s) (run "stat" (list "--format" "%Y" (namestring pathname-or-string)) :output s)))))
1,309
Common Lisp
.lisp
31
36.193548
70
0.63558
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
807b11979995533b9e3e42ce9b848a9ee4c4d49a97e3392569b06a8d9ad72408
1,707
[ -1 ]
1,708
write-utils.lisp
ghollisjr_cl-ana/file-utils/write-utils.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.file-utils) (defun write-lines-to-file (lines file) (loop for line in lines do (format file "~a~%" line))) (defun write-lines-to-pathname (lines pathname &key if-exists if-does-not-exist) (with-open-file (file pathname :direction :output :if-exists if-exists :if-does-not-exist if-does-not-exist) (write-lines-to-file lines file)))
1,416
Common Lisp
.lisp
34
34.852941
70
0.626541
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
5fbd2e50a2c5299890b03e6972196cb6a7912686eca272b3e89e92517b293b17
1,708
[ -1 ]
1,709
sha.lisp
ghollisjr_cl-ana/file-utils/sha.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.file-utils) (defun sha1 (string) "Returns the sha1 sum of a string of text." (with-input-from-string (str (with-output-to-string (s) (with-input-from-string (text string) (run "sha1sum" (list "-") :input text :output s)))) (first (split-sequence #\space (read-line str))))) (defun sha1-from-pathname (pathname-or-string) "Returns sha1 sum of file located at pathname-or-string." (with-input-from-string (str (with-output-to-string (s) (run "sha1sum" (list (namestring pathname-or-string)) :output s))) (first (split-sequence #\space (read-line str)))))
1,644
Common Lisp
.lisp
43
32.488372
70
0.633917
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
0418aca5e5623208b31175f68335f6fa67defb001b92fdee921a662136537eae
1,709
[ -1 ]
1,710
read-utils.lisp
ghollisjr_cl-ana/file-utils/read-utils.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.file-utils) (defun read-lines-from-file (file) (loop for line = (read-line file nil 'eof) until (equal line 'eof) collecting line)) (defun read-lines-from-pathname (pathname) (with-open-file (file pathname :direction :input :if-does-not-exist :error) (read-lines-from-file file))) (defun read-fields-from-file (file) (loop for line = (read-line file nil 'eof) until (equal line 'eof) collecting (line->fields line))) (defun line->fields (line) (labels ((rec (stream acc) (handler-case (rec stream (cons (read stream) acc)) (error nil (nreverse acc))))) (with-input-from-string (s line) (rec s nil)))) (defun read-fields-from-pathname (pathname) (with-open-file (infile pathname :direction :input :if-does-not-exist :error) (read-fields-from-file infile)))
1,910
Common Lisp
.lisp
49
32.55102
70
0.628032
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
76ac5c79c2bec4200b227aa37201a7dd5401a2e45224d7d510cd2fa8ced71732
1,710
[ -1 ]
1,711
package.lisp
ghollisjr_cl-ana/csv-table/package.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (defpackage #:cl-ana.csv-table (:use :cl-csv :iterate :cl :cl-ana.table) (:export :csv-table :create-csv-table :open-csv-table ;; function for converting easily from raw strings: :smart-read-from-string))
1,130
Common Lisp
.lisp
30
34.766667
70
0.686988
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
b1f844f9fde31bdcf830c8425decd387ae12aaf2fae236501c2e395abda289a0
1,711
[ -1 ]
1,712
csv-table.lisp
ghollisjr_cl-ana/csv-table/csv-table.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; Copyright 2019 Katherine Cox-Buday ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (in-package :cl-ana.csv-table) (defclass csv-table (table) ((file :initarg :file :initform nil :accessor csv-table-file :documentation "The CSV file.") (delimeter :initarg :delimeter :initform #\, :accessor csv-table-delimeter :documentation "The delimeter denoting a new field; defaults to a comma.") (row :initarg :row :initform nil :accessor csv-table-row :documentation "hash table mapping field-symbols to values") (field-symbols :initarg :field-symbols :initform () :accessor csv-table-field-symbols :documentation "Storing the lispified field symbols for efficiency.") (read-from-string :initarg :read-from-string :initform nil :accessor csv-table-read-from-string :documentation "If nil, values will be read from the CSV as strings and not interpreted; if non-nil, table-load-next-row will attempt to read a Lisp value from each field."))) (defun open-csv-table (filename &key (read-from-string nil) (delimeter #\,) field-names) "Open a CSV file to be read as a table. Assumes that the first row consists of the field names and are separated by the delimeter unless field-names keyword argument is given." (let* ((file (open filename :direction :input)) (row (make-hash-table :test #'equal)) (table (make-instance 'csv-table :field-names (if field-names field-names (first (read-csv (read-line file) :separator delimeter))) :file file :delimeter delimeter :row row :read-from-string read-from-string :access-mode :read))) (setf (csv-table-field-symbols table) (table-field-symbols table)) table)) ;;; Reading methods: (defun smart-read-from-string (s) (handler-case (multiple-value-bind (read-value read-index) (read-from-string s nil nil) ;; If we don't read the entire string like we expect to, assume ;; the field is a string and return the entire thing. (if (equal (length s) read-index) read-value s)) (error nil s))) (defmethod table-load-next-row ((table csv-table)) (with-accessors ((file csv-table-file) (field-symbols csv-table-field-symbols) (delimeter csv-table-delimeter) (row csv-table-row) (read-from-string csv-table-read-from-string)) table (let* ((reader (if read-from-string #'smart-read-from-string #'identity)) (line (read-line file nil nil)) (csv-data (when line (mapcar reader (first (read-csv line :separator delimeter)))))) (when line (iter (for s in field-symbols) (for v in csv-data) (setf (gethash s row) v)) t)))) (defmethod table-get-field ((table csv-table) field-symbol) (with-accessors ((row csv-table-row)) table (gethash field-symbol row))) ;;; Writing functions: (defun create-csv-table (filename field-names &optional (delimeter #\,)) "Creates a CSV file to be written to as a table." (let ((*print-pretty* nil)) (let* ((file (open filename :direction :output :if-exists :supersede :if-does-not-exist :create)) (row (make-hash-table :test #'equal)) (table (make-instance 'csv-table :field-names field-names :file file :delimeter delimeter :row row :access-mode :write))) (setf (csv-table-field-symbols table) (table-field-symbols table)) (iter (for i upfrom 0) (for n in field-names) (when (not (= i 0)) (format file "~a" delimeter)) (format file "~a" n)) (format file "~%") table))) (defmethod table-set-field ((table csv-table) field-symbol value) (with-accessors ((row csv-table-row)) table (setf (gethash field-symbol row) value))) (defmethod table-commit-row ((table csv-table)) (let ((*print-pretty* nil)) (with-accessors ((file csv-table-file) (row csv-table-row) (field-symbols csv-table-field-symbols) (delimeter csv-table-delimeter)) table (loop for i upfrom 0 for key in field-symbols do (progn (when (not (= i 0)) (format file "~a" delimeter)) (format file "~a" (gethash key row)))) (format file "~%")))) (defmethod table-close ((table csv-table)) (with-accessors ((file csv-table-file)) table (close file)))
5,994
Common Lisp
.lisp
158
28.588608
72
0.582074
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
0bb70cd775678c695b4faa5672c2fd73a32bad0b8c867c755a53b172ea3696e1
1,712
[ -1 ]
1,713
test.lisp
ghollisjr_cl-ana/csv-table/test.lisp
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (require 'cl-ana.csv-table) (in-package :cl-ana.csv-table) (defparameter *table* (create-csv-table "/home/ghollisjr/test.csv" (list "x" "y"))) (table-push-fields *table* ("x" 1) ("y" 2)) (table-set-field *table* :|x| 3) (table-set-field *table* :|y| 4) (table-commit-row *table*) (table-set-field *table* :|x| 5) (table-set-field *table* :|y| 6) (table-commit-row *table*) (table-close *table*) (setf *table* (open-csv-table "/home/ghollisjr/test.csv")) (do-table (row-index *table*) ("x" "y") (print |x|) (print |y|)) (table-close *table*)
1,450
Common Lisp
.lisp
43
31.767442
70
0.679771
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
0ab6f2ac185a97b47d639eb02b526c87b8900d9ec54a2148855ef96d041d7d03
1,713
[ -1 ]
1,714
cl-ana.asd
ghollisjr_cl-ana/cl-ana.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana :serial t :author "Gary Hollis" :description "cl-ana is a free (GPL) data analysis library in Common Lisp providing tabular & binned data analysis along with nonlinear least squares fitting & visualization." :license "GPLv3" :depends-on (#:cl-ana.pathname-utils #:cl-ana.package-utils #:cl-ana.generic-math #:cl-ana.math-functions #:cl-ana.calculus #:cl-ana.binary-tree #:cl-ana.list-utils #:cl-ana.array-utils ;; Make sure to place tensor after defining all gmath ;; generic functions #:cl-ana.tensor #:cl-ana.error-propogation #:cl-ana.quantity #:cl-ana.spline #:cl-ana.table #:cl-ana.table-utils #:cl-ana.hdf-table #:cl-ana.ntuple-table #:cl-ana.csv-table #:cl-ana.reusable-table #:cl-ana.linear-algebra #:cl-ana.lorentz #:cl-ana.histogram #:cl-ana.fitting #:cl-ana.file-utils #:cl-ana.statistics #:cl-ana.statistical-learning #:cl-ana.plotting #:cl-ana.table-viewing #:cl-ana.int-char #:cl-ana.clos-utils #:cl-ana.serialization #:cl-ana.hash-table-utils #:cl-ana.map ;; makeres #:cl-ana.makeres #:cl-ana.makeres-macro #:cl-ana.makeres-block #:cl-ana.makeres-progress #:cl-ana.makeres-table #:cl-ana.makeres-graphviz #:cl-ana.makeres-branch #:cl-ana.makeres-utils #:cl-ana.columnar-table) :components ((:file "package")))
2,778
Common Lisp
.asd
72
28.402778
70
0.564302
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
acbf101024dcabf72cd24c72143b814145ef2a65e1bee1fbf3bac1ef3f9a5ad5
1,714
[ -1 ]
1,715
cl-ana.string-utils.asd
ghollisjr_cl-ana/string-utils/cl-ana.string-utils.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; string-utils.asd (asdf:defsystem #:cl-ana.string-utils :serial t :description "String utilities not already provided by Alexandria" :author "Gary Hollis" :license "GPLv3" :depends-on (#:split-sequence) :components ((:file "package") (:file "string-utils")))
1,156
Common Lisp
.asd
29
38
70
0.707815
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
c9d0f2f51b0149a07510c1ecc9bf791221fbd5811d99f5f8ed2f3e8830a0a5aa
1,715
[ -1 ]
1,716
cl-ana.functional-utils.asd
ghollisjr_cl-ana/functional-utils/cl-ana.functional-utils.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.functional-utils :serial t :author "Gary Hollis" :description "Utilities for doing functional programming not already provided by Alexandria." :license "GPLv3" :depends-on () :components ((:file "package") (:file "functional-utils")))
1,155
Common Lisp
.asd
29
37.896552
70
0.712
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
dc4e735fa314ffcd88b41e42c77b9a52bb3d45bb8ebd65cf97619d7b68445e06
1,716
[ -1 ]
1,717
cl-ana.makeres-progress.asd
ghollisjr_cl-ana/makeres-progress/cl-ana.makeres-progress.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.makeres-progress :serial t :author "Gary Hollis" :description "makeres-progress is a graph transformation for use with makeres" :license "GPLv3" :depends-on (#:cl-ana.makeres #:cl-ana.generic-math #:alexandria) :components ((:file "package") (:file "progresstrans")))
1,224
Common Lisp
.asd
31
36.419355
71
0.690436
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
247b677533345ebd9d4baccd48c1fbc36e7228ccc4a4f0095b0249bc875f7d3d
1,717
[ -1 ]
1,718
cl-ana.serialization.asd
ghollisjr_cl-ana/serialization/cl-ana.serialization.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.serialization :serial t :description "serialization provides functionality for writing various objects to HDF5 files as datasets (which is the only way with HDF5)." :author "Gary Hollis" :license "GPLv3" :depends-on (#:cl-ana.typespec #:cl-ana.histogram #:cl-ana.int-char #:cl-ana.error-propogation #:cl-ana.macro-utils #:cl-ana.hdf-utils #:cl-ana.hdf-table) :components ((:file "package") (:file "histogram")))
1,430
Common Lisp
.asd
36
35.25
70
0.667145
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
c97344099c8e237342ff2377b849b7725e392cc910ab432d65e0e41407672485
1,718
[ -1 ]
1,719
cl-ana.hdf-table.asd
ghollisjr_cl-ana/hdf-table/cl-ana.hdf-table.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; hdf-table.asd (asdf:defsystem #:cl-ana.hdf-table :serial t :description "Table subclass specializing on HDF5 datasets" :author "Gary Hollis" :license "GPLv3" :depends-on (#:cl-ana.list-utils #:cl-ana.hdf-utils #:cl-ana.table #:cl-ana.typed-table #:cl-ana.typespec #:cl-ana.hdf-typespec #:cl-ana.binary-tree #:cl-ana.memoization #:alexandria) :components ((:file "package") (:file "hdf-table") (:file "hdf-table-chain") ;; (:file "raw-hdf-table") ;; (:file "raw-hdf-table-chain") ))
1,504
Common Lisp
.asd
41
32.04878
70
0.645007
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
cafed0825dd9cd3c988f3a12cc8d62beb1a3cd63bb83c41af1b6d2f5c45cfa7b
1,719
[ -1 ]