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
9,228
end.lisp
azimut_shiny/compositions/drafts/end.lisp
(in-package :shiny) ;; Adding filters to output from fluidsynth. ;;---------------------------------------- ;; Due the output is single-float I cannot apply a filter directly ;; So i dump the channels to buses. Then use a second dsp to filter. ;; Trying to implement: ;; https://sourceforge.net/p/incudine/mailman/message/36266377/ (define-vug input-bus ((channel fixnum)) (bus (the fixnum (+ (the fixnum (* current-frame 2)) channel 2)))) (dsp! fluid-in ((synth fluidsynth:synth)) (with ((len (block-size)) (left (make-f32-array len)) (right (make-f32-array len))) (fluidsynth:write-float synth len left 0 1 right 0 1) (foreach-frame (dochannels (current-channel 2) (setf (input-bus current-channel) (f32-ref left current-frame) (input-bus current-channel) (f32-ref right current-frame)))))) (dsp! fluid-out (lpf hpf) (:defaults 0 0) (foreach-frame (foreach-channel (with-samples ((c (input-bus current-channel))) (maybe-expand c) (unless (= 0d0 lpf) (setf c (lpf c lpf 2))) (unless (= 0d0 hpf) (setf c (hpf c hpf 2))) (cout c))))) ;;-------------------------------------------------- (dsp! fluid-in-down ((synth fluidsynth:synth)) (with ((len (block-size)) (left (make-f32-array len)) (right (make-f32-array len))) (fluidsynth:write-float synth len left 0 1 right 0 1) (foreach-frame (dochannels (current-channel 2) (setf (bus 0) (f32-ref left current-frame) (bus 1) (f32-ref right current-frame)))))) (dsp! fluid-out-down () (foreach-frame (foreach-channel (with-samples ((c (bus current-channel))) (cout c))))) ;;-------------------------------------------------- (bbuffer-load "/home/sendai/glenn.wav") (incudine:free (node 0)) (bplay (gethash "glenn.wav" *buffers*) :rate 128 :amp .2) (fluidsynth:sfload *synth* "/home/sendai/Downloads/Nice-Keys-Suite-V1.0.sf2" 1) (defvar *synth2* (fluidsynth:new *settings*)) (fluidsynth:sfload *synth2* "/home/sendai/Downloads/sf2/CTK-230_SoundFont.sf2" 1) (defvar *synth3* (fluidsynth:new *settings*)) (fluidsynth:sfload *synth3* "/home/sendai/Downloads/KBH_Real_and_Swell_Choir.sf2" 1) (defun in-times (l f) (declare (function f) (list l)) (mapcar (lambda (x) (at (+ (now) #[x b]) f)) l)) (defun dall (class-name) (setf *actors* (delete-if (lambda (x) (string= class-name (class-name (class-of x)))) *actors*))) (defun ds (name) (declare (keyword name)) (setf *actors* (delete-if (lambda (x) (eq name (slot-value x 'name))) *actors*))) (defun cs (name &optional (buf (box)) (pos (v! 0 2 0)) (scale 1f0) (instance 'cement) (rot (q:identity)) ) (or (and (position-if (lambda (x) (equal name (slot-value x 'name))) *actors*) (ds name)) (push (make-instance instance :scale scale :buf buf :name name :pos pos :rot rot) *actors*))) (f (now)) (defparameter *fog* (make-line (alexandria:iota 23 :start 11 :step 3))) (defparameter *fog* (make-line (alexandria:iota 23 :start 76 :step -3))) (fpan 0 0) (fpan 1 0) (fp 3 2) (fp 4 32) (defun f ()) (f (now)) (defun hand (time) (if (odds .5) (p time (pc-random 70 90 (scale 0 'bartok)) (rcosr 30 6 5) 1 4)) (p time (pc-random 70 90 (scale 0 'bartok)) (rcosr 30 6 5) (cosr .5 .3 5) 4)) (dall "CEMENT") (let ((*synth* *synth2*)) (fpan 0 30) (fp 2 49) (fp 3 11)) (let* ((s (make-heap (ov-scale :C5 :bartok))) (c (make-heap s)) (flip (make-cycle '(t nil)))) (defun f (time) (let (;;(*synth* *synth2*) (fog (next *fog*))) (if (and (> fog 40) (odds .9)) (let ((n (pick 3 2 1))) (in-times (loop :for i :by .3333 :repeat n :collect i) (lambda () (cs (gensym) (sphere) (v! (1- (random 2f0)) 0 (1- (random 2f0))) (between .2 .6)))) (pa time (next c n) (rcosr (+ -40 fog) 5 5) .333 2 .333)))) (cs :d1 (box) (v! 0 0 0)) (when (zmodt 4) (dall "CEMENT")) (let ((fog (next *fog*))) (when (and (= 10 fog) (zmodt 3)) (setf *cam-vector* (v! (cync time) (sync time) (random 1f0))) (let ((*synth* *synth3*)) (p time 60 (+ (- (next *fog*)) (rcosr 30 5 5)) 1 3)))) (pa time '(60 60 61) '(55 50 50) '(.333 .1 .1) 0 .333) (unless (zmodt 6) (let ((*synth* *synth2*)) (p time 30 30 .3 0))) (aat (+ time #[1 b]) #'f it))) (set-controls (node 10) :lpf 900 :hpf 400) (set-controls (node 10) :lpf 50 :hpf 200) (defun f ()) (fp 1 5) (fg 1.5f0) (let ((*synth* *synth2*)) (fg 1.5f0)) (f (now)) (let ((*synth* *synth3*)) (fp 0 4 0)) (fluid-test *synth3*) (fp 0 0 0) (fg 2f0) (p (now) 50 50 1 0) (incudine:free (node 0)) (fluid-in *synth* :id 9) (fluid-out :id 10 :after 9) (fluid-test *synth2*) (fluid-in-down *synth2* :id 11) (fluid-out-down :id 12 :after 11) (let ((*synth* *synth2*)) (p (now) 50 50 1 1)) (defun f ()) (f (now)) (dsp! buffer-play-test ((buf buffer)) (with ((o (make-buffer (block-size)))) (declare (buffer o)) (foreach-frame (cout (buffer-play buf))))) (incudine:free (node 0)) (buffer-play-test (gethash "glenn.wav" *buffers*))
5,367
Common Lisp
.lisp
155
29.329032
107
0.5625
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
4a98cf090fc6903b8f0e3c08e103586ec5ebad5371bae8092941aea885304173
9,228
[ -1 ]
9,229
collider-draft.lisp
azimut_shiny/compositions/drafts/collider-draft.lisp
(in-package :sc-user) (setf *sc-plugin-paths* (list "/usr/lib/SuperCollider/plugins/" ;; "/usr/share/SuperCollider/Extensions/" )) (setf *sc-synth-program* "/usr/bin/scsynth") (setf *s* (make-external-server "localhost" :port 4444)) (server-boot *s*) (server-quit *s*) (in-package :shiny) (defparameter *synth* (play (sin-osc.ar 300 0 .2))) (cl-collider:free *synth*) (defsynth rhodey ((freq 440) (out 0) (gate 1) (pan 0) (amp 0.1) (vel .8) (mod-index .2) (mix .2) (lfo-speed .4) (lfo-depth .1)) (let* ((lfo-speed (* 12 lfo-speed)) (freq (* 2 freq)) (env1 (env-gen.ar (adsr .001 1.25 .0 .04 1.0))) (env2 (env-gen.ar (adsr .001 1.00 .0 .04 1.0))) (env3 (env-gen.ar (adsr .001 1.50 .0 .04 1.0))) (env4 (env-gen.ar (adsr .001 1.50 .0 .04 1.0))) (osc4 (* TWOPI 2 0.535887 mod-index env4 vel (sin-osc.ar (* freq .5)))) (osc3 (* env3 vel (sin-osc.ar freq osc4))) (osc2 (* TWOPI 0.108819 env2 vel (sin-osc.ar (* 15 freq)))) (osc1 (* env1 vel (sin-osc.ar freq osc2))) (snd (mix (+ (* osc1 mix) (* osc3 (- 1 mix))))) (snd (* snd (+ 1 (* lfo-depth (sin-osc.ar lfo-speed))))) (snd (* snd (env-gen.ar (asr 0 1 .1) :gate gate :act :free))) (snd (pan2.ar snd pan amp))) (out.ar out snd))) (synth 'rhodey :freq (midicps 62) :amp .5 :gate 1) (defmacro pa (time notes offset) `(let* ((other (cdr ,notes)) (offsets (loop :for o :from ,offset :by ,offset :collect o :repeat (length other)))) (at ,time (synth 'rhodey :freq (midicps (first ,notes)))) (loop :for p :in other :for d :in offsets :do (at (+ ,time d) (synth 'rhodey :freq (midicps p)))))) (pa (quant 4) '(90 80 60) 1) (defun f (time) (let ((next-time (+ time 4)) (mychord (make-chord 60 70 3 *phrygian*))) (at (+ 2 time) (synth 'rhodey :freq (midicps (+ -12 (first mychord))) :mix .4)) (pa time mychord .5) (callback next-time #'f next-time))) (defun f ()) (f (quant 4)) (defparameter *m* (synth 'rhodey)) (proxy :foo (sin-osc.ar 440 0 .4)) (proxy :foo (saw.ar 300 .2)) (proxy :foo (saw.ar (sin-osc.kr .5 0 150 300) .2)) (proxy :foo nil) (defsynth drum2 ((freq 3000)) (let* ((env (env-gen.kr (perc .001 .1) :act :free)) (sig (lpf.ar (white-noise.ar) (* freq env)))) (out.ar 0 (pan2.ar sig 0 .2)))) (drum 3000) (named-readtables:in-readtable :sc) (defsynth saw-synth ((note 60) (dur 4.0)) (let* ((env (env-gen.kr (env [0 .2 0] [(* dur .2) (* dur .8)]) :act :free)) (freq (midicps note)) (sig (lpf.ar (saw.ar freq env) (* freq 2)))) (out.ar 0 [sig sig]))) (defun make-melody (time n &optional (offset 0)) (when (> n 0) (at time (synth 'saw-synth :note (+ offset (alexandria:random-elt '(62 65 69 72))))) (let ((next-time (+ time (alexandria:random-elt '(0 1 2 1.5))))) (callback next-time #'make-melody next-time (- n 1) offset) ))) (make-melody (quant 4) 16) (defsynth saw-synth ((note 60) (dur 4.0)) (let* ((env (env-gen.kr (env [0 .2 0] [(* dur .2) (* dur .8)]) :act :free)) (freq (midicps note)) (sig (lpf.ar (saw.ar freq env) (* freq 2)))) (out.ar 0 [sig sig]))) (in-package :sc-user) (defsynth saw-synth ((note 60) (dur 4.0)) (let* ((env (env-gen.kr (env [0 .2 0] [(* dur .2) (* dur .8)]) :act :free)) (freq (midicps note)) (sig (lpf.ar (saw.ar freq env) (* freq 2)))) (out.ar 0 [sig sig])))
3,573
Common Lisp
.lisp
86
35.639535
88
0.549076
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
1415625e30b9cdad29581b86c41f1242d91fee82c982a77f44cb3df19e80735e
9,229
[ -1 ]
9,230
esmerald.lisp
azimut_shiny/compositions/drafts/esmerald.lisp
(in-package :shiny) ;; https://musescore.com/user/17725126/scores/4265161 (setf (bpm *tempo*) 120) (progn (defparameter *mf* "/home/sendai/Downloads/Layers_of_Fear.mid") (defparameter *notes* (subseq (get-measures-pair *mf* 0 8) 4)) (defparameter *bass* (subseq (get-measures-pair *mf* 1 8) 4)) (defparameter *quarter* (first (get-midi-tempo *mf*)))) (alsaseq-start) (alsaseq-pgmchange 1 44) (alsaseq-pgmchange 2 28) (let ((nd (make-cycle (subseq (get-measures-pair *mf* 0 12) 0))) (outer (make-cycle '(1f0 4f0)))) (defun p3 (time) (destructuring-bind (ns ds) (next nd) (mapcar (op (play-midi-note time (+ -12 _) 120 _ 1) (when (not (= 0 _1)) (setf (incandescent::pos incandescent::*camera*) (incandescent::v! (serapeum:random-in-range -10f0 10f0) (serapeum:random-in-range -10f0 10f0) (serapeum:random-in-range -10f0 10f0))) (setf (incandescent::rot incandescent::*camera*) (q:point-at (rtg-math:v! 0 1 0) (incandescent::pos incandescent::*camera*) (rtg-math:v! 0 0 0))) (setf incandescent::*outer* (next outer)))) (reverse ns) (reverse ds)) (aat (+ time #[(reduce #'max ds) b]) #'p3 it)))) (aat (tempo-sync #[1 b]) #'p3 it) (defun p3 ()) (let ((inner (make-cycle '(1f0 2f0 3f0 4f0)))) (defmethod play-midi-note :around (time pitch velocity duration channel) (when (= channel 0) (setf incandescent::*inner* (next inner))) (call-next-method))) (let ((bass-notes (make-cycle (car (car *bass*)))) (bass-durs (make-cycle (cdr (car *bass*))))) (defun p2 (time) ;;#+nil (let* ((bn (ensure-list (next bass-notes))) (d (/ 1 (length bn)))) (play-midi-arp time bn 90 d 0 d)) ;;#+nil (mapcar (lambda (slot) (destructuring-bind (n d) slot (mapcar (op (play-midi-note time _ (rcosr 45 10 4) _ 2)) n d))) (next *notes*)) (aat (+ time #[1 b]) #'p2 it))) (aat (tempo-sync #[1 b]) #'p2 it) (defun p2 ())
2,313
Common Lisp
.lisp
53
32.943396
83
0.519769
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
dee8b2d90c67c5e86bef3c05f19b2b471c927ed92eacadf1b3064858a5eb293d
9,230
[ -1 ]
9,231
extempore-tutorial.lisp
azimut_shiny/compositions/drafts/extempore-tutorial.lisp
;; -------------------------------- ;; extepore tutorial ;; cycle with two callbacks (defun ext (time notes) (play-midi-note time (car notes) 40 1 1) (if (null (cdr notes)) (aat (+ time #[1 b]) #'ext it '(60 62 65)) (aat (+ time #[1 b]) #'ext it (cdr notes)))) (ext (now) '(60 62 65) ) #| (flush-pending) (off-with-the-notes *synth*) |# ;; -------------------------------- ;; extepore tutorial ;; cycle with two callbacks ;; spicing it up with pick, but the gist is that if defined like this ;; we can change the things "dynamicly" without recurring to globs (defun ext (time notes) (play-midi-note time (car notes) 40 1 1) (if (null (cdr notes)) ;; (aat (+ time #[1 b]) #'ext it `(60 62 ,(cm:pick 65 67))) (aat (+ time #[1 b]) #'ext it (cm:pick '(60 62 65) '(60 62 67) '(60 62 67 69) )) (aat (+ time #[1 b]) #'ext it (cdr notes)))) (ext (now) '(60 62 65) ) (setf (bpm *tempo*) 60) (defun exte (chan time notes rhythms) (play-midi-note time (car notes) 40 (car rhythms) 1) (aat (+ time #[(car rhythms) b]) #'exte chan it (if (null (cdr notes)) '(60 62 65 69 67) (cdr notes)) (if (null (cdr rhythms)) '(1/4 1/4 1/2 1/4) (cdr rhythms)))) (exte 1 (tempo-sync #[1 b]) '(60 62 65 69 67) '(1/4 1/4 1/2 1/4)) (exte 2 (tempo-sync #[.75 b]) '(60 62 65 69 67) '(1/4 1/4 1/2 1/4)) ; Pick 2 random number from the list-lispy ;(loop :for x :below 2 :collect (cm:pickl '(60 45 63))) (defun extem (chan time notes rhythms) (play-midi-note time (car notes) 40 (car rhythms) chan) (aat (+ time #[(car rhythms) b]) #'extem chan it (if (null (cdr notes)) (loop :for x :below 4 :collect (cm:pickl '(60 62 64 67 69))) (cdr notes)) (if (null (cdr rhythms)) '(1/4 1/4 1/4 1/4) (cdr rhythms)))) (extem 2 (now) '(60 62 64 67) '(1/4)) (defun extemp (chan time notes rhythms) ; (print (+ 60 (* 50 (cos (* 3.141592 0.0315 time))))) (play-midi-note time (car notes) ;; (abs (round (+ 1 (* 40 (cos (* 3.141592 0.0315 (get-internal-real-time))))))) ;; (abs (round (+ 1 (* 40 (cos (* 3.141592 0.0315 (get-universal-time))))))) (round (cosr 30 10 .6)) (car rhythms) chan) (aat (+ time #[(car rhythms) b]) #'extemp chan it (if (null (cdr notes)) (loop :for x :below 4 :collect (cm:pickl '(60 62 64 67 69))) (cdr notes)) (if (null (cdr rhythms)) '(1/4 1/4 1/4 1/4) (cdr rhythms)))) (extemp 2 (now) '(60 62 64 67) '(1/4)) (extemp 3 (now) '(60 62 64 67) '(1/2)) #| (flush-pending) (off-with-the-notes *synth*) |# ;;; ---------------------------------- ;; Extempore tutorial - Pitch classes ;;; ---------------------------------- ;; Proofs that we cannot always transpose ;; things by adding (pc:? 60 '(0 4 7)) (pc:? 84 '(0 4 7)) (pc:? 35 '(0 4 7)) (pc:? 79 '(0 4 7)) (print (ispitch 60 '(0 4 7))) ;T (print (ispitch 84 '(0 4 7))) ;T (print (ispitch 35 '(0 4 7))) ;NIL (print (ispitch 79 '(0 4 7))) ;T ;; --- ;; this chooses a C in any octave (print (pcrrandom 0 127 '(0))) ;; this chooses any note from a D minor chord in octave 4 (print (pcrrandom 60 73 '(2 5 7))) ;; this chooses any note from a C pentatonic octaves 3-6 (print (pcrrandom 48 97 '(0 2 4 7 9))) ;; --- (print (mapcar (lambda (p) (ispitch (+ p 7) '(0 2 4 5 7 9 11))) '(60 62 64 65 67 69 71))) (print (mapcar (lambda (p) (ispitch (+ p 5) '(0 2 4 5 7 9 11))) '(60 62 64 65 67 69 71))) (print (mapcar (lambda (p) (ispitch (+ p 4) '(0 2 4 5 7 9 11))) '(60 62 64 65 67 69 71))) ;; --- (print (relative 60 1 '(0 2 4 5 7 9 11))); 62 (print (relative 60 4 '(0 2 4 5 7 9 11))); 67 (print (relative 67 0 '(0 2 4 5 7 9 11))); 67 (print (relative 60 -2 '(0 2 4 5 7 9 11))); 57 ;; ------------------- ;; define a melody (defvar *melody* nil) (setf *melody* (loop :for x :from 1 :to 24 :collect (pcrrandom 60 83 '(0 2 4 5 7 9 11)))) ;; Doc: Scheme's named-loops (aka let-loop) can be written with ;; Lisp's do loops ;; https://stackoverflow.com/questions/30178852/is-there-a-style-convention-for-common-lisp-recursive-helper-functions ;; define a random walk melody seeded with 60 ;; (we remove this at the end with cdr) ;; "random walk" (setf *melody* (do ((i 0 (1+ i)) (lst '(60) (cons (relative (car lst) (cm:pick -1 1) '(0 2 4 5 7 9 11)) lst))) ((>= i 24)(cdr (reverse lst))))) (setf *melody* (do ((i 0 (1+ i)) (lst '(60) (cons (relative (car lst) (cm:pick -2 -1 1 2 3) '(0 2 4 5 7 9 11)) lst))) ((>= i 24)(cdr (reverse lst))))) ;; define harmony up a perfect 5th (4 places away in the pitch class set) (defvar *harmony* nil) (setf *harmony* (mapcar (lambda (p) (relative p 4 '(0 2 4 5 7 9 11))) *melody*)) ;; set c at start and end (setf *melody* (cons 60 *melody*)) (setf *harmony* (cons 60 *harmony*)) (setf *melody* (reverse (cons 60 (reverse *melody*)))) (setf *harmony* (reverse (cons 60 (reverse *harmony*)))) ;; random rhythm (defvar *rhythm* nil) (setf *rhythm* (loop :for x :from 1 :to 24 :collect (cm:pick 1/2 1))) ;; set long start and end to rhythm (setf *rhythm* (cons 2 *rhythm*)) (setf *rhythm* (reverse (cons 2 (reverse *rhythm*)))) (defun organum (time melody harmony rhythm) (play-midi-note time (car melody) 30 (car rhythm) 1) (play-midi-note time (car harmony) 30 (car rhythm) 2) (if (not (null (cdr melody))) (aat (+ time #[(car rhythm) b]) #'organum it (cdr melody) (cdr harmony) (cdr rhythm)))) ;; start (fluidsynth:program-change *synth* 1 77) (fluidsynth:program-change *synth* 2 77) (organum (now) *melody* *harmony* *rhythm*) ;;; ----------------------------------------- ;; Extempore tutorial - Making chords with PC ;;; ----------------------------------------- (defun crazy-chord (time) (play-midi-note time (pcrrandom 24 97 '(0 4 7 10 2 3 5 9 6 11 1)) 40 .3 1) (aat (+ time #[.3 b]) #'crazy-chord it)) (defun crazy-chord (time) (play-midi-note time (pcrrandom 24 97 '(0 4 7 10)) 40 .3 1) (aat (+ time #[.3 b]) #'crazy-chord it)) (crazy-chord (now)) ; C-major and repeat (defun chords (time) (mapcar (lambda (x) (play-midi-note time x 30 1 1)) (make-chord 60 72 3 '(0 4 7))) (aat (+ time #[1 b]) #'chords it)) (chords (now)) ;; I IV V ;; I-C IV-F V-E (defun chords (time chord) (mapcar (lambda (x) (play-midi-note time x 30 1 1)) (make-chord 48 90 3 chord)) (aat (+ time #[1 b]) #'chords it (if (> (random 1.0) .8) (cm:pick '(0 4 7) '(5 9 0) '(7 11 2)) chord))) (chords (now) '(0 4 7)) ;; ------------------------------ ;; Extempore tutorial - Harmony ;; ------------------------------ ;; markov chord progression I IV V (defun exhar (time pc) (mapcar (lambda (n c) (play-midi-note time n 30 1 c)) (make-chord 60 73 3 (cm:pickl (cdr (assoc pc '(((0 4 7) (5 9 0) (7 11 2)) ((5 9 0) (7 11 2)(0 4 7)) ((7 11 2)(0 4 7))) :test #'equal)))) '(1 2 0)) (aat (+ time #[1 b]) #'exhar it pc)) (exhar (now) '(0 4 7)) ;; markov chord progression I ii iii IV V vi vii (defun progression (time degree) (mapcar (lambda (x) (play-midi-note time x 30 1 (random 20))) (make-chord 48 77 5 (diatonic 0 '^ degree))) (aat (+ time #[1 b]) #'progression it (cm:pickl (cdr (assoc degree '((i iv v iii vi) (ii v vii) (iii vi) (iv v ii vii i) (v i vi) (vii v i) (vi ii))))))) (progression (now) 'i) #| (define play-note-mord (lambda (time inst pitch vol duration pc) (play-note (- time 5000) inst pitch (- vol 10) 2500) (play-note (- time 2500) inst (pc:relative pitch 1 pc) (- vol 10) 2500) (play-note time inst pitch vol (- duration 5000)))) |# ;; mordant (defun play-note-mord (time pitch vol dur pc chan) (play-midi-note (- time #[1/4 b]) pitch (- vol 10) (/ dur 2) chan) (play-midi-note (- time #[1/8 b]) (relative pitch 1 pc) (- vol 10) (/ dur 2) chan) (play-midi-note time pitch vol dur chan)) ;; markov chord progression I ii iii IV V vi vii (defun progression (time degree) (let ((dur (if (member degree '(i iv)) 2 1))) (mapcar (lambda (x c) (if (and (> x 70) (> (random 1.0) .7)) (play-note-mord time x (cm:pick 30 40) (* .9 dur) '(0 2 4 5 7 9 11)) (play-midi-note time x (cm:pick 30 40) (* .9 dur) c))) (make-chord 40 78 4 (diatonic 0 '^ degree)) '(6 7 8 9)) (aat (+ time #[(* .9 dur) b]) #'progression (+ time #[dur b]) (cm:pickl (cdr (assoc degree '((i iv v iii vi) (ii v vii) (iii vi) (iv v ii vii i) (v i vi) (vii v i) (vi ii)))))))) (progression (now) 'i) (fluidsynth:program-change *synth* 0 78) (flush-pending) ;;; ------------------------- ;; Extempore tutorial - Beats ;;; ------------------------- (fluidsynth:program-change *synth* 2 1) (defun drum-loop2 (time dur) (play-midi-note time 40 50 dur 2) (aat (+ time #[(* .5 dur) b]) #'drum-loop2 (+ time #[dur b]) (cm:pick 1.25 1.75))) (drum-loop2 (tempo-sync #[1 b]) 3/4) ;; beat loop at 120bpm (defun drump-loop (time dur) (play-midi-note time 40 50 dur 1) (aat (+ time #[dur b]) #'drump-loop (+ time #[dur b]) (cm:pick 1/3 1/2 1/4) )) (drum-loop (now) 1/4) (defvar *metro* nil) (setf *metro* (make-metro 120)) ;; (funcall *metro* 'get-beat 4) ;; 88 -- BEAT ;; (funcall *metro* 88) ;; 2.88797696d8 -- GLOBAL SAMPLES ;; (funcall *metro* 'dur 1) ;; 57600 -- N SAMPLES (defun drum-loop (time duration pitch pc) (p (now) (round (qcosr pc pitch 5 .9)) 40 .4 ;; (funcall *metro* 'dur duration) 1) (print "la") (aat (funcall *metro* (+ time duration)) #'drum-loop (+ time duration) duration pitch pc)) (fp 1 20) ;;(p (quant 4) 60 60 1 1) (defun drum-loop ()) (drum-loop (funcall *metro* 'get-beat 4) 1 40 '(0 4 7)) ;;(drum-loop (funcall *metro* 'get-beat 4) .75 50 '(0 4 7 9)) (defun tempo-shift (time) (funcall *metro* 'set-tempo (+ 60 (* 40 (cos (* .25 3.141592 time))))) ;; (aat (funcall *metro* (+ time .25)) #'tempo-shift (+ time .25)) ) (tempo-shift (funcall *metro* 'get-beat 1.0)) (funcall *metro* 'set-tempo 100) ;; -- (defvar *metre* nil) (setf *metre* (make-metre '(2 3 2) 0.5)) (fp 5 80) (defun metre-test (time) (if (funcall *metre* time 1.0) (p time 60 30 .4 5)) (print "la") (aat (funcall *metro* (+ time .5)) #'metre-test (+ time .5) ) ) (defun metre-test ()) (metre-test (funcall *metro* 'get-beat 1.0)) ;; --------- (defvar *metre1* nil) (defvar *metre2* nil) (setf *metre1* (make-metre '(3) .5)) ;; 3/8 (setf *metre2* (make-metre '(2) .5)) ;; 2/8 (flush-pending) (defun metre-test ()) (defun metre-test (time) (if (funcall *metre1* time 1.0) (p (funcall *metro* time) 50 30 .5 1)) (if (funcall *metre2* time 1.0) (p (funcall *metro* time) 60 35 .5 2)) (aat (funcall *metro* (+ time .5)) #'metre-test (+ time .5))) (metre-test (funcall *metro* 'get-beat 1.0)) ;; --------- (setf *metre1* (make-metre '(2 3 4 3 2) .5)) (setf *metre2* (make-metre '(3 5 7 5 3) .5)) (defvar *p1* nil) (setf *p1* (cm:new cm:weighting :of '((70 :weight .8) (60 :weight .2)))) (defun metre-test (time) (p (funcall *metro* time) (cm:next *p1*) 30 1 3) (if (funcall *metre1* time 1.0) (p (funcall *metro* time) 53 40 1 2)) (if (funcall *metre2* time 2.0) (p (funcall *metro* time) 70 30 1 2)) (aat (funcall *metro* (+ time .25)) #'metre-test (+ time .25) ) ) (metre-test (funcall *metro* 'get-beat 4)) (defun metre-test ()) (play-midi-note (now) 60 60 1 0) (fg 2f0) (defun metre-test (time) (play-midi-note (funcall *metro* time) (cm:next (cm:new cm:weighting :of `((,*gm-closed-hi-hat* :weight .8) (,*gm-open-hi-hat* :weight .2)))) 40 (cm:next (cm:new cm:weighting :of '((.5 :weight .8) (.25 :weight .2)))) 1) (if (funcall *metre1* time 1.0) (progn (play-midi-note (funcall *metro* time) *gm-snare* 20 .5 2) (play-midi-note (funcall *metro* time) *gm-pedal-hi-hat* 20 1 3) )) (if (funcall *metre2* time 1.0) (progn (play-midi-note (funcall *metro* time) *gm-kick* 20 1 4) (play-midi-note (funcall *metro* time) *gm-ride-bell* 30 1 5) )) (at (funcall *metro* (+ time .25)) #'metre-test (+ time .25) ))
14,669
Common Lisp
.lisp
371
29.84097
149
0.474599
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
80cb60a4d212a5fe93e7398ae78674cde95d602bffd4f117c44f1e45f3575b92
9,231
[ -1 ]
9,232
8bitmusictheory.lisp
azimut_shiny/compositions/drafts/8bitmusictheory.lisp
(in-package :shiny) ;; https://www.youtube.com/watch?v=5zGqN1ZOEJQ ;; Gbmaj13 - Fm9 ;; Dm9 - Abm6
99
Common Lisp
.lisp
4
23.5
46
0.702128
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
a6aba4fbbfba71c551d23882d79bd5324608711a4dbcac616439b4d9f97d1e95
9,232
[ -1 ]
9,233
dsp-tests.lisp
azimut_shiny/compositions/drafts/dsp-tests.lisp
(in-package :shiny) (defun f ()) (f (now)) (let ((c (make-cycle (make-chord-fixed 50 3 (scale 0 'minor))))) (defun f (time) (prophet :amp .3 :freq (midihz (next c))) (aat (+ time #[1 b]) #'f it))) (prophet :amp .3) ;;-------------------------------------------------- (defun f ()) (let ((maj (new weighting :of (list (list (list (cm:keynum :d3)) :weight .5) (list (ov-scale :d3 :major) :weight .2)))) (min (new weighting :of (list (list (list (cm:keynum :b4)) :weight .9 :max 2) (list (ov-scale :b4 :minor) :weight .2)))) (flip (make-cycle '(nil t)))) (defun f (time) (prophet :dur .6 :amp .3 :freq (midihz (pickl (next maj)))) (when (next flip) (square :dur (cosr 1 .1 1) :amp .08 :freq (midihz (pickl (next min))))) (aat (+ time #[.5 b]) #'f it))) (defun at-times (time time-offsets &rest args) (declare (double-float time) (list time-offsets) (optimize (speed 3))) (mapcar (lambda (x) (apply #'at (+ time (* *SAMPLE-RATE* (* (SAMPLE x) (SPB *TEMPO*)))) args)) time-offsets)) (defun counter-melody (time d) (square :amp .2 :freq (midihz (pc-relative (first d) -3 (scale 0 'lydian)))) (at (+ time #[.5 b]) #'square :amp .5 :freq (midihz (pc-relative (second d) -5 (scale 0 'lydian)))) (at (+ time #[1 b]) #'square :amp .4 :freq (midihz (pc-relative (first d) -4 (scale 0 'lydian)))) ;;(at (+ time #[1 b]) (lambda () (setf *distance* (drunk *distance* 1f0 :low 0f0 :high 2f0)))) ) (defun extended-melody (time d) (at (+ time #[(pick 1 .75) b]) #'dsp-pulse :amp .2 :dur .6 :freq (midihz (pc-relative (third d) (odds .5 -1 1) (scale 0 'lydian))) :cutoff-freq (cosr 700 200 3)) (at (+ time #[1.25 b]) #'square :amp .1 :dur .4 :freq (midihz (+ 12 (first d))) ;;:cutoff-freq (cosr 700 200 3) )) (defparameter *line-xp* (make-line (iota 40 :start .05 :step .05))) (setf *distance* 0f0) (defun f ()) (f (now)) (let ((s (make-palindrome (nths '(0 2 4) (ov-scale :c5 :lydian))))) (defun f (time) (setf *exposure* (next *line-xp*)) (let ((c (make-chord 50 60 3 (rotate (scale 0 'ionian) 0)))) (mapcar (lambda (x) (square :dur 1.5 :amp .7 :freq (midihz x))) c) (at-times time '(1 1.25) #'prophet :dur .5 :amp .5 :freq (midihz (third c))) (at (+ time #[.5 b]) #'prophet :dur .5 :amp .5 :freq (midihz (first c))) (let (;;(d (pc-invert (next s 5) (scale 0 'lydian) )) (d (next s 5)) ) ;;(green :dur (odds .6 1.5 1) :freq (midihz (pc-random 90 100 (scale 0 'lydian)))) (dsp-pulse :amp .2 :freq (midihz (first d)) :cutoff-freq (cosr 700 200 3)) (setf *offset* (random 1f0)) ;;(counter-melody time d) (extended-melody time d) (at (+ time #[(pick 1 .5 .75) b]) #'dsp-pulse :amp .1 :dur .6 :freq (midihz (pc-relative (second d) (odds .5 -1 1) (scale 0 'lydian))) :cutoff-freq (cosr 700 200 3)))) (aat (+ time #[1.5 b]) #'f it))) (defun f ()) (incudine:free (node 0))
3,495
Common Lisp
.lisp
85
31.329412
96
0.475574
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
9ff0f31a6257f0c63bf0b76828b439b7266983012ee78c5a90381b863ccb1627
9,233
[ -1 ]
9,234
drums.lisp
azimut_shiny/compositions/drafts/drums.lisp
(in-package :shiny) (defun kick ()) (defun kick2 ()) (defun kick3 ()) (kick (tempo-sync #[1 b])) (kick2 (tempo-sync #[.5 b])) (kick3 (tempo-sync #[.5 b])) (let ((notes (make-cycle (make-chord 60 70 6 (scale 0 'minor))))) (defbeat kick ((parse-pattern (bjorklund-s 5 13)) 1) (p time (next notes) 50 (* 2 d) 0))) (let ((notes (make-cycle (make-chord 50 60 1 (scale 0 'minor))))) (defbeat kick2 ((parse-pattern (bjorklund-s 4 4)) 1) (p time (next notes) 50 d 2))) (let ((notes (make-cycle (reverse (make-chord 60 70 6 (scale 0 'minor)))))) (defbeat kick3 ((parse-pattern (bjorklund-s 3 8)) .5) (p time (next notes) 50 (cosr .45 .1 4) 3))) (fg .5) (fp 3 30) (fp 2 44) (fp 0 20) (freverb-toggle 1) (freverb-preset 6) ;;-------------------------------------------------- (let ((bd (make-cycle (bd (get-pattern 'getup)))) (sn (make-cycle (sn (get-pattern 'getup)))) (ch (make-cycle (ch (get-pattern 'getup)))) (oh (make-cycle (oh (get-pattern 'getup))))) (defun f (time) (when (next bd) (play-instrument 'drum *gm-kick* (pick .2 .35))) (when (next sn) (play-instrument 'drum *gm-snare* (pick .35 .4))) (when (next ch) (play-instrument 'drum *gm-closed-hi-hat* .35 (pick .3 .4))) (when (next oh) (play-instrument 'drum *gm-open-hi-hat* .35 .6 (pick 1 .9 1.3))) (aat (+ time #[.15 b]) #'f it))) (defun f ()) (f (now)) ;;-------------------------------------------------- (let (;;(p (parse-patternc "x-x- ---x")) (p (make-cycle (bd (get-pattern 'cold)))) (s (make-cycle (sn (get-pattern 'cold)))) (c (make-cycle (ch (get-pattern 'cold)))) (o (make-cycle (oh (get-pattern 'cold)))) (dur .1)) (defun drumplay (time) (when (next p) (play-instrument 'drum *gm-kick*)) (when (next s) (bbplay (gethash "snare_OH_FF_9.wav" *buffers*))) (when (next c) (play-instrument 'drum *gm-closed-hi-hat* :amp .5)) (when (next o) (play-instrument 'drum *gm-open-hi-hat* :amp .1 :dur .1)) (aat (+ time #[ (cosr .2 .1 1) b]) #'drumplay it))) (defun drumplay ()) (drumplay (now)) (defbeat kick ((bd (get-pattern 'funkyd)) .5) (play-instrument 'drum *gm-kick*)) (defun kick ()) (snare (tempo-sync #[1 b])) (let ((hh (make-cycle '(.25)))) (defpattern pat1 ((get-pattern 'wm) .25) (play-instrument 'drum *gm-kick* :dur .25) (play-instrument 'drum *gm-snare* :dur .25) ;; (play-instrument 'drum *gm-closed-hi-hat* :dur 1) (play-instrument 'drum *gm-open-hi-hat* :dur (next hh)) )) (defun pat1 ()) (pat1 (now))
2,556
Common Lisp
.lisp
68
33.911765
76
0.567382
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
dd7b510fd80fa01aee6473248160dc25fe7930801dfb78ecb9816ec38836197c
9,234
[ -1 ]
9,235
molecularmusicbox-generator.lisp
azimut_shiny/compositions/drafts/molecularmusicbox-generator.lisp
(in-package :shiny) ;;-------------------------------------------------- (mbox 4 32 :C 9 14.5 -14 14 (scale 0 'dorian)) (fg .4) (mbox-play 0 40 .5 1 0) (mbox-play 1 40 .5 1 0) (mbox-play 2 40 .5 1 0) (mbox-play 3 40 .5 1 0) (mbox-play 10 40 .5 1 0) (mbox-play 11 40 .5 1 0) (mbox-play 12 40 .5 1 0) (mbox-play 17 40 .5 1 0) (fp 1 40) (mbox-custom 9 .5 (if (odds .8) (p time (+ 12 note) 35 (* duration .45) 1) (pa time (pickn (pick 2 3) (make-chord-fixed (+ note 12) 3 (scale 0 'dorian))) (* duration .1) 35 1 (list (* duration .1) (* duration .1) (* duration .2)))) ) (mplay-9) (mplay-0) (mplay-1) (mplay-2) (mplay-3) (mplay-10) (mplay-11) (mplay-12) (mplay-17) ;;-------------------------------------------------- (all-piano 0) (mbox 4 32 :C 9 14.5 -14 14 (scale 0 'ryukyu)) (mplay-2) (defun %mplay-2 ()) (fp 11 78) (mbox-play 0 50 .5 1 1) (mbox-play 1 50 .5 1 1) (mbox-play 2 50 .5 1 1) (mbox-play 3 60 .5 1 1) (mbox-play 10 60 .5 .05 10) (mbox-play 11 60 .5 .05 11) (mbox-play 7 60 .5 1 1) ;;-------------------------------------------------- ;;; Name on soundcloud - "trash" (fp 0 4) (fp 1 0) (fp 5 2) (fp 9 80 0) (all-piano 80) (mbox 4 8 :C 3 5 -7 14 (scale 0 'lydian)) (mbox-play 3 40 .1 .1 0) (fg 1.0) (fp 0 13) (mplay-3) (defun %mplay-2 ()) (mbox-play 7 50 .2 . 1) ;;-------------------------------------------------- (fp 0 4) (fp 1 0) (fp 5 2) (fp 9 1 0) (all-piano 80) (mbox 4 8 :C 3 5 -7 14 (scale 0 'lydian)) (mbox-play 9 40 .2 .1 3) (fp 3 8) (mplay-1) (defun %mplay-8 ()) (mbox-play 7 50 .2 . 1) ;;-------------------------------------------------- ;; V: 1 2 , 3 , 12 13 (mbox 4 8 :C 3 7 -7 14 (scale 0 'ryukyu)) (mbox 4 8 :C 3 7 -7 14 (ov-pc-scale :scriabin)) (mbox 4 11 :C 3 7 -7 14 (ov-pc-scale :mixolydian)) (all-piano 0) (fpitch 10 10000) (fpitch 11 5000) (mplay-0) (mplay-1) (mplay-2) (mplay-3) (fg .7) (mbox-play 0 30 .2 .1 1) (mbox-play 1 30 .2 .1 1) (mbox-play 2 30 .2 .1 1) (mbox-play 3 60 .2 .1 1) (mbox-play 5 60 .2 .4 1) (mbox-play 10 60 .2 .4 10) (mbox-play 14 60 .2 .09 11) (mbox-play 8 60 .2 .2 1) (defun %mplay-6 m ()) (mplay-1) (mplay-10) (mplay-11) (mplay-3) (fp 30 0) (defun strin ()) (defun strin (time) (let ((r (pick .2 .4 1 1))) (and (odds .5) (p time (qcosr (ov-pc-scale :minor) 75 5 5) (rcosr 50 5 1/2) r 30) ) (aat (+ time r) #'strin it))) (strin (quant (* .2 8))) (mbox-play 0 40 .2 .1 1 (p time note p-volume (* duration p-note-duration-mul) p-channel)) (defun mplay ()) (destructuring-bind (notes durations channel beats) (nth 11 (reverse *p*)) (declare (ignore channel)) (mplay (quant 4) (make-cycle notes) (make-cycle durations) 2 (make-cycle beats) 60)) (destructuring-bind (notes durations channel beats) (nth 2 (reverse *p*)) (mplay (quant 4) (make-cycle notes) (make-cycle durations) 3 (make-cycle beats))) (destructuring-bind (notes durations channel beats) (nth 3 (reverse *p*)) (mplay (quant 4) (make-cycle notes) (make-cycle durations) 4 (make-cycle beats))) (fp 5 25) (freverb-toggle 1) (freverb-preset 2) (destructuring-bind (notes durations channel beats) (nth 14 (reverse *p*)) (mplay (quant 4) (make-cycle notes) (make-cycle durations) 5 (make-cycle beats))) (destructuring-bind (notes durations channel beats) (nth 8 (reverse *p*)) (mplay (quant 4) (make-cycle notes) (make-cycle durations) 6 (make-cycle beats))) (defparameter *metro* (make-metro 120)) (defun mplay ()) (defun mplay (time notes durations channel beats &optional (vol 60)) (let ((beat (next beats))) (when (= 1 beat) (let ((note (next notes)) (duration (next durations))) (p time note vol (/ duration 7) channel)))) (aat (+ time .2) #'mplay it notes durations channel beats)) (freverb-toggle 1) (freverb-preset 2) (fp 2 4) (fp 3 58) (fp 4 58) (fp 5 72) (fp 6 58) (fg .4) (defun mm ()) (let ((rhythms (make-cycle '(1 2 1)))) (defun mm (time) (let ((c (make-chord 70 85 3 (scale 0 'ryukyu))) (rhythm (next rhythms))) (if (odds .7) (pa time c (/ rhythm 3) 60 6 rhythm) (p time c 50 rhythm 6)) (aat (+ time rhythm) #'mm it)))) (mm (quant 4)) #| (mbox (funcall *metro* (funcall *metro* 'get-beat 4)) 32 :E 4 3 -7 7 (scale 1 'dorian)) (mbox 4 32 :C 9 14.5 -14 14 (scale 0 'dorian)) (mbox (tempo-sync #[1 b]) 32 :C 9 14.5 -14 14 (scale 0 'dorian)) (mbox (tempo-sync #[1 b]) 32 :G 10 3.5 -14 14 (scale 0 'dorian)) (mbox (tempo-sync #[1 b]) 32 :C 8 14.5 -7 14 (scale 0 'dorian)) (mbox (tempo-sync #[1 b]) 32 :D 9 1.5 -14 14 (scale 0 'dorian)) (mbox (tempo-sync #[1 b]) 32 :C 7 3 -7 14 (scale 0 'aeolian)) |# #| (all-piano *synth*) (fluidsynth:program-change *synth* 3 43) (fluidsynth:program-change *synth* 4 33) (fluidsynth:program-change *synth* 6 43) |# #| (flush-pending) (off-with-the-notes) |# ;;-------------------------------------------------- (mbox 4 32 :C 9 14.5 -14 14 (scale 0 'minor)) (let ((r (make-cycle (parse-pattern (get-mbeats 0 8)))) (n (make-cycle (get-mnotes 0 8))) (rr (make-cycle (parse-pattern (get-mbeats 10 17)))) (nn (make-cycle (get-mnotes 10 17)))) (defun f (time) (when (next r) (let ((nn (next n))) (p time nn 50 1 1) (play-ivory nn 2 :amp 300 :vib .1))) (when (next rr) (let ((n (next nn))) (p time n 60 1 0) (play-blue n 2))) (aat (+ time #[.3 b]) #'f it))) (f (now)) (defun f ()) (fp 1 40)
5,516
Common Lisp
.lisp
190
26.110526
84
0.56862
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
f552847c8a6e0efd66204d88a8bdb3fcdfe72e91afb81fc0f4a32cb04ca08a3a
9,235
[ -1 ]
9,236
gloriette.lisp
azimut_shiny/compositions/drafts/gloriette.lisp
(in-package :shiny) ;; -------------------------------------------------------------------- ;; Gloriette for John Cage - Translated from notes from metalevel ;; TODO: stop using a global and try to use a local variable instead ;; -------------------------------------------------------------------- (defparameter *c0* 0) (let* ((d (pval *c0*)) (p (make-weighting `((g3 :weight ,d) (a3 :weight ,d) bf3 (c4 :weight ,d) d4 (e4 :weight ,d) f4 (g4 :weight ,d) (0 :max 1 :weight .25)) 1)) (q (make-weighting (list 1/16 1/8 (make-cycle 1/32 2))))) (defun f (time) (let ((r (rhythm (next q)))) (p time (cm:transpose (cm:keynum (next p)) 12) 40 r 2) (p time (cm:transpose (cm:keynum (next p)) 0) 40 r 1) (p time (cm:transpose (cm:keynum (next p)) -12) 40 r 0) (aat (+ time #[r b]) #'f it)))) (all-piano 0) (flush-pending) (f (tempo-sync #[1 b])) ;;-------------------------------------------------- (let* ((d (pval *c0*)) (p (make-weighting `((g3 :weight ,d) (a3 :weight ,d) bf3 (c4 :weight ,d) d4 (e4 :weight ,d) f4 (g4 :weight ,d) (0 :max 1 :weight .25)) 1)) (q (make-weighting (list 1/16 1/8 (make-cycle 1/32 2))))) (defun f (time chan offset) (let ((r (rhythm (next q) 20))) (if (and (= 1 chan) (odds .1)) (setf *c0* 0) (incf *c0* .1)) (p time (cm:transpose (cm:keynum (next p)) offset) 40 r chan) (aat (+ time #[r b]) #'f it chan offset)))) (defun f ()) (f (tempo-sync #[4 b]) 0 -12) (f (tempo-sync #[4 b]) 1 0) (f (tempo-sync #[4 b]) 2 12) ;;-------------------------------------------------- (defun bird ()) (defun bird (time offset vel chan p q i &optional (w 0)) ;; (if (= chan 3) (setf vel 40)) ;; (if (not (= i 200)) (let* ((i (1+ i)) (note (next p)) (dur (next q)) (mul 12)) (setf *c0* (cm:interp i 0 .5 90 4)) ;; (setf *c0* 0) ;; (setf i 0) (p time (cm:keynum (cm:transpose note offset)) vel (* dur (- mul 3) ) chan) (aat (+ time (* mul dur)) #'bird it offset vel chan p q i w))) (defun cage (offset vel chan) (let* ((d (pval *c0*)) (p (make-weighting `((g3 :weight ,d) (a3 :weight ,d) bf3 (c4 :weight ,d) d4 (e4 :weight ,d) f4 (g4 :weight ,d) (0 :max 1 :weight .25)) 1)) (q (make-weighting (list 1/16 1/8 (make-cycle 1/32 2))))) (aat (quant 4) #'bird it offset vel chan p q 0))) ;; 10 violin ;; 11 pizzicato (?) ;; 15 wind (cage -12 40 0) (cage 0 50 1) (cage 12 30 2) (fg .9) (fp 2 30) (fluidsynth:program-change *synth* 3 10) (fluidsynth:program-change *synth* 1 33) (fluidsynth:program-change *synth* 2 10) (fluidsynth:program-change *synth* 3 26) (fluidsynth:program-change *synth* 1 77) (fluidsynth:program-change *synth* 2 33) (fg .1) (at (funcall *metro* (funcall *metro* 'get-beat 4)) #'cage -12 40 3) (at (funcall *metro* (funcall *metro* 'get-beat 4.5)) #'cage 0 45 1) (at (funcall *metro* (funcall *metro* 'get-beat 1.75)) #'cage 12 45 2) (at (tempo-sync #[4 b]) #'cage -12 40 3) (at (tempo-sync #[4.5 b]) #'cage 0 45 1) (at (tempo-sync #[1.75 b]) #'cage 12 45 2) (progn (at (tempo-sync #[1 b]) #'cage -12 30 3) (at (tempo-sync #[32 b]) #'cage 0 50 1) (at (tempo-sync #[64 b]) #'cage 12 40 2)) (flush-pending) (off-with-the-notes *synth*) #|| (process repeat 100 for n = (next p) for r = (rhythm (next q) 65) for i from 0 set w = (interp i 0 .5 90 4) output (new midi :time (now) :duration r :keynum (transpose n offset)) wait r) ||#
4,655
Common Lisp
.lisp
139
22.482014
71
0.402849
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
6b2f01a6240eb1944f8aeeb28ba6d23e79dab19c4ef1fc492c190a18bdbc905f
9,236
[ -1 ]
9,237
incudine.lisp
azimut_shiny/compositions/drafts/incudine.lisp
(in-package :shiny) ;; (dsp! bplay ;; ((buf buffer) rate start-pos ;; (loop-p boolean) attenuation rms (cfreq fixnum)) ;; (:defaults 0d0 -1 0 nil .00001 0 10) ;; (with-samples ;; ((in (incudine.vug:buffer-play ;; buf rate start-pos loop-p #'stop)) ;; (inn (* in attenuation)) ;; ;; (inn (incudine.vug:downsamp cfreq inn)) ;; ) ;; (out inn inn))) ;; (dsp! bplay ;; ((buf buffer) rate start-pos ;; (loop-p boolean) attenuation rms (cfreq fixnum)) ;; (:defaults 0d0 1 0 nil .00001 0 10) ;; (with-samples ;; ((in (incudine.vug:buffer-play ;; buf rate start-pos loop-p #'incudine:free)) ;; (inn (* in attenuation)) ;; (inn (+ inn ;; ;; (incudine.vug:buzz 2 .1 2) ;; ;; (incudine.vug:downsamp 10 inn) ;; ;; (incudine.vug:lpf inn 100 1) ;; ;; (incudine.vug:hpf inn 200 10) ;; ;; (incudine.vug:butter-hp inn 1000) ;; )) ;; ) ;; (out inn inn))) ;;(defvar *buf* (make-buffer 512 :channels 1)) ;; From Music V family. (define-vug rms (in hp) (:defaults 0 10) (with-samples ((b (- 2 (cos (* hp *twopi-div-sr*)))) (c2 (- b (sqrt (the non-negative-sample (1- (* b b)))))) (c1 (- 1 c2)) (in2 (* in in)) (q +sample-zero+)) (sqrt (the non-negative-sample (~ (+ (* c1 in2) (* c2 it))))))) ;; (dsp! rms-master-out-test ((index fixnum)) ;; (:defaults 0) ;; (setf (aref-c *c-arr* index) ;; (coerce (audio-out 0) 'single-float)) ;; (setf index ;; (mod (1+ index) 512))) ;; (dsp! rms-master-out-test ((index fixnum)) ;; (:defaults 0) ;; (setf (smp-ref (incudine::buffer-base-data- *buf*) index) ;; (rms (audio-out 0))) ;; (setf index ;; (mod (1+ index) (the fixnum (buffer-size *buf*))))) (define-vug select (l) (car (alexandria:shuffle l))) (dsp! ambi (freq vol) (:defaults 100 1) (with-samples ((note (incudine.vug:lag 70 1)) (freq (midihz note)) (detune1 (incudine.vug:lag 12 1)) (detune2 (incudine.vug:lag 24 1)) (freq2 (midihz (+ note detune1))) (freq3 (midihz (+ note detune2))) (noise (select (list (pink-noise .002) (white-noise .002)))) (in (+ (incudine.vug:ringz noise freq .2) (incudine.vug:ringz noise freq .2) (incudine.vug:ringz noise freq2 .2) (incudine.vug:ringz noise freq3 .2))) (in (tanh in)) (in (incudine.vug:lpf in 110 .1)) (in (* 100 in))) (out in in))) (ambi :id 2) (incudine:free (node 2)) ;; https://www.systemshock.org/shocklogs/ (bbuffer-load "/home/sendai/Downloads/sample/LOG0119.wav") (bbuffer-load "/home/sendai/Downloads/sample/LOG0120.wav") (put-phrase "joy" "LOG0120.wav" 5.5 3.7) (put-phrase "apart" "LOG0120.wav" 9 4) (put-phrase "separate" "LOG0120.wav" 13 .8) (put-phrase "individual" "LOG0120.wav" 14.5 4) (put-phrase "undo" "LOG0119.wav" 17 2.2) (word-play "joy" :rate 1) ;;-------------------------------------------------- (bbuffer-load "/home/sendai/projects/sonic-pi/etc/samples/guit_em9.flac") (bbuffer-load "/home/sendai/projects/sonic-pi/etc/samples/loop_garzul.flac") (defun f (time) (bbplay (gethash "ice.ogg" *buffers*) ;; :rate (pick .25 .5 1) :beat-length 8 :attenuation .5 ;; :id 2 ) ;; (bbplay (gethash "guit_em9.flac" *buffers*) ;; ;; :rate (pick .25 .5 1) ;; :beat-length 8 ;; :attenuation .5 ;; ;; :id 2 ;; ) ;; (bbplay (gethash "loop_garzul.flac" *buffers*) ;; :rate (pick .5 1) ;; :attenuation 1 ;; :id 3) (aat (+ time #[8 b]) #'f it)) (defun f ()) (f (now)) (incudine:free (node 0)) ;;-------------------------------------------------- (bbuffer-load "/home/sendai/Downloads/sample/EM0902-EM0902.wav") (bplay (gethash "EM0902-EM0902.wav" *buffers*) 1 0 nil :attenuation 1 :id 2) (bbuffer-load "/home/sendai/Downloads/sample/LOG0106.wav") (bbplay (gethash "LOG0106.wav" *buffers*) :attenuation 1 :id 3 :loop-p nil) (bbuffer-load "/home/sendai/Downloads/sample/EM0903.wav") (bbplay (gethash "EM0903.wav" *buffers*) :beat-length 8) (bplay (gethash "EM0903.wav" *buffers*) 1 0 nil :attenuation 1) (put-phrase "nuisance" "EM0903.wav" 21 1) (put-phrase "why" "EM0903.wav" 8.4 2) (put-phrase "feel" "EM0903.wav" 10.5 3) (word-play (pick "why" "nuisance" "feel") :rate (pick 1 2 1.5) :id (1+ (random 30))) (word-play "why") (word-play "nuisance" :beat-length 4) (incudine:free (node 0)) (bbuffer-load "/home/sendai/whatever.wav") (bplay (gethash "whatever.wav" *buffers*) 1 0 nil :attenuation 1 :id 2) (defun g ()) (defun g (time) (let ((cfreq (drunk 60 5))) (set-controls 2 :cfreq cfreq :rate (funcall (pick '+ '+ '+ '- '+ '+ '+ '+) (+ cfreq (pick 0 0 1 -1 -2))))) (aat (+ time #[1 b]) #'g it)) (g (now)) (set-controls 2 :rate 1f0 :attenuation 1d0 :cfreq 1) ;;-------------------------------------------------- (make-instrument 'drum "/home/sendai/Downloads/sample/OH/") (push-note 'drum *gm-kick* "kick_OH_F_9.wav") (push-note 'drum *gm-side-stick* "snareStick_OH_F_9.wav") (push-note 'drum *gm-snare* "snare_OH_FF_9.wav") (push-note 'drum *gm-closed-hi-hat* "hihatClosed_OH_F_20.wav") (push-note 'drum *gm-pedal-hi-hat* "hihatFoot_OH_MP_12.wav") (push-note 'drum *gm-open-hi-hat* "hihatOpen_OH_FF_6.wav") (push-note 'drum *gm-low-floor-tom* "loTom_OH_FF_8.wav") (push-note 'drum *gm-hi-floor-tom* "hiTom_OH_FF_9.wav") (push-note 'drum *gm-crash* "crash1_OH_FF_6.wav") (push-note 'drum *gm-ride* "ride1_OH_FF_4.wav") (push-note 'drum *gm-chinese* "china1_OH_FF_8.wav") (push-note 'drum *gm-cowbell* "cowbell_FF_9.wav") (push-note 'drum *gm-open-triangle* "bellchime_F_3.wav") (push-note 'drum *gm-ride-bell* "ride1Bell_OH_F_6.wav") (defun f (time dur &optional (beat 0)) (and (zmod beat 1) (bbplay (gethash "kick_OH_F_9.wav" *buffers*) :attenuation 1d0 :left .1)) (and (zmod beat 3) (play-instrument 'drum *gm-snare* :dur dur :amp .4)) ;; (and (zmod beat 2) (play-instrument 'drum *gm-side-stick* dur .4)) ;; (and (zmod beat 2.5) (play-instrument 'drum *gm-side-stick* dur .4)) (aat (+ time #[dur b]) #'f it .5 (+ beat dur))) (defun f ()) (f (now) 1) (pat (now)) (defun pat ()) (defpattern pat ((get-pattern 'getup) .2) (if (odds .5) (bbplay (gethash "kick_OH_F_9.wav" *buffers*) :attenuation 1d0 :left .1) (bbplay (gethash "kick_OH_F_9.wav" *buffers*) :attenuation 1d0 :right .1)) (bbplay (gethash "snareStick_OH_F_9.wav" *buffers*) :attenuation 1d0) (bbplay (gethash "hihatClosed_OH_F_20.wav" *buffers*) :attenuation 1d0)) ;;--------------------------------------------------
7,105
Common Lisp
.lisp
193
32.585492
73
0.553148
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
be9041c48727c4d9f01d3d8a5770adba160d964d0fa13b8a56c36a8bd7e0f8f3
9,237
[ -1 ]
9,238
bass.lisp
azimut_shiny/compositions/drafts/csound/bass.lisp
(in-package :shiny) (load-csound (get-orchestra :bass)) (make-play bass "i1" :fco1 .1 :fco2 .3 :res1 .2 :res2 .2 :env1 .1 :env2 .4 :dec1 .05 :dec2 .8 :acc1 0 :acc2 0 :bars 120 :amp .2 :keynum 60) (play-bass 50 1 :bars 120 :amp .8 :res1 .9 :res2 .2) (play-bass 60 1 :bars 1) (start-thread) ;;-------------------------------------------------- (start-csound (merge-orcs (get-orchestra :bass) (get-orchestra :asynth))) (load-csound (merge-orcs (get-orchestra :bass) (get-orchestra :asynth))) (start-thread) (start-csound (get-orchestra :bass)) ;; https://github.com/AbletonTriCitiesUserGroup/Gallery/ ;; -----VCOs------ ------VCF------ ---VCOs-- ------LFOs------ ;; Strt Leng Levl Pitch Semi Fine Vcf1 Vcf2 Rez Wav1 Wav2 Wave Rate1 Rate2 Ring ;;i1.1 0 -2 .7 06.00 1 1 1000 200 10 2 2 2 .25 .3 .75 (make-play asynth "i1.1" :amp .7 :keynum 60 :semi 1 :fine 1 :vcf1 1000 :vcf2 200 :rez 10 :wav1 2 :wav2 2 :wave 2 :rate1 .25 :rate2 .3 :ring .75) (play-asynth 60 .2 :amp .1) (let ((note (make-cycle (make-chord-fixed 66 3 (scale 0 'ryukyu))))) (defun f (time) (if (odds .8) (play-hihat 1) (play-snare 1)) (if (odds .8) (play-bass (next note) 1 :amp .2 :bars 300) (play-bass (+ 12 (next note)) 2 :amp .2 :bars 1)) (aat (+ time #[1 b]) #'f it))) (f (now)) (defun f ()) ;;-------------------------------------------------- (start-csound (get-orchestra :drumkit)) (start-thread) (load-csound (get-orchestra :drumkit)) (make-play bass "i1" :amp 10000 :wave 1 :pulse 8 :env 10 :rhyth 30 :keynum 60 :gliss 20 :p1 .1) ;;in star dur amp pulse rhythm env1 env2 pan ;;i2 0 16 20000 8 32 12 11 .7 .2 (make-play hihat "i2" :amp 10000 :pulse 8 :rhy 32 :env1 12 :env2 11 :pan1 .7 :pan2 .2) ;;SNARE ;; ;in star dur amp pulse env1 env2 rhythm pan ;; i3 0 16 30000 8 13 14 33 .3 .2 (make-play snare "i3" :amp 10000 :pulse 8 :env1 13 :env2 14 :rhy 33 :pan1 .3 :pan2 .2) ;;CRASH ;;in star dur amp pulse rhythm env1 env2 pan ;;i4 0 32 2500 .25 34 12 15 .2 .2 13.03 (make-play crash "i4" :amp 2500 :pulse .25 :rhy 34 :env1 12 :env2 15 :pan1 .2 :pan2 .2 :keynum 80) (play-hihat 1) (play-bass 60 1) (play-snare 2) (play-crash 60 2 :pan1 .3)
2,430
Common Lisp
.lisp
61
35.459016
144
0.545802
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
49ea2d0ec7229db617ce4c7e7833090765754afde7dfd0d6409cd82266a7b7bd
9,238
[ -1 ]
9,239
trapped.lisp
azimut_shiny/compositions/drafts/csound/trapped.lisp
(in-package :shiny) (start-csound (get-orchestra :trapped)) (load-csound (get-orchestra :trapped)) (start-thread) ;; TRAPPED (make-play ivory "i1" :p4 0 :keynum 60 :amp 200 :vib .001 :glis 17.8 :drop .99) (make-play blue "i2" :p4 0 :keynum 60 :amp 600 :reverb .6 :lfo 23 :harm 10 :sweep .52) (make-play violet "i3" :p4 0 :keynum 60 :amp 800 :reverb .8 :rand 57) (make-play black "i4" :p4 0 :keynum 60 :amp 800 :swp 4600 :eswp 6500 :band 33 :rev 0.6) (make-play green "i5" :p4 0 :keynum 60 :amp 900 :rev .2 :pan .1 :carr 3 :modf 10 :modi 12 :rand 27) (make-play cooper "i6" :p4 .81 :sweeps 3000 :sweepe 17 :band 10 :rev .6 :amp 1.6) (make-play pewter "i7" :amp 1000 :keynum 60 :bphase .2 :ephase .7 :oamp .6 :oscf 2 :oscm 3 :rev .12) (make-play red "i8" :amp 4 :swp 20 :eswp 8000 :band 590 :rand1 2 :rand2 9.9 :rev .6) (make-play sand "i9" :delay .2 :keynum 60 :amp 500 :rev .2 :ramp 6.2 :rfreq 320) (make-play taupe "i10" :p4 0 :keynum 60 :amp 500 :rev .8 :ramp 5 :rfreq 223) (make-play rust "i11" :delay 0 :keynum 60 :amp 1200 :rev .2) (make-play teal "i12" :p4 0 :keynum 60 :amp 1000 :swp 100 :pswp 7000 :band 16 :rev .2) (make-play foam "i13" :p4 0 :keynum 60 :amp 1000 :vib 40 :glis 7) (make-play swirl "i99" :pan 2) ;; requires nudruz (defparameter *expwarp* (loop :for n :from 1 :to 3 :by .1 :collect (mapcar #'round (cm:expwarp '(36 55 64) n)))) (let ((n (make-heap *expwarp*))) (defun f (time) (let ((i (reverse (next n)))) (play-sand (nth 0 i) 4 .2 500) (at (+ time #[1 b]) #'play-green (nth 2 i) 1 .2 500) (at (+ time #[2 b]) #'(lambda () (play-sand (nth 1 i) 1 .2 500 .9)))) (aat (+ time #[4 b]) #'f it))) (defun f ()) (f (now)) (defparameter *m5chds* (loop :for n :in (cm::m5 (cm::indices 12)) :collect (cm::transp '(0 3 5 7) n))) (defparameter *rgrthing* (cm::generic-branch #'cm::rgr-alldim1 *m5chds*))
1,880
Common Lisp
.lisp
36
49.944444
100
0.623843
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
081477289bf765f9dc51accf78789dc2cf732e6e7e3c4e22c437e32773890f74
9,239
[ -1 ]
9,240
xanadu.lisp
azimut_shiny/compositions/drafts/csound/xanadu.lisp
(in-package :shiny) (start-csound (get-orchestra :xanadu)) (load-csound (get-orchestra :xanadu)) (start-thread) ;; XANADU (make-play plucke "i1" :p4 0 :keynum 60) (make-play pluck "i2" :p4 0 :keynum 60) (make-play newfm "i3" :p4 0 :keynum 60 :llimit .2 :rlimit 2.0) (play-newfm 90 5 :p4 .9) (play-pluck 90 2) (play-pluck-arp '(60 62) 1 1) ;; Csound tutorial (defun lorenz () (labels ((interpolate (x) (round (+ 36 (* x 60))))) (let ((r 3.974)) (mapcar #'interpolate (loop :repeat 100 :with y = .5 :collect (setf y (* r y (- 1f0 y)))))))) (let ((notes (make-cycle (lorenz)))) (defun f (time) (let ((n (next notes))) (play-pluck n .5)) (aat (+ time #[.5 b]) #'f it))) (defun f ()) (f (now))
771
Common Lisp
.lisp
26
25.615385
63
0.570461
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
de0b32e5edf5ec36a761ca3c9d1472d539a073a237e7275a7a4c4136efe470cf
9,240
[ -1 ]
9,241
template.lisp
azimut_shiny/compositions/drafts/csound/template.lisp
(in-package :shiny) (defparameter *dummy* "instr 1 this that the other instr 2 more of that if then instr 3 blue green light fire")
140
Common Lisp
.lisp
11
11
21
0.779528
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
1698ada16b43e2a10fa9e92c2b3a53fabadc3b8e1b507760414d4c46095a696e
9,241
[ -1 ]
9,242
tests.lisp
azimut_shiny/compositions/drafts/csound/tests.lisp
(in-package :shiny) (start-csound (gethash :xanadu *orcs*)) (bt:make-thread (lambda () (loop :for frame = (csound:csoundperformksmps *c*) :while (= frame 0)))) ;; dodgefig327.orc - meh - drop of things, weird electic drums, no keynum ;; winkler/pwm2 ;; varios/bass-drum (blu1e-monday like) ;; costello/stringphaser (synth strings intro like) ;; cook/808hithat () ;; cook/synth (old electronic music, demo crack style) ;; cook/sequencer ;; cook/buzz (make-orc :string :filename "string" :filepath "/home/sendai/projects/csound-instruments/dodge/") (make-orc :dodsoprano :filename "dodsoprano" :filepath "/home/sendai/projects/csound-instruments/dodge/") (make-orc :soprano :filename "soprano" :filepath "/home/sendai/projects/csound-instruments/cook/") (make-orc :soprano :filename "soprano" :filepath "/home/sendai/projects/csound-instruments/pinkston/") (make-orc :fmdrum :filename "fmdrum" :filepath "/home/sendai/projects/csound-instruments/pinkston/") (csound:csoundcompileorc *c* (get-orc :fmdrum)) (csound:csoundreadscore *c* (get-sco :fmdrum)) ; play some notes ; p4 = amp; p5 = fund; p6 = 0 < ampfac < 1; p7 = fmt env func ; p8 = port func; p9 = fmt hz func; p10 = fmt amp func; p11, 12 = i1,i2 fns i01 0 1 20000 7.07 .5 2 3 4 5 6 7 (make-play dod "i1" :amp 20000 :keynum 60 :p6 .5 :p7 2 :p8 3 :p9 4 :p10 5 :p11 6 :p12 7) (play-dod (pickl (ov-scale :C4 :minor)) 1 :p10 3) ; Strt Leng Levl Pitch Vowl1 Vowl2 Delay Glide i01 0.00 -0.50 1.00 09.00 2.00 1.00 2.00 0.25 (csound:csoundreadscore *c* "i01 0.00 -0.50 1.00 09.00 2.00 1.00 2.00 0.25") (make-play soprano "i1" :lvl 1f0 :keynum 60 :vowl1 2f0 :vowl2 1f0 :delay 2f0 :glide .25) (play-soprano 60 1) ; play some notes ; p4 = amp; p5 = fund; p6 = 0 < ampfac < 1; p7 = fmt env func ; p8 = port func; p9 = fmt hz func; p10 = fmt amp func; p11, 12 = i1,i2 fns i01 0 1 30000 7.07 .7 2 3 4 5 6 7 i01 1 . . 8.04 (make-play soprano "i1" :amp 20000 :keynum 60 :ampfac .7 :env 2 :port 3 :fmthz 4 :fmtamp 5 :i1 6 :i2 7) (play-soprano (pickl (ov-scale :C4 :minor)) 2 :fmthz 1 :i1 3) ;nn st dur igain irvt ilpt-or-pch iscale i01 0 10 .7 .2 5.00 .4 (make-play drum "i1" :igain .7 :irvt .2 :keynum 60 :iscale 4) (play-drum 50 1) ;parms: st dur amp pch rise decay lfohz lfofn oscfn i1 0 3 16000 13.00 1 2 15 2 1 i1 + . . . . . 20 i1 + . . . . . 25 f0 10 s ;parms: st dur amp pch rise decay lfohz amfn oscfn i2 0 3 16000 13.00 1 2 15 2 1 ; lfohzfn panfn 3 4 i2 + . . . . . 20 i2 + . . . . . 25 f0 10 s ;parms: st dur amp pch rise decay lfohz amfn oscfn i3 0 3 16000 12.06 1 2 15 2 1 ; lfohzfn panfn ibend bendfn 3 4 .25 4 i3 + . . . . . 20 i3 + . . . . . 25 (make-play tick1 "i1" :amp 10000 :keynum 60 :rise 1 :Decay 2 :lfohz 15 :lfofn 2 :oscfn 2) (play-tick1 60 1) ;Test a range of pitches, bend amounts, transient durations, and indexes. ; st dur ipkdb ipch carfac modfac maxbnd trdur endbnd indx1 indx2 isusdb i01 0 .75 90 7.00 1 .31791 1 .2 0 7 .005 82 (make-play drum "i1" :ipkdb 90 :keynum 60 :carfac 1 :modfac .31791 :maxbnd 1 :trdur .2 :endbnd 0 :indx1 7 :indx2 .005 :isusdb 82) (play-drum (pickl (ov-scale :C3 :minor)) 1 :trdur 2 :modfac .8 :carfac .2) ;;-------------------------------------------------- (load-csound (merge-orcs (get-orchestra :phaser) (get-orchestra :physmodl '(0 1)))) (make-play phaser "i1" :amp 3000 :keynum 60) (make-play phaser-effect "i2" :change .9) (make-play phaser-reverb "i3" :p1 .93 :p2 1.2 :p3 1 :p4 7000 :p5 1) (make-play bass "i4" :amp 1400 :keynum 60 :pluckdur .25 :left 1f0 :right 1f0) (make-play flute "i5" :amp 6000 :keynum 60 :press .9 :breath .036 :fbk1 .4 :fbk2 .4 :left 1f0 :right 1f0) (start-thread) (play-phaser-effect 10) (play-phaser 60 1) (play-flute 60 1) (play-bass-arp (make-chord 30 40 3 (scale 0 'minor)) .5 .5)
4,524
Common Lisp
.lisp
99
41.979798
129
0.560654
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
464a0e8696b548f810e5a7a84c58b2a20ffb10d9ed7f7f8c04ea3765c78a23f5
9,242
[ -1 ]
9,243
csound2.lisp
azimut_shiny/compositions/drafts/csound/csound2.lisp
(let ((chord (make-cycle (make-chord-fixed 60 3 (scale 0 'ryukyu)))) (here (make-cycle '(t nil))) ;;(lead (make-cycle (make-chord-fixed 80 5 (scale 0 'ryukyu)))) (lead (make-cycle *spectrum*))) (defun f (time) (let ((n (next chord))) ;;(playcsound *inst3* n 2 2 .2) ;; (if (odds .5) ;; (p time 60 60 1 0) ;; (progn ;; (p time 60 60 .5 2 :pan 0) ;; (p (+ time #[.5 b]) 60 60 .5 3 :pan 127))) (when (next here) (playcsound *inst1* (next lead) 4))) (aat (+ time #[2 b]) #'f it))) (defpattern k ((gethash 'wm *patterns*) .25) (bbplay "kick_OH_F_9.wav" :attenuation .2 :rate 1) (bbplay "snare_OH_FF_9.wav" :attenuation .2 :rate .2) (bbplay "hihatClosed_OH_F_20.wav" :attenuation .05 :rate 2) ;;(bbplay "hihatOpen_OH_FF_6.wav" :attenuation .05 :rate -2) ) (k (tempo-sync #[1 b])) (f (tempo-sync #[1 b])) (defun f ()) (defun k ()) (let ((chord (make-cycle (make-chord-fixed 60 3 (scale 0 'ryukyu)))) (here (make-cycle '(t nil))) ;;(lead (make-cycle (make-chord-fixed 80 5 (scale 0 'ryukyu)))) (lead (make-line *expand*))) (defun f (time) (let ((n (next chord))) (playcsound *inst3* (+ 12 n) 2 2 .2) ;; (if (odds .5) ;; (p time 60 60 1 0) ;; (progn ;; (p time 60 60 .5 2 :pan 0) ;; (p (+ time #[.5 b]) 60 60 .5 3 :pan 127))) (when (next here) (playcsound *inst3* (cm:transp (next lead) 0) 2 3 0.4))) (aat (+ time #[1 b]) #'f it))) (defpattern k ((gethash 'getup *patterns*) .5) (playcsound *inst3* *gm-kick* d 4 .9) (playcsound *inst3* *gm-snare* d 2 .2) (playcsound *inst3* *gm-closed-hi-hat* d 4 .1)) (defun k ()) (k (now))
1,763
Common Lisp
.lisp
48
31.583333
70
0.526964
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
da3fa8327161d9655b25bd556623ff97351806a0e28cd062bb7f36efcab01f56
9,243
[ -1 ]
9,244
aeolus.lisp
azimut_shiny/compositions/drafts/csound/aeolus.lisp
(in-package :shiny) ;; Using https://github.com/gogins/csound-aeolus plugin. ;; I shouln't need Csound at all and I should be able to use ;; Aeolus standalone with MIDI, but, I cannot start Aeolus without Jack. ;; So this helps by letting csound in charge of controling ;; the audio driver. ;; Update: in the end ALSA has hiccups so this is only useful to play around ;; this is due the 64 on ksmps mandatory by the plugin. ;;(setf *csound-options* '("-odac" "-m3")) ;; sr = 44100 ;; kr = 4410 ;; ksmps = 10 ;; nchnls = 2 (setf *csound-globals* " sr = 44100 kr = 4410 ksmps = 128 nchnls = 2") (setf *csound-globals* " sr = 44100 ksmps = 64 nchnls = 2") ;; (setf *csound-globals* " ;; sr = 48000 ;; ksmps = 64 ;; nchnls = 2") (make-orc :aeolus :globals " 0dbfs = 1 gi_aeolus aeolus_init \"/home/sendai/testfield/stops\", \"Aeolus\", \"waves\", 0, 10" :sco " i2 0 -1" :orc " instr 1 aeolus_note gi_aeolus, p4, p5, p6 endin instr 2 aeolus_preset gi_aeolus, 1, 1, \"/home/sendai/testfield/stops/.aeolus-presets\" a_out[] init 2 a_out aeolus_out gi_aeolus out a_out endin") (start-csound (get-orchestra :aeolus)) (start-thread) (make-play flute "i1" :chan 2 :midi 60 :vel 60) (make-play honk "i1" :chan 0 :midi 60 :vel 60) (make-play organ "i1" :chan 1 :midi 60 :vel 60) (make-play eorgan "i1" :chan 3 :midi 60 :vel 60) (play-flute 60 1) (defun f (time) (play-eorgan 64 .2 :vel 20) (aat (+ time #[1 b]) #'f it)) (defun f ()) (f (now))
1,513
Common Lisp
.lisp
55
25.272727
86
0.656272
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
d35e232dd197d4037812cd025036448bf88bbb36a4274a481e451f5172678045
9,244
[ -1 ]
9,245
merge.lisp
azimut_shiny/compositions/drafts/csound/merge.lisp
(in-package :shiny) (make-orc :synth :filename "synth" :filepath "/home/sendai/projects/csound-instruments/cook/") (start-csound (get-orchestra :synth)) (load-csound (get-orchestra :synth)) (start-thread) ;; ; -----VCOs------ ------VCF------ ---VCOs-- ------LFOs------ ;; ; Strt Leng Levl Pitch Semi Fine Vcf1 Vcf2 Rez Wav1 Wav2 Wave Rate1 Rate2 Ring ;; i1.1 0.00 -2 0.70 06.00 1.00 1.00 1000 200 10 02 02 02 0.25 0.30 0.75 (make-play synth "i1" :amp .7 :keynum 60 :semi 1f0 :fine 1f0 :vcf1 1000 :vcf2 200 :rez 10 :wav1 2 :wav2 2 :wave 2 :rate1 .25 :rate2 .3 :ring .75 :left 1f0 :right 1f0) (play-synth (make-chord 60 90 3 (scale 0 'minor)) 3 :amp .1 :vcf1 2000 :left .6) (play-synth-arp '(60 54) .5 1 :amp .1) ;;-------------------------------------------------- (make-orc :phaser :filename "stringphaser" :filepath "/home/sendai/projects/csound-instruments/costello/") (load-csound (get-orchestra :phaser)) (start-csound (get-orchestra :phaser)) (start-thread) ;; i19 0 5 3000 6.07 ; Global instrument for ensemble/phaser effect. p4 sets amount ; of pitch change in chorusing. ;; i22 0 20 .9 ; Global instrument for reverb. ;; i99 0 24 .93 1.2 1 7000 1 (make-play phaser "i19" :amp 3000 :keynum 60) (make-play phaser-effect "i22" :change .9) (make-play phaser-reverb "i99" :p1 .93 :p2 1.2 :p3 1 :p4 7000 :p5 1) (play-phaser-reverb 10) (play-phaser-effect 10 :change .1) (play-phaser 70 1) (play-phaser (make-chord 60 70 3 (scale 0 'minor)) 2 :amp 500) ;;-------------------------------------------------- (make-orc :wavmodfm :filename "wavmodfm" :filepath "/home/sendai/projects/csound-instruments/dodge/") (start-csound (get-orchestra :wavmodfm)) (start-thread) (load-csound (get-orchestra :wavmodfm)) (make-play wavmodfm "i1" :amp 3000 :freq 440) (play-wavmodfm (make-chord 40 60 3 (scale 0 'minor)) 2 :amp 1000) ;;-------------------------------------------------- ;; Inception-esque gong (make-orc :gong :filename "gong" :filepath "/home/sendai/projects/csound-instruments/costello/") (start-csound (get-orchestra :gong)) (start-thread) (load-csound (get-orchestra :gong)) ;; i99 1 25 200 5000 .999 0 100 200 10000 1.2 ;; i99 6 20 150 5000 .999 0 100 300 10000 .8 ;; i99 11 15 400 5000 .999 0 200 300 20000 1 (make-play gong "i99" :freq 200 :amp 5000 :p4 .999 :p5 0 :p6 100 :p7 200 :p8 10000 :p9 1.2) (play-gong 60 20 :amp 500) ;;-------------------------------------------------- ;; A set of cool eerie stuff... (make-orc :otis :filename "otis" :filepath "/home/sendai/projects/csound-instruments/costello/") (start-csound (get-orchestra :otis)) (load-csound (get-orchestra :otis)) (start-thread) (make-play otis15 "i15" :freq 443.713 :amp 200 :pan .401) (make-play drums "i7" :amp .799 :ampfunc 3 :freq 203 :ratio 1.416 :p8 4.99 :p9 .511) (make-play drone "i8" :freq 60 :amp .399 :p6 9.999 :p7 3) (make-play bell "i5" :freq 60 :amp .032 :p6 4 :p7 70.006 :p8 169.437) (make-play timpani "i14" :freq 48.695 :amp .046 :p6 3 :p7 7 :p8 90) ;; 5 bell ;; 7 mouse drums - fm (play-timpani (pickl (make-chord-fixed 60 3 (scale 0 'minor))) .3) (play-timpani (pickl (ov-scale :c6 :minor)) 4 :amp .01) (play-drone 58 10 :amp .1 :p7 1) (play-bell-arp '(60 62 65) 2 2 :p8 20) (play-drums 200 .05) (play-otis15 50 8 :amp 1000 :pan .9) ;;-------------------------------------------------- (make-orc :physmodl :filename "physmodl" :filepath "/home/sendai/projects/csound-instruments/mikelson/") (load-csound (get-orchestra :physmodl)) (start-csound (get-orchestra :physmodl)) (start-thread) ;; i2 128 4 1400 6.00 .25 (make-play bass "i2" :amp 1400 :keynum 60 :pluckdur .25 :left 1f0 :right 1f0) ;; Start Dur Amp Pitch Press Filter Embouchure Reed Table ;; (20000) (8.00-9.00) (0-2) (500-1200) (0-1) ;;i4 32 16 6000 8.00 1.5 1000 .2 1 (make-play clarinet "i4" :amp 6000 :keynum 60 :press 1.5 :filter 1000 :emb .2 :reed 1 :left 1f0 :right 1f0) ; Slide Flute ; Start Dur Amplitude Pitch Pressure Breath Feedbk1 Feedbk2 i3 80 16 6000 8.00 .9 .036 .4 .4 i3 . 4 . 8.05 .99 . . . (make-play flute "i3" :amp 6000 :keynum 60 :press .9 :breath .036 :fbk1 .4 :fbk2 .4 :left 1f0 :right 1f0) ; Drumstick ; Start Dur Amp Pitch PreFilter i8 0 4 200 7.05 100 (make-play drumstick "i8" :amp 200 :keynum 50 :prefilter 100) (play-drumstick 60 1) ; Drum 1 ; Start Dur Amp Pitch PreFilter TubeLength Feedback1 Feedback2 ;;i9 0 128 160 5.11 100 4 4.4 4.3 (make-play drum "i9" :amp 160 :keynum 40 :prefilter 100 :tubelength 4 :feedback1 4.4 :feedback 4.3 :left .4 :right .4) (play-flute 62 1 :left .2 :press .9 :fbk1 .5) (play-drum 60 10) (play-clarinet 70 1 :left .2) (play-bass 30 1 :pluckdur .3 :right .02 :amp 200) ;;-------------------------------------------------- (make-orc :hallown :filename "hallown" :filepath "/home/sendai/projects/csound-instruments/mikelson/") (start-csound (get-orchestra :hallown)) (load-csound (get-orchestra :hallown)) (start-thread) ; Ghosties ; Start Dur Amp Frqc ;;i11 44 6 5 7.00 ;;i12 48 3 7 8.00 (make-play ghost1 "i11" :amp 5 :keynum 60) (make-play ghost2 "i12" :amp 5 :keynum 60) (play-ghost2 100 3) ; Electronic Zap from the Mandelbrot set. ; Sta Dur Amp Pitch XCorner YCorner XStep YStep MaxLoop Pan ;; i10 70 1.0 60 7.00 -0.6 -0.8 .0002 .002 400 1.0 ;; (make-play zap "i10" :amp 60 :keynum 60 :xcorner -.6 :ycorner -.8 ;; :xtep .0002 :ystep .002 :maxloop 400 :pan 1f0) ;; (play-zap 80 1) ; Wolf Howl ; Sta Dur Amp FqcTab FrmTab Pan Fco ;; i2 12 4 10 6 20 1 1000 ;; i2 13 2 25 8 20 .2 1500 ;; (make-play wolf "i2" :amp 10 :fqctab 6 :frmtab 20 :pan 1f0 :fco 1000) ;; (play-wolf 2 :fqctab 6 :pan .2) ; Thunder ; Sta Dur Amp Fqc Fco Atk Pan ;; i3 14 4 6000 100 100 40 .5 ;; i3 17 4 6800 80 200 10 .7 ;; (make-play thunder "i3" :amp 600 :fqc 100 :fco 100 :atk 40 :pan .5) ;; (play-thunder 2) ; Church Bell ; Sta Dur Amp Fqc Pan OutCh1 OutCh2 i6 42 2.0 1000 8.02 1.0 3 4 (make-play bell "i6" :amp 1000 :keynum 60 :pan 1f0 :outch1 3 :outch2 4) (play-bell 60 1 :pan .8 :amp 3000) ; Organ Intro to Bach's Toccata & Fugue in Dminor ; Sta Dur Amp Fqc Pan OutCh1 OutCh2 i4 26 .12 200 7.09 .9 1 2 i4 + .1 300 7.07 .8 1 2 (make-play organ "i4" :amp 200 :keynum 60 :pan .5 :outch1 1 :outch2 2) (play-organ 55 1) ;;-------------------------------------------------- (make-orc :bass-drum :filename "bass-drum" :filepath "/home/sendai/projects/csound-instruments/varios/") (load-csound (get-orchestra :bass-drum)) (make-play bass-drum "i1" :amp 3000) (start-csound (get-orchestra :bass-drum)) (start-thread) (play-bass-drum .25 :amp 1000) ;;-------------------------------------------------- (make-orc :ourvoice :filename "ourvoice" :filepath "/home/sendai/projects/csound-instruments/pinkston/") (load-csound (get-orchestra :ourvoice)) (start-csound (get-orchestra :ourvoice)) (start-thread) (make-play voice-a "i1" :amp 10000 :keynum 60 :fmt1 609 :db1 0 :fmt2 1000 :db2 -6 :fmt3 2450 :db3 -12 :fmt4 2700 :db4 -11 :fmt5 3240 :db5 -24 :left 1f0 :right 1f0) (make-play voice-e "i1" :amp 10000 :keynum 60 :fmt1 400 :db1 0 :fmt2 1700 :db2 -9 :fmt3 2300 :db3 -8 :fmt4 2900 :db4 -11 :fmt5 3400 :db5 -19 :left 1f0 :right 1f0) (make-play voice-iy "i1" :amp 10000 :keynum 60 :fmt1 238 :db1 0 :fmt2 1741 :db2 -20 :fmt3 2450 :db3 -16 :fmt4 2900 :db4 -20 :fmt5 4000 :db5 -32 :left 1f0 :right 1f0) (make-play voice-o "i1" :amp 10000 :keynum 60 :fmt1 325 :db1 0 :fmt2 700 :db2 -12 :fmt3 2550 :db3 -26 :fmt4 2850 :db4 -22 :fmt5 3100 :db5 -28 :left 1f0 :right 1f0) (make-play voice-oo "i1" :amp 10000 :keynum 60 :fmt1 360 :db1 0 :fmt2 750 :db2 -12 :fmt3 2400 :db3 -29 :fmt4 2675 :db4 -26 :fmt5 2950 :db5 -35 :left 1f0 :right 1f0)
8,654
Common Lisp
.lisp
196
40.438776
90
0.575437
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
de5af1ba5a0a36e7574e7f315c402f51c67a5bf8e452db72f1e79424b90e872b
9,245
[ -1 ]
9,246
rhythmic.lisp
azimut_shiny/compositions/drafts/csound-live-code/rhythmic.lisp
(in-package :shiny) ;;-------------------------------------------------- ;; Cover of Steven Yi: ;; csound-live-code/practice/2019-05-13-rhythmic.orc ;; ;; Tempo: 120 (progn (setf (bpm *tempo*) 120) (update-1beat)) (flush-pending) (off-with-the-notes) (fg 2f0) (progn (fp 7 89) (fp 1 0) (fp 2 70) (fp 5 52) (fp 6 52) (fp 8 52) (fpan 8 100) (fpan 6 20)) (aat (tempo-sync #[1 b]) #'p1 it) (defun p1 ()) ;; <3 (let ((p1 (hexpat "f")) (p2 (hexpat "cfab cbaf bdbe dc")) (p3 (hexpat "cfab cbaf b")) (p4 (hexpat "0c")) (p5 (hexpat "000f")) (scale (scale 0 'aeolian))) (defun p1 (time) (when (next p1) (p time (pc-relative (note :c2) (nth-beat 2 '(0 4 7 11 14 18 21 18 14 11)) scale) 40 1 1)) (when (next p2) (p time (pc-relative (note :c2) (+ 4 (nth-beat 1.93 '(0 4 7 11 14 18 21 18 14 11))) scale) (* (choose .7) (rcosr 45 5 10)) .8 2)) ;; (when (next p3) (p time (pc-relative (note :c2) (+ 7 (nth-beat 1.7 '(0 4 7 11 14 18 21 18 14 11))) scale) (* (choose .7) (rsinr 45 5 10)) .1 5)) (when (next p4) (p time (pc-relative (note :c4) (nth-beat 1.7 '(12 6)) scale) (rcosr 45 5 10) .8 6)) (when (next p5) (p time (pc-relative (note :c6) (nth-beat 2.7 '(0 2 3 4)) scale) 30 .8 8)) (aat (+ time #[.8 b]) #'p1 it)))
1,650
Common Lisp
.lisp
56
20.642857
78
0.424701
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
80592e14d9505e7e69327e1aee2557925932494178ac7525839b871996d62840
9,246
[ -1 ]
9,247
hexbeat.lisp
azimut_shiny/compositions/drafts/csound-live-code/hexbeat.lisp
(in-package :shiny) (fp 2 40) (fp 0 20) (fg 2f0) (fp 1 40) ;; A - 1010 - up/back/off ;; 8 - 1000 - up/back ;; 2 - 0010 - off ;; ;; C - 1100 - up/back/weak-sincopated ;; 1 - 0001 - weak-syncopated ;; ;; B - 1011 - up/back/weak-sync ;; 4 - 0100 - weak-sync ;; 9 - 1001 - up/weak-sync (at (tempo-sync #[(* .3 16) b]) #'eval (defpattern h (((parse-pattern (bjorklund 3 12) :true-char #\1) (parse-pattern (bjorklund 2 12) :true-char #\1) (parse-pattern (bjorklund 4 12) :true-char #\1) (parse-pattern (bjorklund 1 12) :true-char #\1)) .3) (p time 40 40 .2 0) (p time 52 30 .1 0) (p time 60 40 .2 0) (p time (pc-quantize (drunk 70 5) (scale 0 'minor)) 40 .3 2))) (fp 2 52) (aat (tempo-sync #[ (* 16 .3) b]) #'h it) (defun h ()) (defun f (time) (when (hbeat time "cc8a") (p time (nth 0 (ov-scale :c3 :minor)) 30 .1 0)) (when (hbeat time "cc8a") (p time (nth 0 (ov-scale :c4 :minor)) 30 .1 0)) (when (hbeat time "ffff") (p time (nth (pick 0 4 7 11) (ov-scale :c5 :minor)) 30 .1 0)) (when (hbeat time "ffff") (p time (pc-relative (note :c2) (+ (* (mod time 3) 7) (* (mod time 2) 2) (* (mod time 5) 4) (* (mod time 7) 3)) (scale 0 'minor)) 30 .1 2)) (when (hbeat time "ffff") (p time (pc-relative (note :c3) (+ 4 (* (mod time 3) 7) (* (mod time 2) 2) (* (mod time 5) 4) (* (mod time 7) 3)) (scale 0 'minor)) 30 .1 1)) (aat (+ time #[1 b]) #'f it)) (setf (bpm *tempo*) 120) (aat (tempo-sync #[1 b]) #'f it) (defun f ()) ;; /** Non-interpolating oscillator. Given phase in range 0-1, ;; returns value within the give k-array table. */ ;; opcode xosc, i, ik[] ;; iphase, kvals[] xin ;; indx = int(lenarray:i(kvals) * (iphase % 1)) ;; xout i(kvals, indx) ;; endop ;; (round (* 4 ;; (/ (mod (/ (node-uptime 0) *1beat*) (* 2 4)) (* 2 4)))) ;; /** Given period in beats, return current phase of global ;; clock in range [0-1) */ ;; opcode phsb, i, i ;; ibeats xin ;; iticks = ibeats * 4 ;; xout (i(gk_clock_tick) % iticks) / iticks ;; endop ;; ;; ??? ;; (/ (mod (/ (node-uptime 0) *1beat*) ;; (* 2 4)) ;; (* 2 4)) ;; xosc(phsb(2), array(0,4,7,11, 14, 18, 21, 18, 14, 11))
2,523
Common Lisp
.lisp
80
25.1125
68
0.479012
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
52241184c875ea9febe228302cfc6717644952ea4f624eb015fd0b5a55e81f07
9,247
[ -1 ]
9,248
rsg4.lisp
azimut_shiny/compositions/drafts/meaning/rsg4.lisp
(in-package #:shiny) ;; requires azimut/rocketman ;; load "rsg4.rocket" (freset) (setf (bpm *tempo*) 120) (defun f ()) (progn (fg 2f0) (fp 0 71) (fp 1 70) (fp 2 70) (fp 3 68) ;; ;; (fpan 2 120) ;; (fpan 3 5) ;;(fspread 2 t) (fspread 3 nil) ) (fp 4 47) (let ((s (scale 0 'minor)) (v (vector 0 0)) (l)) (defun g (time) ;;#+nil (and (or (< .99 (incandescent::rocket-get "song:ter.appear") 1.1) (odds (incandescent::rocket-get "song:ter.appear"))) (setf (svref v 1) (beat)) (p time (setf l (pc-random 60 75 s)) 80 .5 1)) ;;#+nil (and (or (< .9 (incandescent::rocket-get "song:cua.appear") 1.1) (odds (incandescent::rocket-get "song:cua.appear"))) (when (zerop (mod (beat) 2)) (setf (svref v 0) (beat)) (p (+ #[.25 b] time) (ivar (stutter (make-chord-fixed 72 3 s)) 1) 70 1 3))) ;;#+nil (and (odds .1) (pa time (stutter (make-chord-fixed (min 84 (pc-quantize (+ 24 (rsinr 60 10 6)) s)) 3 s)) 80 .5 4 .2)) ;;#+nil (when (or (< .9 (incandescent::rocket-get "song:sec.appear") 1.1) (and (odds (incandescent::rocket-get "song:sec.appear")) (= 3.5 (mod (beat) 4f0)))) (p time 48 40 2 1)) ;;#+nil (setf incandescent::*scene-index* (floor (incandescent::rocket-get "scene"))) (p time (pc-relative 60 (ivar (list 0 0 (pick 2 2 2 1) 0) .5) s) (floor (* (incandescent::rocket-get "song:main.volume") (ivar (transpose '(30 30 35 30) (if (position (beat) v :test #'=) 0 5)) .5))) .35 0) (setf l nil) (aat (+ time #[.5 b]) #'g it))) (let ((time (tempo-sync #[.5 b]))) (at time #'incandescent::rocket-pause-toggle) (aat time #'g it)) (defun g ())
2,104
Common Lisp
.lisp
70
20.828571
81
0.453918
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
aa902fc73abfa32206eb32b743b42a58e8bfc65f54567cea0904e0e49136d697
9,248
[ -1 ]
9,249
foxdot5.lisp
azimut_shiny/compositions/drafts/foxdot/foxdot5.lisp
(in-package :shiny) ;; ;; ten-lines-or-less/industrialis.py ;; (ql:quickload :shiny/foxdot) (setf *fx-path* "/home/sendai/.local/lib64/python3.4/site-packages/FoxDot/snd/") (clean-buffers) (fg 2f0) (fx-load-simple "x/lower/0_kick_drum.wav" "x") (fx-load-simple "_/hyphen/0_hihat_closed.wav" "-") (fx-load-simple "d/lower/0_wood.wav" "d") (fx-load-simple "v/lower/0_low_bass.wav" "v") (fx-load-simple "v/upper/heavy 0.wav" "V") (fx-load-simple "_/colon/hh01.wav" "_") (fx-load-simple "o/lower/1_snare_drum.wav" "o") (setf (bpm *tempo*) 160d0) ;; d1 >> play(P["V::"][:16] & P["<v >< |o1| >"], drive=0.1, rate=1.2) (destructuring-bind (p1 p2 p3) (fx-pat "<(_v)__(Vv)><v >< o >") (defun f (time) (bbplay (next p1) :amp .1 :rate 1.2) (bbplay (next p2) :amp .4 :rate 1.2) (bbplay (next p3) :amp .4 :rate 1.2) (aat (+ time #[1 b]) #'f it))) (aat (tempo-sync #[4 b]) #'f it) (defun f ()) ;; cp >> play("* ") (fx-load-simple "_/asterix/0_clap.wav" "*") (let ((p1 (fx-pat "* "))) (defun g (time) (bbplay (next p1) :amp .1 :lpf 500) (aat (+ time #[1 b]) #'g it))) (aat (tempo-sync #[1 b]) #'g it) (defun g ()) ;; these will work better (or at all) on synth ;; b1 >> bass(dur=1/4, formant=PRand(8)[:8], rate=PRand(5,10)[:8], pan=PWhite(-1,1)) (fp 2 0) (let ((vel (make-line (iota 40 :start 0))) (m1 (make-metre '(8 4 2) .5))) (defun bass (time) (if (funcall m1 time 1) (progn (p time 72 (next vel) 1/4 2) (p (+ #[.125 b] time) 72 (next vel) 1/4 2)) (progn (fpan 2 (pick 0 127)) (p time 60 (next vel) 1/4 2))) (fpitch 2 (+ 8192 (round (* (between 5 10) (/ 8192 12))))) (aat (+ time #[1/4 b]) #'bass it))) (aat (tempo-sync #[1/4 b]) #'bass it) (defun bass ()) ;; b2 >> sawbass(var([0,5,2,[3,6]],[8,6,1,1]), dur=PDur(3,8)).spread() (let ((dur (make-cycle (pdur 3 8))) (var (var '(0 5 2 3) '(8 6 1 1))) (scale (ov-scale :c4 :minor))) (defun h (time) (let ((d (next dur))) (p time (nth (funcall var) scale) 40 d 0) (p time (nth (funcall var) scale) 40 d 1) (aat (+ time #[d b]) #'h it)))) ;; Spread (let ((pg 116)) (fpitch 1 (+ 8192 (round (* .125 (/ 8192 12))))) (fpitch 0 (+ 8192 (round (* .125 (/ 8192 12))))) (fpan 0 0) (fpan 1 127) (fp 1 pg) (fp 0 pg)) (freset) (aat (tempo-sync #[1 b]) #'h it) (defun h ())
2,436
Common Lisp
.lisp
73
29.684932
84
0.530812
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
842e6f8b9dccc54342c6a6fd6b9867f0b4460debfba053bbd588bece508586e2
9,249
[ -1 ]
9,250
foxdot.lisp
azimut_shiny/compositions/drafts/foxdot/foxdot.lisp
(in-package x#:shiny) (setf *fx-path* "/home/sendai/.local/lib64/python3.4/site-packages/FoxDot/snd/") (fx-clear) (setf (bpm *tempo*) 100) ;; Clock.bpm=100; Scale.default="minor" ;;p1 >> pulse([0,-1,-2,-3], dur=8, lpf=600, lpr=0.2, crush=8) + (0,2,4,const(6)) (dsp! dsp-pulse (freq amp dur atk rel cutoff-freq lpr (dw fixnum)) (:defaults 440 .1 1 .001 .4 1000 1 8) (with-samples ((i (pulse (* dw freq) amp)) (i (lpf i cutoff-freq lpr)) (i (incudine.vug:downsamp dw i)) (i (* i (envelope (make-perc atk rel) 1 dur #'incudine:free)))) (stereo i))) (let ((note (make-cycle '(0 -1 -2 -3))) (scale (scale 0 'minor))) (defun f (time) (let ((n (next note))) (dsp-pulse (midihz (pc-relative (note :c4) n scale)) .1 8 .001 .9 600 .2 2) (dsp-pulse (midihz (pc-relative (note :c4) (+ 4 n) scale)) .1 8 .1 .9 600 .2 2) (aat (+ time #[3.5 b]) #'dsp-pulse (midihz (pc-relative (note :c4) (+ (pick 2 -2 2) n) scale)) .1 8 .1 .9 600 .2 2)) (aat (+ time #[8 b]) #'f it))) (aat (tempo-sync #[1 b]) #'f it) (defun f ()) ;;-------------------------------------------------- (fx-load "x/lower/0_kick_drum.wav" "x") (fx-load "v/lower/0_low_bass.wav" "v") (fx-load "o/lower/0_snare_drum.wav" "o") (fx-load-simple "x/lower/0_kick_drum.wav" #\x) (fx-load-simple "v/lower/0_low_bass.wav" #\v) (fx-load-simple "o/lower/0_snare_drum.wav" #\o) ;; d1 >> play("(x )( x)o{ vx[xx]}", crush=16, rate=.8) ;; .every([24,5,3], "stutter", 4, dur=3) (let ((p1 (fx-pat "(x )( x)o{ vx[xx]}")) (m1 (make-metre '(24 5 3) .5))) (defun d1 (time) (let ((n (next p1))) ;;(if (funcall m1 time 1)) (fx-play n :rate .8 :downsamp 16 :dur .3 :amp .2) ;;(fx-play (repeat 4 (ensure-list n)) :rate .8 :downsamp 16 :dur .3 :amp .2) ) (aat (+ time #[.3 b]) #'d1 it))) (let ((p1 (fx-pat "(x )( x)o{ vxX}")) (m1 (make-metre '(24 5 3) .5))) (defun d1 (time) (if (funcall m1 time 1) (let ((n (next p1))) (bbplay n :lpf 400 :amp .1 :downsamp 16 :rate 2) (at (+ time #[.15 b]) #'bbplay n :lpf 400 :amp .1 :downsamp 16 :rate 2)) (progn (bbplay (next p1) :amp .2 :downsamp 16 :rate .8 :lpf 400))) (aat (+ time #[.3 b]) #'d1 it))) (aat (tempo-sync #[.2 b]) #'d1 it) (defun d1 ()) (let ((dur (make-cycle (list (make-cycle (make-cycles 1 '(x NIL) '(NIL x) 'o '(x xx v NIL)) (make-cycle '(24 5 3))) (make-cycle (make-cycles 4 '(x NIL) '(NIL x) 'o '(x xx v NIL)) 3))))) (defun g (time &optional (beat 0)) (when-let ((n (print (next dur)))) (case n (x (bbplay n :amp .3 :downsamp 16 :rate .8)) (v (bbplay n :amp .3 :downsamp 16 :rate .8)) (xx (progn (at (+ time #[.1 b]) #'bbplay 'x :amp .3 :rate 2 :downsamp 16 :rate .8) (bbplay 'x :amp .3 :rate 2 :downsamp 16 :rate .8))) (o (bbplay n :amp .3 :downsamp 16 :rate .8)))) (aat (+ time #[.2 b]) #'g it (+ beat .2)))) (aat (tempo-sync #[1 b]) #'g it) (defun g ()) ;;-------------------------------------------------- (fx-load "_/hyphen/0_hihat_closed.wav" "-") (fx-load "s/lower/0_shaker.wav" "s") (fx-load "_/tilde/0_ride.wav" "~") (fx-load "_/asterix/0_clap.wav" "*") ;;d2 >> play("<-s>< ~*~>").every(30.5, "jump", cycle=32) ;; hot to jump? (let ((tempo (make-metro 220))) (destructuring-bind (p1 p2) (fx-pat "<-s>< ~*~>") (defun d (time) (when (funcall tempo 'at-beat 30) (next p1 2) (next p2 2)) (fx-play (next p1) :amp .2 :lpf 500) (fx-play (next p2) :amp .1 :lpf 500) (aat (+ time #[.3 b]) #'d it)))) (defun d ()) (aat (tempo-sync #[1 b]) #'d it)
3,942
Common Lisp
.lisp
102
31.95098
82
0.482218
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
775205c93f83c877cfeea2a784efcfdc824a7d2600031b7d68813c15aa3ec624
9,250
[ -1 ]
9,251
foxdot3.lisp
azimut_shiny/compositions/drafts/foxdot/foxdot3.lisp
(in-package #:shiny) ;; "ghost-in-the-machine.lisp" ;; scuffer version of FoxDot's song "ghost-in-the-machine.py"[1] ;; using lisp's "Common Music" patterns. And some custom helpers[2]. ;; ;; [1]: github.com/Qirky/ten-lines-or-less ;; [2]: github.com/azimut/shiny ;;-------------------------------------------------- ;; Scale.default="minor"; Clock.bpm=120 (setf (bpm *tempo*) 120f0) ;;-------------------------------------------------- ;; d1 >> play("G(:-)", rate=-1/2, ;; pshift=var([0,3],[6,2])+(0.1,0), ;; pan=(-1,1), ;; room=1, ;; amp=2) (bbuffer-load "/home/sendai/.local/lib64/python3.4/site-packages/FoxDot/snd/g/upper/0_Stab.wav" 'G) (bbuffer-load "/home/sendai/.local/lib64/python3.4/site-packages/FoxDot/snd/_/colon/hh01.wav" 'C) (bbuffer-load "/home/sendai/.local/lib64/python3.4/site-packages/FoxDot/snd/_/hyphen/0_hihat_closed.wav" '-) ;; TODO: pshift, room (let ((notes (fx-pat "G(:-)"))) (defun d1 (time) (fx-play (next notes) :rate -.5 :rpitch (ivar '(0 3) '(6 2)) :pan (ivar '(.1 .9) 2) :amp .3) (aat (+ time #[1 b]) #'d1 it))) (aat (tempo-sync #[1 b]) #'d1 it) (defun d1 ()) ;;-------------------------------------------------- ;; d2 >> play("x-", sample=2).sometimes("stutter", 4, dur=3) (bbuffer-load "/home/sendai/projects/FoxDot/FoxDot/snd/x/lower/2_kick_drum.wav" 'x)o (bbuffer-load "/home/sendai/projects/FoxDot/FoxDot/snd/_/hyphen/2_hihat_closed.wav" '-) ;; TODO: usage of make-weighting is WRONG there (let ((notes (fx-pat "x-"))) (defun d2 (time) (if (sometimes) (fx-play (fx-stutter (ensure-list (next notes)) 4) :amp .4 :dur 3) (fx-play (next notes) :amp .4)) (aat (+ time #[1 b]) #'d2 it))) (aat (tempo-sync #[4 b]) #'d2 it) (defun d2 ()) ;;-------------------------------------------------- ;; d3 >> play(" I ", sample=2, ;; hpf=(0,2000), ;; lpf=(300,0), ;; hpr=0.5) (bbuffer-load "/home/sendai/projects/FoxDot/FoxDot/snd/i/upper/2_rock_snare.wav" 'I) (let ((notes (fx-pat " I "))) (defun d3 (time) (fx-play (next notes) :amp .5 :lpf (ivar '(300 0) 2) :lpr .5 :hpf (ivar '(0 2000) 2) :hpr .5) (aat (+ time #[1 b]) #'d3 it))) (aat (tempo-sync #[4 b]) #'d3 it) (defun d3 ()) ;;-------------------------------------------------- ;; b1 >> dbass(var([0,6,5,2],[6,2]), ;; dur=PDur(3,8,[0,2]), ;; sus=2, ;; chop=4, ;; rate=4) (let ((scale (ov-scale :C5 :minor)) (dur (make-cycle (list (make-cycle (pdur 3 8 0)) (make-cycle (pdur 3 8 2))))) (notes (var '(0 6 5 2) '(6 2 6 2)) ;;(make-cycle (make-var '(0 6 5 2) '(6 2 6 2))) )) (defun b1 (time) (let ((d (next dur))) (clc 23 (nth (next notes) scale) (rcosr 30 5 5) d) (aat (+ time #[d b]) #'b1 it)))) (aat (tempo-sync #[4 b]) #'b1 it) (defun b1 ()) ;;-------------------------------------------------- ;; p2 >> blip([0,1,[[3,4],2]], dur=[4,3,1], ;; drive=PWhite(0.2,0.7), ;; oct=6, ;; lpf=2000, ;; room=1/2, ;; echo=0.75, ;; echotime=6, ;; sus=1).penta().spread() (let* ((dur (make-cycle '(4 3 1))) (scale (ov-scale :C6 :pentatonic)) ;; NOTE: cannot use (make-var) as this is a sub-sub pattern (notes (make-cycle (list 0 1 (make-cycle (list (make-cycle '(3 4) 1) 2) 1))))) (defun p2 (time) (let ((d (next dur))) (p time (nth (next notes) scale) 40 d 0) (aat (+ time #[d b]) #'p2 it)))) (aat (tempo-sync #[4 b]) #'p2 it) (defun p2 ()) (fp 0 0) ;;-------------------------------------------------- ;;k1 >> klank(oct=5, lpf=200, lpr=0.5) (dsp! dsp-klank (freq1 freq2 freq3 freq4 freq5 freq6 freq7 freq8 amp lpf lpr) (:defaults 523.2503 587.32855 622.253 698.4553 783.98944 830.608 932.3258 1046.5002 .01 200 .5) (with-samples ((n (white-noise)) ;;(n (* n (impulse 2 1 .1))) ;;(n 523.2503) (in (+ (incudine.vug:ringz n freq1 1) (incudine.vug:ringz n freq2 1) (incudine.vug:ringz n freq3 1) (incudine.vug:ringz n freq4 1))) ;;(in (downsamp 2 in)) (in (lpf in lpf lpr)) (in (* amp in))) (stereo in))) (defun k1 ()) (incudine:free (node 25)) (let* ((scale (ov-scale :C5 :minor)) (notes (nths '(0 1 2 3) scale)) (midinotes (mapcar #'midihz notes))) (defun k1 (time) (setf *instances* (between 10 100)) (setf *mul* 1f0) (destructuring-bind (a b c d) midinotes (dsp-klank a b c d :amp .001 :lpf 200 :lpr .5 :id 100)) ;;(aat (+ time #[1 b]) #'k1 it) )) (aat (tempo-sync #[4 b]) #'k1 it) (set-control 100 :amp .0001) (incudine:free (node 100))
5,223
Common Lisp
.lisp
134
33.38806
108
0.455296
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
1276ec0b19a1b87bc9dc551b96acac3c8de4ee41add7c66e3788f93b727cbec6
9,251
[ -1 ]
9,252
foxdot7.lisp
azimut_shiny/compositions/drafts/foxdot/foxdot7.lisp
(in-package :shiny) (setf *fx-path* "/home/sendai/.local/lib64/python3.4/site-packages/FoxDot/snd/") (fx-clear t) (fx-load "x/upper/" "X") (fx-load "o/lower/" "o") (fx-load "_/hyphen/" "-") (fx-load "_/forwardslash/" "/") (freset) (fp 0 33) (fp 1 11) ;; bd >>play ("(X[--])", amp=6,dur=0.5) ;; hh >>play ("-", amp=4,dur=0.25) ;; sn >>play ("(o )/", amp=2,sus=0.1) (destructuring-bind (p1 p2 p3) (fx-pat "<X[--]><-><(o )/>") (defun bd (time) (fx-play (next p1) :amp .1 :dur .5) (aat (+ time #[.5 b]) #'bd it)) (defun hh (time) (fx-play (next p2) :amp .05) (aat (+ time #[.25 b]) #'hh it)) (defun sn (time) (fx-play (next p3) :amp .025) (aat (+ time #[1 b]) #'sn it))) (defun bd ()) (defun hh ()) (defun sn ()) (aat (tempo-sync #[.5 b]) #'bd it) (aat (tempo-sync #[.25 b]) #'hh it) (aat (tempo-sync #[1 b]) #'sn it) ;; b1 >>bass(var([2,1,6,4],8), dur=4, chop=(8,5), bits=(4,3), pan=(-1,1), amp=1/2) (fp 0 52) (let ((scale (ov-scale :c4 :harmonic-minor)) (var (var '(2 1 6 4) 8)) (pan (make-cycle '(0 127)))) (defun b1 (time) ;;(fpan 0 (next pan)) (clc 21 (transpose (next var) 60) 30 1) ;;(p time (nth (next var) scale) 40 1 0) (aat (+ time #[2 b]) #'b1 it))) (aat (tempo-sync #[4 b]) #'b1 it) (defun b1 ()) ;; b2 >>bass(dur=4, chop=(8,5), bits=(4,3), pan=(-1,1), amp=1/2) (fp 1 0) (let ((pan (make-cycle '(0 127)))) (defun b2 (time) ;;(fpan 1 (next pan)) ;;(p time 60 40 4 1) (clc 25 60 40 1) (aat (+ time #[4 b]) #'b2 it))) (aat (tempo-sync #[4 b]) #'b2 it) (defun b2 ()) ;; b3 >>bass(([0, 1.1, 2, 0, 1.4]),chop=2, dur=0.5,rate=PRange (3)/4).solo() (let ((var (make-cycle '(0 1 2 0 1))) (scale (ov-scale :c4 :harmonic-minor))) (defun b3 (time) ;; (fluidsynth:all-notes-off *synth* 1) ;; (fluidsynth:all-notes-off *synth* 0) ;; (p time (nth (next var) scale) 40 (cosr .3 .1 5) 2) (clc 21 (nth (next var) scale) 40 (cosr .3 .1 5)) (aat (+ time #[.5 b]) #'b3 it))) (fp 2 68) (aat (tempo-sync #[.5 b]) #'b3 it) (defun b3 ())
2,070
Common Lisp
.lisp
64
29.546875
82
0.518741
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e78af0cbc0755ea42594fb11e8e7eef241b1120ae8cda6ef1cdb350e508aee7f
9,252
[ -1 ]
9,253
foxdot4.lisp
azimut_shiny/compositions/drafts/foxdot/foxdot4.lisp
(in-package #:shiny) (setf *fx-path* "/home/sendai/.local/lib64/python3.4/site-packages/FoxDot/snd/") (fx-clear) ;; Scale.default="minor" ;; Clock.bpm=140 (setf (bpm *tempo*) 140f0) ;; c1 >> play("@", dur=1/4, ;; sample=P[:8].rotate([0,1,3]), ;; rate=4, ;; pan=-0.5) (fx-load "_/at/" #\@) (let ((s (make-cycle (fx-rotate (range 0 7) '(0 1 3))))) (defun c1 (time) (fx-play "@" :sample (next s) :amp .2 :rate 4 :pan .25) (aat (+ time #[.25 b]) #'c1 it))) (aat (tempo-sync #[.25 b]) #'c1 it) (defun c1 ()) ;; c2 >> play("#", dur=40, ;; room=1, ;; amp=2, ;; pan=0.5) (fx-load "_/hash/0_crash.wav" #\#) (defun c2 (time) (fx-play "#" :amp .2 :pan .75) (aat (+ time #[40 b]) #'c2 it)) (aat (tempo-sync #[40 b]) #'c2 it) (defun c2 ()) ;; d1 >> play("<V:>< * ><[--]>") (fx-load "v/upper/heavy 0.wav" #\V) (fx-load "_/colon/hh01.wav" #\:) (fx-load "_/asterix/0_clap.wav" #\*) (fx-load "_/hyphen/0_hihat_closed.wav" #\-) (destructuring-bind (p1 p2 p3) (fx-pat "<V:>< * ><[--]>") (defun d1 (time) (fx-play (next p1) :amp .2) (fx-play (next p2) :amp .2 :lpf 500) (fx-play (next p3) :amp .2) (aat (+ time #[1 b]) #'d1 it))) (aat (tempo-sync #[1 b]) #'d1 it) (defun d1 ()) ;; b1 >> dbass(dur=PDur(3,8), ;; sus=2, ;; chop=4, ;; shape=PWhite(0,1/2), ;; pan=PWhite(-1,1)) ;; .sometimes("offadd", 4) + var([0,2],4) ;; offadd, adds a new voice 4 sem "sometimes" in this case ;; var() in this case is used to add the 0 or 2 each 4 beats to both 2 or single note (let* ((dur (make-cycle (pdur 3 8))) (pan (make-weighting '(0 127))) (pan (make-cycle '(.01 .99))) (offset (make-cycle (make-var '((0 2) 4) 1))) (va1r (var '(0 2) 4)) (note (make-cycle (list (make-cycle '(0) (pval (between 4 12))) 4)))) (defun b1 (time) (let ((d (next dur))) ;;(fpan 0 (next pan)) (csound-chnset (next pan) "VoxHumana.pan") (and (< 4 (mod (round (/ (node-uptime 0) *1beat*)) 16) 16) (at (+ #[(/ d 2) b] time) #'clc 23 (pc-relative (note :c4) (+ 4 (next var)) (scale 0 'minor)) (rcosr 70 5 5) (* 2 d))) ;;#+nil (clc 23 (pc-relative (note :c3) (next var) (scale 0 'minor)) (rcosr 70 5 5) (* 2 d)) (aat (+ time #[d b]) #'b1 it)))) (fp 0 1) (fg 2f0) (aat (tempo-sync #[1 b]) #'b1 it) (defun b1 ()) ;; p1 >> space([7,6,4,P*(2,1),0], ;; dur=8, ;; pan=(-1,1)) ;;Master().hpf=var([0,4000],[76,4])
2,860
Common Lisp
.lisp
83
28.831325
85
0.444043
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
c6a9b88994a2cfd166d21d17add20226bf06a9e3cccf1cc974e2b25813285885
9,253
[ -1 ]
9,254
pads.lisp
azimut_shiny/compositions/drafts/foxdot/pads.lisp
(in-package #:shiny) ;; https://www.youtube.com/watch?v=k-v1Ibt1pW4 (freverb-toggle) (freverb-preset 5) (fg 1f0) ;; PxRand ;; shape ;; mix ;; pshift ;; lpf (let ((scale (ov-scale :c4 :pentatonic))) (defun f (time) (fpan 0 (between 0 127)) (p time (nth (between 0 8) scale) 40 4 0) (aat (+ time #[4 b]) #'f it))) (aat (tempo-sync #[4 b]) #'f it) (defun f ()) (fx-load "/x/lower/0_kick_drum.wav" 'x) (fx-load "/x/lower/1_kick_drum.wav" 'x) (fx-load "/x/lower/2_kick_drum.wav" 'x) (fx-load "/x/lower/3_kick_drum.wav" 'x) (fx-load "/_/hyphen/0_hihat_closed.wav" '-) (fx-load "/_/hyphen/1_hihat_closed.wav" '-) (fx-load "/_/hyphen/2_hihat_closed.wav" '-) (fx-load "/_/hyphen/3_hihat_closed.wav" '-) (fx-load "/d/lower/0_wood.wav" 'd) (bbplay (fx-buf 'd)) (let ((pat (make-cycle (list (make-cycle '(x -) 1) '- (make-weighting '(- x) 1) (make-weighting '(x -) 1) 'd '- '- '-)))) (defun g (time) (bbplay (print (fx-buf (print (next pat)) 0)) :amp .2) (aat (+ time #[1 b]) #'g it))) (aat (tempo-sync #[1 b]) #'g it) (defun g ()) (setf (bpm *tempo*) 220d0)
1,193
Common Lisp
.lisp
43
23.348837
58
0.536713
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
4292b345dff78715470b7628981d5e2bb9835bae8711354b571f2934e71adc05
9,254
[ -1 ]
9,255
foxdot2.lisp
azimut_shiny/compositions/drafts/foxdot/foxdot2.lisp
(in-package #:shiny) ;; Scuffed version of "crushed-dreams.py" ;; From "Qirky/ten-lines-or-less" (setf (bpm *tempo*) 144f0) (freverb-toggle 1) (freverb :roomsize .25d0 :level 40d0 :width 10d0) (freset) (fg 2f0) (fp 0 18);; (fp 0 0) (fpan 0 60) ;; C1 >> blip(((0,2,4,6) + var([0,3],[24,8])) % 7, ;; dur=8, ;; sus=2, ;; echo=0.75, ;; echotime=8, ;; lpf=3000, lpr=0.2, ;; room=0.25).spread() (let* ((scale (ov-scale :C5 :harmonic-major)) (e (cm:new cm:transposer :of '(0 2 4 6) :stepping (make-cycle (make-var '(0 3) '(3 1)))))) (defun f (time) (p time (nths (mapcar (lambda (x) (mod x 7)) (next e)) scale) 50 8 0) (aat (+ time #[8 b]) #'f it))) (defun f ()) (aat (tempo-sync #[1 b]) #'f it) ;; p1 >> sinepad([0,4,[6,[8,9]],7], ;; dur=1/2, ;; sus=1, ;; drive=0.1, ;; room=1, ;; lpf=expvar([20,2000],32)) ;; .sometimes("rotate") + var([0,2],[12,4]) ;; p2 >> pads(p1.pitch, ;; dur=PDur(3,8)*4, ;; pan=PWhite(-1,1), ;; chop=4, ;; oct=4) (fg 2f0) (let ((scale (ov-scale :C5 :harmonic-major)) (r (make-cycle (list (make-cycle '(0) (make-weighting '(4 5 6 7 8 9 10 11 12))) (make-cycle '(0 1 2 3) 1)))) (e (make-cycle (list (list 0 4 6 7) (list 0 4 8 7) (list 0 4 6 7) (list 0 4 9 7))))) (defun fff (time) (p time (cm:transpose (nths (cm:pattern-value e) scale) -12) 40 2.5 0) (aat (+ time #[2.5 b]) #'fff it)) (defun ff (time) (let* ((c (next e)) (notes (nths (copy-list c) scale))) (if (odds .5) (pa time (cm:transpose (alexandria:rotate notes (next r)) -24) (rcosr 30 5 2) .25 1 .25) (p time notes (rcosr 50 5 2) .5 3)) ) (aat (+ time #[.5 b]) #'ff it))) (defun ff ()) (defun fff ()) (aat (tempo-sync #[1 b]) #'ff it) (aat (tempo-sync #[1 b]) #'fff it) ;;-------------------------------------------------- ;;-------------------------------------------------- ;;-------------------------------------------------- (clean-buffers) (bbuffer-load "/home/sendai/projects/FoxDot/FoxDot/snd/x/lower/1_kick_drum.wav") (bbuffer-load "/home/sendai/projects/FoxDot/FoxDot/snd/x/lower/2_kick_drum.wav") (bbuffer-load "/home/sendai/projects/FoxDot/FoxDot/snd/s/lower/1_shaker.wav") (bbuffer-load "/home/sendai/projects/FoxDot/FoxDot/snd/s/lower/2_shaker.wav") (bbuffer-load "/home/sendai/projects/FoxDot/FoxDot/snd/d/lower/1_wood.wav") (bbuffer-load "/home/sendai/projects/FoxDot/FoxDot/snd/d/lower/2_wood.wav") (bbuffer-load "/home/sendai/projects/FoxDot/FoxDot/snd/_/at/gb_noise (1).wav") (bbuffer-load "/home/sendai/projects/FoxDot/FoxDot/snd/_/at/gb_noise (2).wav") (bbuffer-load "/home/sendai/projects/FoxDot/FoxDot/snd/h/lower/snap_1.wav") (bbuffer-load "/home/sendai/projects/FoxDot/FoxDot/snd/h/lower/snap_2.wav") (bbuffer-load "/home/sendai/projects/FoxDot/FoxDot/snd/b/lower/dot (1).wav") (bbuffer-load "/home/sendai/projects/FoxDot/FoxDot/snd/b/lower/dot (2).wav") (bbuffer-load "/home/sendai/projects/FoxDot/FoxDot/snd/_/plus/wb_1.wav") (bbuffer-load "/home/sendai/projects/FoxDot/FoxDot/snd/_/plus/wb_2.wav") (defparameter *fx-instruments* (make-hash-table :test #'equal)) (defun fx-get (instrument &optional (sample 0)) (gethash (gethash (list instrument sample) *fx-instruments*) *buffers*)) (setf (gethash (list '+ 1) *fx-instruments*) "wb_1.wav") (setf (gethash (list '+ 2) *fx-instruments*) "wb_2.wav") (setf (gethash (list 'x 1) *fx-instruments*) "1_kick_drum.wav") (setf (gethash (list 'x 2) *fx-instruments*) "2_kick_drum.wav") (setf (gethash (list 's 1) *fx-instruments*) "1_shaker.wav") (setf (gethash (list 's 2) *fx-instruments*) "2_shaker.wav") (setf (gethash (list 'd 1) *fx-instruments*) "1_wood.wav") (setf (gethash (list 'd 2) *fx-instruments*) "2_wood.wav") (setf (gethash (list '@ 1) *fx-instruments*) "gb_noise (1).wav") (setf (gethash (list '@ 2) *fx-instruments*) "gb_noise (2).wav") (setf (gethash (list 'h 1) *fx-instruments*) "snap_1.wav") (setf (gethash (list 'h 2) *fx-instruments*) "snap_2.wav") (setf (gethash (list 'b 1) *fx-instruments*) "dot (1).wav") (setf (gethash (list 'b 2) *fx-instruments*) "dot (2).wav") ;; This one actually, plays the 4 stutter in the time slot of 1 (?, every 3 cycles ;; d1 >> play("x",sample=1,crush=16,amp=1).every(3, "stutter", 4, pan=[-1,1]) ;; ;; d1 >> play("<(x )(sx)d(@hb)>< + +( [ +])>", ;; sample=var([1,2]), ;; crush=var([16,32],2), ;; amp=var([1,0],[60,4])) ;; .every(3, "stutter", 4, dur=var([3,1],[7,3]), rate=2, pan=[-1,1]) ;; (let ((crush (make-cycle '(16 16 32 32))) (sam (make-cycle '(1 2))) (other (make-cycle (list (make-cycle (make-var '(NIL + NIL + (NIL ++)) 1) 3) (make-cycle (make-var '(NIL + NIL + (NIL ++)) 4) (make-cycle '(3 1)))))) (notes (make-cycle (list (make-cycle (make-var '((x NIL)(s x)d(@ h b)) 1) 3) (make-cycle (make-var '((x NIL)(s x)d(@ h b)) 4) (make-cycle '(3 1))))))) (defun d1 (time) (let ((pan (pick 0f0 1f0)) (s (next sam)) (crushed (next crush))) (when-let ((n (next other))) (case n (+ (bbplay (fx-get n s) :rate 1 :amp .3 :pan pan :downsamp crushed)) (++ (at (+ time #[.15 b]) #'bbplay (fx-get '+ s) :rate 2 :amp .3 :pan pan :downsamp crushed)))) (when-let ((n (next notes))) (bbplay (fx-get n s) :amp .2 :rate 1 :downsamp crushed :pan pan))) (aat (+ time #[.5 b]) #'d1 it))) (defun d1 ()) (aat (tempo-sync #[1 b]) #'d1 it)
6,178
Common Lisp
.lisp
152
34.164474
87
0.513064
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
50e1d080d9b8b7fd5ca65df946dbff820835b6a4437db21380861db91909904f
9,255
[ -1 ]
9,256
foxdot8.lisp
azimut_shiny/compositions/drafts/foxdot/foxdot8.lisp
(in-package #:shiny) (setf *fx-path* "/home/sendai/.local/lib64/python3.4/site-packages/FoxDot/snd/") (fx-clear t) (fx-load "_/hyphen/0_hihat_closed.wav" "-") (fx-load "v/upper/" "V") (fx-load "s/lower/" "s") (fx-load "o/upper/" "O") (fx-load "u/lower/" "u") (fx-load "_/plus/" "+") (fx-load "_/at/" ".") ;; d1 >> play(" ;; <Vs> ;; <[--]> ;; <.{.+[ +]}O( [( u)O])>", lpf=var([0,1000],[28,4])) (let ((var (var '(0 1000) '(28 4)))) (destructuring-bind (p1 p2 p3) (fx-pats "<Vs><[--]><.{.+[ +]}O( [( u)O])>") (defun d1 (time) (fx-play (next p1) :lpf (next var) :amp .1 :sample (pick 0 2)) (fx-play (next p2) :lpf (next var) :dur .5 :amp .1) (fx-play (next p3) :lpf (next var) :dur .5 :amp .05) (aat (+ time #[.5 b]) #'d1 it)))) (aat (tempo-sync #[.5 b]) #'d1 it) (defun d1 ()) ;; P([3,4,5,4],7,[9,9,9,10]) is like a vector multiplication... ;; [3,7,9] [4,7,9] [5,7,9] [4,7,10] ;; p1 >> keys(([3,4,5,4],7,[9,9,9,10]), dur=4, spin=8, tremolo=4, room=1, amp=2) (let ((notes (make-cycle (make-var '((3 4 5 7) 7 (9 9 9 10)) 1)))) (defun p1 (time) (clc 23 (transpose (next notes 3) 60) 30 .5) (aat (+ time #[2 b]) #'p1 it))) (aat (tempo-sync #[2 b]) #'p1 it) (defun p1 ()) ;; p2 >> sawbass(var([1,0,-2,-4],4), dur=1/2, amp=[1,1,0,1]).sometimes("amp.trim", 3) ;; p3 >> star(p2.pitch + (P[1,0,1,0,1,0,0,2,1,0]), dur=PDur([5,1,2,2],8)*2, sus=2, oct=6) (let ((var (var '(1 0 -2 -4) 4)) (amp (make-cycle '(1 1 0 1))) (amp2 (make-cycle '(1 1 0))) ;; (off (make-cycle '(1 0 1 0 1 0 0 2 1 0))) (dur (make-cycle '(2.5 .5 1 1)))) (defun p2 (time) (clc 22 (transpose (next var) 60) (* (if (sometimes) (next amp2) (next amp)) 30) .125) (aat (+ time #[.25 b]) #'p2 it)) (defun p3 (time) (let ((d (next dur))) (clc 12 (+ (transpose (next var) (+ 60 24)) (next off)) 10 (* 2 d)) (aat (+ time #[d b]) #'p3 it)))) (aat (tempo-sync #[.5 b]) #'p2 it) (defun p2 ()) (aat (tempo-sync #[2.5 b]) #'p3 it) (defun p3 ()) ;; # Add for some variety ;; p3.sometimes("offadd", 4) + var([0,2],[PRand([0,2,4])])
2,235
Common Lisp
.lisp
63
30.428571
89
0.476256
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
73d0a8b172b01fe142f89f70653ab88aa08c3d5b8d57642996f59cd2947458ae
9,256
[ -1 ]
9,257
foxdot6.lisp
azimut_shiny/compositions/drafts/foxdot/foxdot6.lisp
(in-package #:shiny) ;; ;; glow.py ;; (setf *fx-path* "/home/sendai/.local/lib64/python3.4/site-packages/FoxDot/snd/") (shiny::clean-buffers) (fx-load-simple "x/lower/0_kick_drum.wav" "x") (fx-load-simple "o/lower/0_snare_drum.wav" "o") (fx-load-simple "_/hyphen/0_hihat_closed.wav" "-") (fx-load-simple "_/equals/0_hihat_open.wav" "=") ;; d1 >> play("x o x - o = x - - = o x ") (let ((p1 (fx-pat "x o x - o = x - - = o x "))) (defun d1 (time) (fx-play (next p1) :amp .5) (aat (+ time #[1 b]) #'d1 it))) (aat (tempo-sync #[1 b]) #'d1 it) (defun d1 ()) ;; d2 >> play("-- -- ---") (let ((p1 (fx-pat "-- -- ---"))) (defun d2 (time) (fx-play (next p1) :amp .5) (aat (+ time #[1 b]) #'d2 it))) (aat (tempo-sync #[1 b]) #'d2 it) (defun d2 ()) ;; b1 >> pluck([0, 3, 2], dur=[1/2, 1], oct=4) (let ((dur (make-cycle '(1/2 1))) (notes (make-cycle '(0 3 2)))) (defun b1 (time) (let ((d (next dur))) (clc 23 (transpose (next notes) 60) 30 d) (aat (+ time #[d b]) #'b1 it)))) (aat (tempo-sync #[1/2 b]) #'b1 it) (defun b1 ()) ;; p1 >> pads([0, 3, 7, 8, -2], dur=[4, 8], oct=5, amp=0.7) (let ((dur (make-cycle '(4 8))) (notes (make-cycle '(0 3 7 8 -2)))) (defun p1 (time) (let ((d (next dur))) (clc 23 (+ -12 (clc 23 (pc-relative (note :c5) (next notes) (scale 0 'minor)) 70 d)) 50 d) (aat (+ time #[d b]) #'p1 it)))) (fp 2 100) (fp 4 9) (aat (tempo-sync #[4 b]) #'p1 it) (defun p1 ())
1,486
Common Lisp
.lisp
46
29.195652
87
0.508025
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
ee4881fe15f17dc550609b8735366f1045a8c8009a237299dbb18693a3c66023
9,257
[ -1 ]
9,258
randompads.lisp
azimut_shiny/compositions/drafts/foxdot/randompads.lisp
(in-package :shiny) ;; Completely offsounding cover of: ;; https://www.youtube.com/watch?v=k-v1Ibt1pW4 ;; around 9:06 (csound-socket-send "start \"Mono\"") (let ((note (make-weighting (iota 8))) (pan (make-cycle '(.01 .99)))) (defun p1 (time) (let ((d (between 1 7))) (csound-chnset (next pan) "Mono.pan") (csound-chnset (ilinvar '(500 5000) 128) "Mono.cut") (clc "MonoNote" (pc-relative (note :c4) (next note) (scale 0 'pentatonic)) 30 (* 2 d)) (aat (+ time #[d b]) #'p1 it)))) (aat (tempo-sync #[1 b]) #'p1 it) (defun p1 ()) (let ((p1 (fx-pat "(v-)-{-v}{v-}d---"))) (defun d1 (time) (if (sometimes) (fx-play (fx-stutter (next p1) 4) :amp .2 :dur 3 :downsamp 4 :sample (if (sometimes) 2 0)) (fx-play (next p1) :amp .2 :downsamp 4 :sample (if (sometimes) 2 0))) (aat (+ time #[1 b]) #'d1 it))) (aat (tempo-sync #[1 b]) #'d1 it) (defun d1 ()) (let ((dur (make-cycle (mapcar (op (* 2 _)) (pdur 3 8))))) (defun b1 (time) (let ((d (next dur))) (clc "MonoNote" (transpose (ivar '(0 3 5 7) '(8 4 3 1)) 60) 20 d) (aat (+ time #[d b]) #'b1 it)))) (aat (tempo-sync #[1 b]) #'b1 it) (defun b1 ()) (let ((dur (make-cycle (pdur 3 8))) (var (var '(0 4) '(6 2))) (var2 (var '(0 1 2) .5))) (defun p2 (time) (let ((d (next dur))) (clc 23 (pc-relative (note :c4) (ivar '(0 4) '(6 2)) (scale 0 'minor)) (* 10 (nth-beat 2 '(1 0))) d) (clc 23 (pc-relative (note :c4) (+ 2 (next var)) (scale 0 'minor)) (* 10 (nth-beat 2 '(1 0))) d) (clc 23 (pc-relative (note :c4) (next var2) (scale 0 'minor)) (* 10 (nth-beat 2 '(1 0))) d) (aat (+ time #[d b]) #'p2 it)))) (aat (tempo-sync #[.75 b]) #'p2 it) (defun p2 ())
1,919
Common Lisp
.lisp
52
29.538462
76
0.480408
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
88d898c077612223e6afdec3ebaea220cdd6d5bcdc7f8d22c6348018e4aaaf1c
9,258
[ -1 ]
9,259
midifile5.lisp
azimut_shiny/compositions/drafts/midifile/midifile5.lisp
(in-package :shiny) (fg 2f0) (progn (defparameter *mf* "/home/sendai/Downloads/April_14th.mid") (defparameter *bass* (subseq (get-measures-pair *mf* 0 3) 0)) (defparameter *notes* (subseq (get-measures-pair *mf* 1) 0)) (defparameter *quarter* (first (get-midi-tempo *mf*)))) (setf (bpm *tempo*) 70) (let ((p 46)) (fp 0 p) (fp 6 p)) (fp 1 40) (fp 2 42) (fp 2 74) (defmethod p :around (time pitch velocity duration channel &key pan) (call-next-method)) (defmethod p :around (time pitch velocity duration channel &key pan) ;; (call-next-method) (when (numberp pitch) (if (and (= channel 0) (< 1 pitch 50)) (progn (call-next-method time pitch velocity duration channel) (call-next-method time (+ 12 pitch) (+ -10 velocity) (* .3333 4) 2)) (call-next-method))) ) (let ((bass (make-cycle *bass*)) (notes (make-cycle *notes*))) (defun f (time) ;; background + phasing (destructuring-bind (n d) (next notes) (pa time n 55 .3333 0 .3333) (pa (+ #[(cosr 1 .5 1) b] time) (butlast (transpose (reverse n) +12)) 55 .1111 0 .3333) ) ;; notes (destructuring-bind (n d) (next bass) (pa time (rn n) 60 d 1 d)) (aat (+ time #[4 b]) #'f it))) (aat (tempo-sync #[*quarter* b]) #'f it) (defun f ())
1,333
Common Lisp
.lisp
41
28.073171
78
0.5947
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
91a5c7e9d57bf2e3e936b5c047314033218143a5117b51359501f273cc80ef93
9,259
[ -1 ]
9,260
midifile3.lisp
azimut_shiny/compositions/drafts/midifile/midifile3.lisp
(in-package :shiny) (progn (defparameter *mf* "/home/sendai/Downloads/Aquatic_Ambience.mid") (defparameter *notes-lead* (get-notes *mf* 0)) (defparameter *notes-bass* (get-notes-durations-chords-silences *mf* 1)) (defparameter *notes-next* (subseq (get-measures-pair *mf* 1 18) 14)) (defparameter *quarter* (first (get-midi-tempo *mf*)))) (freset) (fp 3 87) (fp 1 0) (fp 2 2) (defun g ()) (defun f ()) ;; <3 (let ((notes (make-cycle (subseq *notes-lead* 0 63))) (onotes (make-cycle *notes-next*)) (bass (make-cycle (subseq *notes-bass* 0 9)))) (defun g (time) (destructuring-bind (n d) (next onotes) (pa time (cm:transpose n +12) 40 d 3 (d2o d))) (aat (+ time #[ (* 4 *quarter*) s]) #'g it)) (defun f (time &optional (beat 0)) (let* ((r .3) (step (* r 16))) ;;(play-phaser (next notes) r) (p time (next notes) 40 r 2) ;; (play-taupe (next notes) r) (when (= (round (mod beat step)) 0) ;; (play-taupe (+ 12 (first (next bass))) step) ;; (let ((*clef* "f") ;; (*window-name* "other"))) ;;(play-phaser (+ 12 (first (next bass))) step) (p time (+ 12 (first (next bass))) 60 step 1) ) (aat (+ time #[r b]) #'f it (+ beat r))))) (aat (tempo-sync #[*quarter* s]) #'f it) (defun f ()) (aat (tempo-sync #[*quarter* s]) #'g it) (defun g ()) (fp 2 60) (let* ((scale (reverse (ov-scale :c5 :aeolian))) (cscale (make-cycle scale)) (rhythm (make-cycle '(1 1 .5 .5 1.25 .5 1)))) (defun g (time) (let ((r (next rhythm))) (and (fluidsynth:all-notes-off *synth* 0) (p time (car (next cscale (pick 1 1 1 1 3))) 40 r 2)) (aat (+ time #[r b]) #'g it)))) (aat (tempo-sync #[1 b]) #'g it) (defun g ()) ;;-------------------------------------------------- (let ((notes (make-cycle (subseq *notes-lead* 0 20)))) (defun f (time) (let ((n (next notes))) (when (odds .1) (inscore-video "/home/sendai/bunny.mp4" 2 :alpha 100 :window-name "w2" :video-name (pick "v2" "v4" "v1") :x (between -1f0 1f0) :y (between 0 .5) :rotatez (between -40f0 40f0)) (let ((*window-name* "w2")) (p time (+ 12 n) 60 2 0))) (p time (+ -12 n) 60 .5 0)) (aat (+ time #[.5 b]) #'f it))) (inscore-reset) (inscore-video "/home/sendai/bunny.mp4" 10 :volume .8) (inscore-reset) (inscore-stream) (inscore-init) (fp 0 20) (defun f ()) (f (now)) ;;-------------------------------------------------- (defun video-show (name filepath time dur) (make-cvideo name filepath) (at (+ time #[dur b]) #'queue-delete name)) (let ((notes (make-cycle (subseq *notes-lead* 0 20)))) (defun f (time) (let ((n (next notes))) (when (odds .1) (play-) (video-show :bunny "/home/sendai/bunny.mp4" time 4)) (play-timpani n .5)) (aat (+ time #[.5 b]) #'f it))) (f (now))
3,030
Common Lisp
.lisp
87
29.022989
74
0.511779
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
5f37cb01b4ffe9059776c2ecc84506f2e997ed931db863914bcd01283be208de
9,260
[ -1 ]
9,261
midifile1.lisp
azimut_shiny/compositions/drafts/midifile/midifile1.lisp
(in-package :shiny) (defparameter *mf* "/home/sendai/Downloads/Radiohead_-_Daydreaming.mid") (defparameter *notes* (subseq (get-notes *mf*) 0 29)) (defparameter *notes* (subseq (get-notes-durations *mf*) 30 60)) (defparameter *mnotes* (cm:markov-analyze (mapcar #'car *notes*) :order 2)) (defparameter *notes* (subseq (get-notes *mf*) 0 29)) (defparameter *mnotes* (cm:markov-analyze (get-notes-durations-chords-silences *mf* 1) :order 2)) (defun f ()) (defparameter *metre* (make-metre '(4) 1)) (defparameter *notes* (subseq (get-notes *mf*) 3 30)) (let ((notes (make-cycle *notes*))) (defun f (time &optional (beat 0)) (let ((n (next notes)) (ps (odds .2)) (r .5)) (p time (+ -12 n) (rcosr 60 5 5) (+ 1 r) 0) (when (and (not ps) (= 1 (funcall *metre* beat))) (destructuring-bind (n d) (next *mnotes*) (p time (cm:transpose n +24) 70 d 1))) ;;(and ps (play-sand (+ 12 n) 2 :amp (rcosr 100 50 5))) (aat (+ time #[r b]) #'f it (+ .5 beat))))) (f (now)) (fp 0 0) (fp 0 33) (fp 1 1) (fg 1f0) (defun f ()) (defparameter *notes* (subseq (get-notes *mf*) 1020 1100)) (defparameter *metre* (make-metre '(8) 1)) (let ((notes (make-cycle *notes*))) (defun f (time &optional (beat 0)) (let ((n (next notes)) (ps (odds .2)) (r .3)) (p time (+ -12 n) (rcosr 60 5 5) (+ 1 r) 0) (when (and (not ps) (= 1 (funcall *metre* beat))) (p time (cm:transpose (car (next *mnotes*)) +24) 70 4 1)) ;;(and ps (play-sand (+ 12 n) 1 :amp (rcosr 350 50 5))) (aat (+ time #[r b]) #'f it (+ .5 beat))))) (aat (tempo-sync #[1 b]) #'f it) (defun f ())
1,664
Common Lisp
.lisp
44
33.613636
75
0.570099
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
bde967aba143a2c5869d4195aeb6428f738d98d2d83e6eb4b4d9a02cce4197f9
9,261
[ -1 ]
9,262
midifile4.lisp
azimut_shiny/compositions/drafts/midifile/midifile4.lisp
(in-package #:shiny) (progn (defparameter *mf* "/home/sendai/Downloads/Minecraft_Theme_Sweden_Calm.mid") (defparameter *bass* (get-measures-pair *mf* 0 4 2)) (defparameter *notes* (get-measures-pair *mf* 1 4 2))) (setf (bpm *tempo*) 42) (let ((measures (make-cycle *notes*)) (bass (make-cycle *bass*))) (defun f (time) (let* ((measure (next measures)) (notes (first measure)) (durations (second measure))) (pa time notes 50 durations 0 (d2o durations))) (let* ((measure (next bass)) (notes (first measure)) (durations (second measure))) (pa time notes 50 durations 0 (d2o durations))) (aat (+ time #[2 b]) #'f it))) (defun f ()) (f (now)) ;;-------------------------------------------------- (progn (defparameter *mf* "/home/sendai/Downloads/Resurrections_-_Celeste.mid") (defparameter *notes* (subseq (get-measures-pair *mf* 0 4) 2)) (defparameter *sing* (get-measures-pair *mf* 1 4)) (defparameter *quarter* (first (get-midi-tempo *mf*)))) (let ((notes (make-cycle *notes*)) (sing (make-cycle *sing*))) (defun f (time) (let* ((measure (next notes)) (notes (first measure)) (durations (second measure))) (pa time notes 40 durations 0 (d2o durations))) (let* ((measure (next sing)) (notes (first measure)) (durations (second measure))) (pa time notes 60 durations 1 (d2o durations))) (aat (+ time #[ (* *quarter* 4) s]) #'f it))) (defun f ()) (f (now)) (fg 2f0) (fp 1 0) (fp 0 1) (fp 0 49)
1,603
Common Lisp
.lisp
44
31.431818
78
0.571982
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
0f275af7f779182502ac1ce429f4a7e07d1662cc626de84bfec0c3d52aa92e58
9,262
[ -1 ]
9,263
midifile2.lisp
azimut_shiny/compositions/drafts/midifile/midifile2.lisp
(in-package :shiny) (fg 2f0) (defparameter *mf* "/home/sendai/Downloads/Chrono_Trigger_-_11_Secret_of_the_Forest.mid") (defparameter *notes* (get-notes *mf*)) (defparameter *bass* (subseq (get-notes-durations-chords-silences *mf* 1) 0 20)) (defvar *mm* (cm:markov-analyze *notes* :order 3 :print? nil)) (freverb-toggle 1) (freverb :roomsize .25d0 :level 1d0 :width 3d0) (fp 3 52) (fp 2 22) (freset) ;;<3 (let ((note (make-cycle (subseq *notes* 0 90))) (bass (make-cycle *bass*)) (s (make-metro 60))) (defun f (time &optional (beat 0)) (let ((n (next note))) (p time (+ 24 (first (next bass))) 50 .2 1 :pan (pick 0 128)) (progn (when (funcall s 'at-beat 4) (p time (+ -12 n) 40 1 3)) (p time (+ -12 n) 40 .3 0)) ;;(p time (next *mm*) 30 .1 2) ;;(play-taupe (+ -12 n) .3 :amp 200 :ramp (rcosr 10 5 1) :rfreq 1000) ) (aat (+ time #[.2 b]) #'f it (+ .2 beat)))) (fp 0 0) (fp 2 68) (fp 1 74) (fp 1 90) (aat (tempo-sync #[.2 b]) #'f it) (defun f ()) ;;-------------------------------------------------- (defparameter *mf* "/home/sendai/Downloads/Loro.mid") (defparameter *notes* (get-notes *mf*)) (defparameter *notes-lead* (get-notes-durations-chords-silences *mf* 1)) (defun f ()) (let ((note (make-palindrome (subseq *notes* 0 30))) (lead (make-cycle (subseq *notes-lead* 20 30)))) (defun f (time &optional (beat 0)) (let ((n (next note))) (p time n 50 .3 0) ;;(play-taupe (+ 12 n) .3 :amp (rcosr 140 20 5) :ramp 1) (destructuring-bind (n d) (next lead) (when (> n 0) (p time n 50 (* .4 d) 1)) ;;(play-taupe n (* .4 d) :rfreq 900 :ramp 10) ) ) (aat (+ time #[.2 b]) #'f it (+ .2 beat)))) (f (now)) (fp 1 0) (let ((notes (make-cycle (subseq *notes-lead* 0 20)))) (defun g (time) (let* ((n (next notes)) (i (first n)) (r (* .8 (second n)))) ;;(play-blue (+ 12 i) r) (p time (+ 12 i) 50 r 1) (aat (+ time #[r b]) #'g it)))) (g (now)) (fp 1 21) (defun g ())
2,090
Common Lisp
.lisp
66
27.242424
81
0.528274
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
d358966ad19b75a75cd59eeb0bbdadd00ccebd88ee62b8ab9c8625106a69d393
9,263
[ -1 ]
9,264
endings.lisp
azimut_shiny/compositions/drafts/midifile/endings.lisp
(in-package #:shiny) (defparameter *mf* "/home/sendai/Downloads/Octopath_Traveler_-_Haanits_Theme.mscz.mid") (defparameter *notes* (subseq (get-measures-pair *mf* 999 1.5 0) 0)) (defparameter *sing* (subseq (get-measures-pair *mf* 999 1.5 1) 0)) (defparameter *pc-follow* (delete-duplicates (sort (mapcar (lambda (x) (mod x 12)) (subseq (get-notes *mf* 1) 0 16)) #'<))) (defun f ()) (let ((measures (make-cycle *notes*)) (sing (make-cycle *sing*))) (defun f (time) (let* ((measure (next measures)) (notes (first measure)) (durations (second measure))) (play-midi-arp time notes 50 durations 0 (d2o durations))) (let* ((n (pc-random 70 90 *pc-follow*)) (i (max 0.1 (+ -3 (cm:interp n 20f0 .1f0 100f0 5f0))))) (at (+ time #[.5 b]) (lambda () (setf *scale* i))) ;; (play-midi (+ #[.5 b] time) ;; n 30 .2 0) ) (let* ((measure (next sing)) (notes (first measure)) (durations (second measure))) (setf *uvs* (+ -.5 (random 1f0))) (progn (setf *rotcube* (drunk 5 5 :low 0 :high 30)) ;; (play-midi time ;; (pc-relative (+ 12 (first notes)) ;; (1+ (random 11)) ;; *pc-follow*) ;; 30 .3 0) ) ;;(setf *rotcube* 0) (play-midi-arp time notes 1 durations 0 (d2o durations)) ) (aat (+ time #[1.5 b]) #'f it)) ) (setf *actors* nil) (make-cubemap) (make-thing) (make-piso (v! 0 -2 0) (q:identity) -.2) ;;(make-piso (v! 0 -2 0) (q:from-axis-angle (v! 0 1 0) (radians -180)) -.2) ;;(make-piso (v! 0 2 0) (q:from-axis-angle (v! 1 0 0) (radians -180)) -.2) (make-piso (v! 0 2 0) (q:* (q:from-axis-angle (v! 0 1 0) (radians -180)) (q:from-axis-angle (v! 1 0 0) (radians -180))) -.2) (make-piso (v! 0 -2 0)) (f (now))
1,990
Common Lisp
.lisp
55
29.672727
75
0.50338
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
2de813b8c2174f8fd7e4bcb488e273b77a76c1bd7387b615582fb52808fe2878
9,264
[ -1 ]
9,265
aisatsana.lisp
azimut_shiny/compositions/drafts/midifile/aisatsana.lisp
(in-package :shiny) (defvar *notes* NIL) (defvar *sing* NIL) (defvar *quarter* NIL) (defvar *mf* NIL) (setf (bpm *tempo*) 64) (setf *quarter* .23) (setf *mf* "/home/sendai/Downloads/aisatsana_by_Aphex_Twin.mscz.mid") (setf *notes* (subseq (get-measures-pair *mf* 0 12 (* *quarter* 4) :seconds nil) 4)) (setf *sing* (subseq (get-measures-pair *mf* 1 24 (* *quarter* 4) :seconds nil) 12)) (let* ((c (make-cycle *notes*)) (cc (make-cycle *sing*))) (defun f (time) (let* ((nn (next c)) (n (first nn)) (d (second nn))) (pa time n 40 d 1 (d2o d))) (let* ((nn (next cc)) (n (first nn)) (d (second nn))) (pa time n 40 d 1 (d2o d))) (aat (+ time #[(* 4 *quarter*) b]) #'f it))) (aat (tempo-sync #[1 b]) #'f it) (fp 1 40) (defun f ())
831
Common Lisp
.lisp
27
26.333333
77
0.5375
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
30cd0813a4a62a2caa3ddfd1e1cbf34f956dd836b885fe8366825d18ecf2ce79
9,265
[ -1 ]
9,266
midifile6.lisp
azimut_shiny/compositions/drafts/midifile/midifile6.lisp
(in-package :shiny) (fg 2f0) (progn (defparameter *mf* "/home/sendai/Downloads/Wet_Hands_Minecraft.mid") (defparameter *bass* (subseq (get-measures-pair *mf* 0 4) 0)) (defparameter *notes* (subseq (get-measures-pair *mf* 1 4) 0)) (defparameter *quarter* (first (get-midi-tempo *mf*)))) (let ((notes (make-cycle *notes*)) (bass (make-cycle *bass*))) (defun f (time) (destructuring-bind (n d) (next notes) (pa time n 40 d 0 (d2o d))) (destructuring-bind (n d) (next bass) (pa time n 40 d 1 (d2o d))) (aat (+ time #[(* 4 *quarter*) b]) #'f it))) (aat (tempo-sync #[1 b]) #'f it) (defun f ())
644
Common Lisp
.lisp
17
34.294118
75
0.603531
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e477204a4e46f9684eced82cf6ba51b7ccd538d24ac9e34a59f36c003d36d0db
9,266
[ -1 ]
9,267
obxd.lisp
azimut_shiny/compositions/drafts/lv2/obxd.lisp
(in-package #:shiny) ;;http://www.onicos.com/staff/iz/formats/midi-event.html (set-rt-block-size 64) (rt-start) (incudine.vug:lv2->vug "https://obxd.wordpress.com" obxd) (dsp! lv2-synth-test ((plugin (or null vug-foreign:plugin-instance))) (:defaults nil) (with ((out (cffi:null-pointer))) (declare (type pointer out)) ;; We will use VUG-FOREIGN:PLUGIN-PORT-POINTER out of the DSP. (setf out (obxd :plugin-instance plugin)) (foreach-frame ;; Plugin with multiple audio output ports, for example two: (out (sample (f32-ref (incudine::ptr-ref out 0) current-frame)) (sample (f32-ref (incudine::ptr-ref out 1) current-frame)))))) (lv2-synth-test :id 123) (defparameter *sst* (control-value 123 'plugin)) (lv2:write-event *sst* (lv2:midi-message #xc0 3 0)) (defun note-test (keynum velocity duration) (rt-eval () (lv2:write-event *sst* (lv2:midi-message #x90 keynum velocity)) (at (+ (now) #[duration seconds]) (lambda (k) (lv2:write-event *sst* (lv2:midi-message #x80 k 0))) keynum))) (progn (note-test 69 30 2) (note-test 74 30 2)) (lv2:write-event *sst* (lv2:midi-message #xc0 0 0)) (let* ((scale (ov-scale :c2 :minor)) (hscale (make-heap scale)) (rhy (make-cycle '(1 1 .5 .5 .25 .25 .5 1)))) (defun f (time) (let ((r (next rhy))) ;;(swipe-dsp-down *sst* 20 .15) (swipe-dsp-down *sst* 54 (- r .2) 1) ;;(swipe-dsp-down *sst* 55 .25) (lv2-note *sst* (next hscale) 30 (- r .2)) (aat (+ time #[r b]) #'f it)))) (set-lv2-control *sst* 20 0) (setf (bpm *tempo*) 60) (defun f ()) (f (now)) (set-lv2-control *sst* 20 .3) (defvar *midiin* (jackmidi:open)) (make-responder *midiin* (lambda (st d1 d2) (lv2:write-event *sst* (lv2:midi-message st d1 d2))))
1,807
Common Lisp
.lisp
46
34.76087
102
0.624714
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
9d389476c46df264bde20b907e574bd126d0d4225009c8ddd72d22402b7a1f09
9,267
[ -1 ]
9,268
lv2.lisp
azimut_shiny/compositions/drafts/lv2/lv2.lisp
(in-package #:shiny) ;;(ql:quickload :incudine-lv2) (set-rt-block-size 64) (set-rt-block-size 1) (rt-start) ;; Error: Div by zero ;;(incudine.vug:lv2->vug "http://www.openavproductions.com/sorcer" wolper) (incudine.vug:lv2->vug "https://obxd.wordpress.com" obxd) (incudine.vug:lv2->vug "http://invadarecords.com/plugins/lv2/testtone" wolper) (incudine.vug:lv2->vug "http://tumbetoene.tuxfamily.org" wolper) (incudine.vug:lv2->vug "https://github.com/asb2m10/dexed" dexed) (dsp! dexed-test ((plugin (or null vug-foreign:plugin-instance))) (:defaults nil) (with ((out (cffi:null-pointer))) (declare (type pointer out)) (setf out (dexed :plugin-instance plugin)) (foreach-frame ;; Single audio output port for Dexed. (stereo (sample (f32-ref out current-frame)))))) (dsp! lv2-synth-test ((plugin (or null vug-foreign:plugin-instance))) (:defaults nil) (with ((out (cffi:null-pointer))) (declare (type pointer out)) ;; We will use VUG-FOREIGN:PLUGIN-PORT-POINTER out of the DSP. (setf out (obxd :plugin-instance plugin)) (foreach-frame ;; Plugin with a single audio output port. ;;(stereo (sample (f32-ref out current-frame))) ;; Plugin with multiple audio output ports, for example two: (out (sample (f32-ref (incudine::ptr-ref out 0) current-frame)) (sample (f32-ref (incudine::ptr-ref out 1) current-frame))) ))) (lv2-synth-test :id 123) (defparameter *sst* (control-value 123 'plugin)) (free (node 0)) ;;(at time #'fluidsynth:noteon *synth* channel n velocity) (lv2:write-event *sst* (lv2:midi-message 1 10 80)) (lv2:write-event *sst* (lv2:midi-message (logand 0 #xF) 0 0)) (defvar *midiin* (jackmidi:open)) (make-responder *midiin* (lambda (st d1 d2) (lv2:write-event *sst* (lv2:midi-message st d1 d2)))) (dexed-test :id 123) (defvar *dexed* (control-value 123 'plugin)) (lv2:write-event *dexed* (lv2:midi-message #xc0 6 0)) (defun note-test (keynum velocity duration) (rt-eval () (lv2:write-event *dexed* (lv2:midi-message #x90 keynum velocity)) (at (+ (now) #[duration seconds]) (lambda (k) (lv2:write-event *dexed* (lv2:midi-message #x80 k 0))) keynum))) (progn (note-test 69 100 2) (note-test 74 90 1.5)) ;;-------------------------------------------------- (defvar *midiin* (jackmidi:open)) (make-responder *midiin* (lambda (st d1 d2) ;; Channel one for Dexed. (when (= (logand st #xf) 0) (lv2:write-event *dexed* (lv2:midi-message st d1 d2))))) (recv-start *midiin*) (incudine::lv2->vug "https://obxd.wordpress.com" obxd) (dsp! obxd-test ((plugin t)) (:defaults nil) (with ((out (cffi:null-pointer))) (declare (type pointer out)) (setf out (obxd :plugin-instance plugin)) (foreach-frame ;; Two audio output ports for Obxd. (out (sample (f32-ref (incudine::ptr-ref out 0) current-frame)) (sample (f32-ref (incudine::ptr-ref out 1) current-frame)))))) (obxd-test :id 321) (defvar *obxd* (control-value 321 'plugin)) (make-responder *midiin* (lambda (st d1 d2) ;; Channel two for Obxd. (when (= (logand st #xf) 1) (lv2:write-event *obxd* (lv2:midi-message st d1 d2)))))
3,344
Common Lisp
.lisp
79
36.64557
78
0.63324
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
4a845e4be65e9a69186fcc0316b4884d952bfc1be571da68f30a03817f4f670f
9,268
[ -1 ]
9,269
dexed.lisp
azimut_shiny/compositions/drafts/lv2/dexed.lisp
(in-package #:shiny) (set-rt-block-size 64) (rt-start) (incudine::lv2->vug "https://github.com/asb2m10/dexed" dexed) (dsp! dexed-test ((plugin (or null vug-foreign:plugin-instance))) (:defaults nil) (with ((out (cffi:null-pointer))) (declare (type pointer out)) (setf out (dexed :plugin-instance plugin)) (foreach-frame ;; Single audio output port for Dexed. (stereo (sample (f32-ref out current-frame)))))) (dexed-test :id 123) (defparameter *dexed* (control-value 123 'plugin)) ;; Program change. (lv2:write-event *dexed* (lv2:midi-message #xc0 3 0)) (progn (note-test (now) 69 30 2) (note-test (now) 74 30 1.5)) (lv2:write-event *dexed* (lv2:midi-message #xc0 33 0)) (defun f (time) ;;(swipe-dsp-down *dexed* 57 1) (swipe-dsp-sin *dexed* 42 .5) (swipe-dsp-up *dexed* 44 .5) (swipe-dsp-up *dexed* 67 1) ;;(swipe-dsp-up *dexed* 30 1) (note-test (pickl (ov-scale :c4 :minor)) 30 .5) (aat (+ time #[1 b]) #'f it)) (aat (tempo-sync #[4 b]) #'f it) (defun f ())
1,019
Common Lisp
.lisp
30
31.033333
65
0.650972
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
de90f2f743a6b8e457f2676018693652eaeb4909e1566996f43aa19aaef7442e
9,269
[ -1 ]
9,270
package.lisp
azimut_shiny/collider/package.lisp
(uiop:define-package shiny (:shadowing-import-from #:cm #:between) ;; between is in tmp-func but undef (:use #:cl #:arrow-macros #:cl-ppcre #:sc) (:import-from #:cm #:eop? #:rhythm ;; modify a list, like a chord #:invert #:transpose #:shuffle ;; lazy evaluation, can be next'd #:pval ;; random boolean #:odds ;; random "single element" picker, still you can use lists of lists #:pick #:pickl ;; random distribution helper #:ran #:drunk ;; brownian noise #:between ;; patterns #:next #:new #:weighting #:markov ;; higher order explicit transition, than nesting patterns #:cycle #:palindrome #:heap)) ;; define var, provided originally by incudine (in-package :shiny) (defvar *sample-rate* 1d0) ;; incudine-like macro (defmacro aat (time function &rest arguments) (let* ((it (intern "IT")) (delta (caddr time)) (real (cadr time)) (next `(+ ,real ,delta))) `(let ((,it ,next)) (callback ,it ,function ,@arguments))))
1,392
Common Lisp
.lisp
43
20.372093
83
0.467706
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
66c1ea4b54543a68a4696d17aef1a37d1530ab8d43c31457561b4d02932e39af
9,270
[ -1 ]
9,271
package.lisp
azimut_shiny/cepl/package.lisp
(uiop:define-package #:shiny (:shadowing-import-from #:cm #:between) ;; between is in tmp-func but undef (:shadowing-import-from #:incudine #:buffer-data #:buffer #:sample) (:shadowing-import-from #:cepl #:free) (:use #:cl #:cepl #:vari #:rtg-math #:nineveh #:arrow-macros #:temporal-functions #:cl-ppcre #:incudine #:cepl.skitter #:livesupport) (:import-from #:alexandria #:flatten #:when-let #:when-let* #:iota #:sequence-of-length-p #:last-elt #:first-elt #:length= #:extremum #:ensure-list #:appendf #:lastcar) (:import-from #:with-setf #:with-setf #:with-setf*) (:import-from #:incudine.external #:foreign-copy-samples) (:import-from #:cm #:eop? #:rhythm ;; modify a list, like a chord #:invert ;; CEPL?!?? ;; #:transpose ;;#:shuffle ;; lazy evaluation, can be next'd #:pval ;; random boolean #:odds ;; random "single element" picker, still you can use lists of lists #:pick #:pickl ;; random distribution helper #:ran #:drunk ;; brownian noise #:between ;; patterns #:next #:new #:weighting #:markov ;; higher order explicit transition, than nesting patterns #:cycle #:palindrome #:heap) (:import-from #:incudine.vug #:maybe-expand #:define-vug #:define-ugen #:make-frame #:frame-ref #:delay1 #:cout #:counter #:vuglet #:current-channel #:current-frame #:buffer-play #:foreach-channel #:foreach-frame #:pan2 #:with #:delay-s #:envgen #:vdelay #:stereo #:midi-note-on-p #:midi-note-off-p #:midi-program-p ;;#:mouse-button #:with-control-period #:white-noise #:samphold #:pole #:make-local-adsr #:make-local-perc #:phasor #:make-f32-array #:phasor-loop #:bpf #:lpf #:hpf #:buffer-read #:buffer-write #:butter-lp #:fractal-noise #:out #:~ ;; nieveh!!!! ;;#:rand #:sine #:pulse #:line #:pink-noise #:dsp!) (:import-from #:incudine.util #:dochannels #:with-samples #:f32-ref #:db->lin #:+twopi+ #:rt-eval ;;#:barrier #:return-value-p #:sample->fixnum #:non-negative-sample #:lin->db #:SAMPLE #:*SAMPLE-DURATION* #:*SAMPLE-RATE* #:*twopi-div-sr* #:+sample-zero+)) (in-package #:shiny) (defun quant (beats) "returns the time (+ (now) beats), sc-collider like thing" (+ (now) (* *sample-rate* (* (sample beats) (spb *tempo*)))))
3,944
Common Lisp
.lisp
131
15.351145
83
0.378116
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
a2b8a45149817f840a63042851ac0b0b0a3329bccb8cf416893b868bcd39ac50
9,271
[ -1 ]
9,272
package-standalone.lisp
azimut_shiny/cepl/package-standalone.lisp
(uiop:define-package shiny (:use #:cl ;; misc #:arrow-macros ;; cepl #:cepl #:vari #:rtg-math #:nineveh #:with-setf #:temporal-functions #:cepl.sdl2-image #:cepl.skitter #:livesupport) (:import-from #:alexandria #:flatten #:when-let #:when-let* #:iota #:appendf #:sequence-of-length-p #:last-elt #:first-elt #:lastcar) (:import-from #:with-setf #:with-setf #:with-setf*))
650
Common Lisp
.lisp
27
12.777778
38
0.4061
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
7f72f7a99e8b11f9a131b595153dbd3705be8db9c1a0860a64ccc1969f1920b4
9,272
[ -1 ]
9,273
package-collider.lisp
azimut_shiny/cepl/package-collider.lisp
(uiop:define-package shiny (:shadowing-import-from #:cm #:between) (:shadowing-import-from #:cepl #:free #:mix) (:use #:cl ;; misc #:arrow-macros #:cl-ppcre ;; collider ;; #:sc ;; cepl #:cepl #:vari #:rtg-math #:nineveh #:with-setf #:temporal-functions #:cepl.sdl2-image #:cepl.skitter #:livesupport) (:import-from #:pixel-spirit-deck #:defcard #:stroke #:g-fill #:circle-sdf #:cross-sdf #:flower-sdf #:heart-sdf #:hex-sdf #:poly-sdf #:rays-sdf #:rect-sdf #:rhomb-sdf #:spiral-sdf #:star-sdf #:tri-sdf #:vesica-sdf) (:import-from #:sc #:*s* #:callback #:at #:quant) (:import-from #:the-book-of-shaders #:g-random #:g-rand) (:import-from #:cm #:eop? #:rhythm ;; modify a list, like a chord #:invert ;; #:transpose ;; glsl-symbols #:shuffle ;; lazy evaluation, can be next'd #:pval ;; random boolean #:odds ;; random "single element" picker, still you can use lists of lists #:pick #:pickl ;; random distribution helper #:ran #:drunk ;; brownian noise #:between ;; patterns #:next #:new #:weighting #:markov ;; higher order explicit transition, than nesting patterns #:cycle #:palindrome #:heap)) ;; define var, provided originally by incudine (in-package :shiny) (defvar *sample-rate* 1d0)
2,011
Common Lisp
.lisp
69
16.449275
83
0.417826
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
1223d7cdc513f5a81e998937699c8d378c1d467750fba2c57318e7487581fd41
9,273
[ -1 ]
9,274
shiny-collider-cepl.asd
azimut_shiny/shiny-collider-cepl.asd
(asdf:defsystem "shiny-collider-cepl" :description "Describe somecepl here" :author "Your Name <[email protected]>" :license "GPL-3.0" :serial t :depends-on ( ;; ??? #:swank ;; collider #:sc ;; midi-constrol #:local-time #:cl-alsaseq ;; fluid #:fluidsynth ;; misc #:arrow-macros #:cm ;; needed on extempore.lisp #:cl-ppcre ;; cepl stuff #:cepl.sdl2 #:cepl.sdl2-image #:livesupport #:skitter #:classimp #:cepl.skitter.sdl2 #:temporal-functions #:dirt #:split-sequence #:rtg-math #:rtg-math.vari #:dendrite #:nineveh #:with-setf ;; ?? #:pixel-spirit-deck #:the-book-of-shaders ) :components ((:file "cepl/package-collider") (:file "musicutils") ;; (:file "nudruz") (:file "extempore") (:file "overtone")))
1,274
Common Lisp
.asd
44
15.409091
46
0.394309
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
75223f1aad2aa1c9975dd201fc9a1067206ed90e4a580cb723bf91f6d34a336c
9,274
[ -1 ]
9,275
shiny-cepl-standalone.asd
azimut_shiny/shiny-cepl-standalone.asd
(asdf:defsystem "shiny-cepl-standalone" :description "Describe somecepl here" :author "Your Name <[email protected]>" :license "GPL-3.0" :serial t :depends-on (;; ??? #:swank ;; misc #:arrow-macros ;; cepl stuff #:cepl.sdl2 #:cepl.sdl2-image #:livesupport #:skitter #:classimp #:cepl.skitter.sdl2 #:temporal-functions #:dirt #:split-sequence #:rtg-math.vari #:dendrite #:nineveh #:with-setf) :components ((:file "cepl/package-standalone") (:file "lib/assets") (:file "lib/misc-gpu")))
786
Common Lisp
.asd
26
17.807692
48
0.452632
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
bd4644c91a9070168db1c4fe21196ea32b816e300565785bac995532bcab2967
9,275
[ -1 ]
9,276
shiny-collider.asd
azimut_shiny/shiny-collider.asd
(asdf:defsystem "shiny-collider" :description "Describe somecepl here" :author "Your Name <[email protected]>" :license "GPL-3.0" :serial t :depends-on ( ;; ??? #:swank ;; nudruz #:screamer ;; collider #:cl-collider ;; midi-constrol ;;#:local-time #:cl-alsaseq ;; fluid #:fluidsynth ;; misc #:arrow-macros #:cm ;; needed on extempore.lisp #:cl-ppcre ) :components ((:file "collider/package") (:file "musicutils") (:file "nudruz") (:file "extempore") (:file "overtone") (:file "drums")))
833
Common Lisp
.asd
29
15.931034
45
0.411692
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
f0517489a2bef16cd614393ac3ba1d0dc6229f32527b2a53309570948d660fc4
9,276
[ -1 ]
9,277
shiny.asd
azimut_shiny/shiny.asd
(asdf:defsystem "shiny" :author "azimut <[email protected]>" :description "incudine" :license "GPL-3.0" :version "0.1" :serial t :depends-on (#:incudine #:cl-ppcre #:cl-arrows #:cm #:serapeum #:str #:verbose) :components ((:file "package") (:file "lib/musicutils") (:file "lib/extempore") (:file "lib/overtone") (:file "lib/drums") (:file "lib/cm") (:file "lib/incudine") (:file "lib/buffers") (:file "lib/midifile") (:file "lib/cryptogram"))) (asdf:defsystem "shiny/fluidsynth" :author "azimut <[email protected]>" :description "incudine" :license "GPL-3.0" :version "0.1" :serial t :depends-on (#:shiny #:incudine-fluidsynth) :components ((:file "lib/fluidsynth"))) (asdf:defsystem "shiny/lv2" :author "azimut <[email protected]>" :description "incudine" :license "GPL-3.0" :version "0.1" :serial t :depends-on (#:shiny #:incudine-lv2) :components ((:file "lib/lv2"))) (asdf:defsystem "shiny/alsaseq" :author "azimut <[email protected]>" :description "incudine" :license "GPL-3.0" :version "0.1" :serial t :depends-on (#:shiny #:cl-alsaseq) :components ((:file "lib/alsaseq"))) (asdf:defsystem "shiny/csound" :author "azimut <[email protected]>" :description "incudine" :license "GPL-3.0" :version "0.1" :serial t :depends-on (#:shiny #:csound) :components ((:file "lib/csound"))) (asdf:defsystem "shiny/gme" :author "azimut <[email protected]>" :description "incudine" :license "GPL-3.0" :version "0.1" :serial t :depends-on (#:shiny #:cl-gme/incudine) :components ((:file "lib/gme"))) (asdf:defsystem "shiny/aubio" :author "azimut <[email protected]>" :description "incudine" :license "GPL-3.0" :version "0.1" :serial t :depends-on (#:shiny #:aubio/double) :components ((:file "lib/aubio"))) (asdf:defsystem "shiny/espeak-ng" :author "azimut <[email protected]>" :description "incudine" :license "GPL-3.0" :version "0.1" :serial t :depends-on (#:shiny #:espeak-ng) :components ((:file "lib/espeak-ng"))) (asdf:defsystem "shiny/morse" :author "azimut <[email protected]>" :description "incudine" :license "GPL-3.0" :version "0.1" :serial t :depends-on (#:shiny #:cl-morse) :components ((:file "lib/morse"))) (asdf:defsystem "shiny/foxdot" :author "azimut <[email protected]>" :description "incudine" :license "GPL-3.0" :version "0.1" :serial t :depends-on (#:shiny #:cl-lex #:yacc) :components ((:file "lib/foxdot/foxdot") (:file "lib/foxdot/foxdot-grammar") (:file "lib/foxdot/foxdot-play"))) (asdf:defsystem "shiny/csound-live-code" :author "azimut <[email protected]>" :description "incudine" :license "GPL-3.0" :version "0.1" :serial t :depends-on (#:shiny #:cl-lex #:yacc #:numcl #:bit-smasher) :components ((:file "lib/csound-live-code"))) (asdf:defsystem "shiny/csound-udp" :author "azimut <[email protected]>" :description "incudine" :license "GPL-3.0" :version "0.1" :serial t :depends-on (#:shiny #:usocket) :components ((:file "lib/csound-udp")))
3,517
Common Lisp
.asd
119
24.151261
50
0.619427
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
67bd5a560e58691d81f3d8b8126db9945113771b0e55c769c0a37e62a990f281
9,277
[ -1 ]
9,278
shiny-cepl.asd
azimut_shiny/shiny-cepl.asd
(asdf:defsystem "shiny-cepl" :author "azimut <[email protected]>" :description "incudine + cepl" :license "GPL-3.0" :version "0.1" :serial t :depends-on (#:swank #:cm #:incudine #:arrow-macros #:cl-ppcre #:cepl.sdl2 #:livesupport #:skitter #:classimp #:cepl.skitter.sdl2 #:temporal-functions #:dirt #:rtg-math.vari #:dendrite #:nineveh) :components ((:file "cepl/package") (:file "lib/assets") (:file "lib/misc-gpu") (:file "lib/musicutils") (:file "lib/extempore") (:file "lib/overtone") (:file "lib/drums") (:file "lib/cm") (:file "lib/incudine"))) (asdf:defsystem "shiny-cepl/fluidsynth" :author "azimut <[email protected]>" :description "incudine" :license "GPL-3.0" :version "0.1" :serial t :depends-on (#:shiny-cepl #:incudine-fluidsynth) :components ((:file "lib/fluidsynth"))) (asdf:defsystem "shiny-cepl/csound" :author "azimut <[email protected]>" :description "incudine" :license "GPL-3.0" :version "0.1" :serial t :depends-on (#:shiny-cepl #:csound) :components ((:file "lib/csound"))) (asdf:defsystem "shiny-cepl/gme" :author "azimut <[email protected]>" :description "incudine" :license "GPL-3.0" :version "0.1" :serial t :depends-on (#:shiny-cepl #:cl-gme/incudine) :components ((:file "lib/gme"))) (asdf:defsystem "shiny-cepl/aubio" :author "azimut <[email protected]>" :description "incudine" :license "GPL-3.0" :version "0.1" :serial t :depends-on (#:shiny-cepl #:aubio/double) :components ((:file "lib/aubio")))
1,899
Common Lisp
.asd
62
22.967742
50
0.569869
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
c318bdef69b7593e928fbe175de92e797f0929e68ae8231b96d0835e8716c229
9,278
[ -1 ]
9,279
asdasda
azimut_shiny/examples/brio/asdasda
float tri(in float x){return abs(fract(x)-.5);} vec3 tri3(in vec3 p){return vec3( tri(p.z+tri(p.y*1.)), tri(p.z+tri(p.x*1.)), tri(p.y+tri(p.x*1.)));} mat2 m2 = mat2(0.970, 0.242, -0.242, 0.970); float triNoise3d(in vec3 p) { float z=1.4; float rz = 0.; vec3 bp = p; for (float i=0.; i<=3.; i++ ) { vec3 dg = tri3(bp); p += (dg); bp *= 2.; z *= 1.5; p *= 1.2; //p.xz*= m2; rz+= (tri(p.z+ tri(p.x+ tri(p.y)))) /z; bp += 0.14; } return rz; } float fogmap(in vec3 p, in float d) { p.x += time; p.z += time*.5; return triNoise3d(p*2.2/(d+8.0))* (smoothstep(.7,.0,p.y)); } vec3 fog(in vec3 col, in vec3 ro, in vec3 rd, in float mt) { float d = .5; for(int i=0; i<7; i++) { vec3 pos = ro + rd*d; float rz = fogmap(pos, d); col = mix(col,vec3(.85, .65, .5),clamp(rz*smoothstep(d,d*1.8,mt), 0., 1.) ); d *= 1.8; if (d>mt)break; } return col; }
1,241
Common Lisp
.asd
48
16.458333
73
0.404908
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
94416843035d111d1754f626baa1b774a37ab8a6023757040702e106ef578996
9,279
[ -1 ]
9,283
loop.sclang
azimut_shiny/compositions/drafts/loop.sclang
SynthDef(\simpler, { arg buf=0 ,freq=220 ,sampleStart=0 ,loopStart=0 ,loopLen=1 // between 0 (min) and 1 (max) ,fadeTime=0.1 ,gate=1 ,attack=0.01 ,sustain=1 ,release=1 ,f0=220; var rate = freq / f0; var sr = rate*BufSampleRate.kr(buf); var fadeFrames = fadeTime*sr; var loopEnd = loopLen*(BufFrames.kr(buf) - loopStart) + loopStart; var loopFrames = loopEnd - loopStart + 1; var loopTime = (loopFrames - fadeFrames)/sr; var startUpTime = (loopStart - sampleStart)/sr; var trigLoop = TDuty.ar(Dseq([startUpTime + loopTime, Dseq([loopTime], inf)]), gapFirst:1); var phaseA = Phasor.ar(trigLoop, rate, sampleStart, inf, loopStart); var phaseB = Phasor.ar(trigLoop, rate, loopEnd - fadeFrames, inf, loopEnd - fadeFrames); var srcA = BufRd.ar(buf.numChannels, buf, phaseA); var srcB = BufRd.ar(buf.numChannels, buf, phaseB); var startLoop = SetResetFF.ar(trigLoop); var loopPan = Phasor.ar(trigLoop, 2/fadeFrames * rate, -1, inf, -1).clip(-1,1); var out = Select.ar(startLoop, [srcA, LinXFade2.ar(srcB, srcA, pan:loopPan)]); var env = EnvGen.ar(Env.asr(attack, sustain, release, 1), gate, doneAction:2); Out.ar(0, Splay.ar(out) * env); }).add; // Try it out: ~buf = Buffer.read(s, Platform.resourceDir +/+ 'sounds/a11wlk01.wav'); Pdef(\p, Pbind(*[ instrument: \simpler ,buf: ~buf ,octave: Prand([3,4,5],inf) ,degree: Pn(Plazy({Pseq([-4,0,5,7,9,12].scramble.clump(2),2)})) ,dur: 0.5 ,strum: Prand([0, 0.125, 0.25], inf) ,strumEndsTogether: false ,loopStart: Pwhite(90000, 150000) ,sampleStart: Pwhite(50000, 85000) ,loopLen: 0.4 ,fadeTime: 0.15 ,attack: 0.25 ,release: 4 ])).play;
1,694
Common Lisp
.cl
49
31.142857
89
0.670128
azimut/shiny
18
2
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
dc2b623f381f361724e71901a92ea0730de0d6f14a519c483a66768bca2cb503
9,283
[ -1 ]
9,559
fft.lisp
ahefner_bordeaux-fft/fft.lisp
;;; -*- Mode: Lisp; Package: BORDEAUX-FFT -*- ;;; (c) copyright 2004-2009 by ;;; Robert Strandh <[email protected]> ;;; Sylvain Marchand <[email protected]> ;;; Martin Raspaud <[email protected]> ;;; (c) copyright 2008-2009 by ;;; Andy Hefner <[email protected]> ;;; (c) copyright 2009 by ;;; Paul Khuong <[email protected]> ;;; ;;; This program is free software; you can redistribute it and/or ;;; modify it under the terms of the GNU General Public License ;;; as published by the Free Software Foundation; either version 2 ;;; 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, write to the ;;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, ;;; Boston, MA 02111-1307, USA. (defpackage :bordeaux-fft (:use :common-lisp) (:export :fft :sfft :fft! :ifft :sifft :ifft! :complex-sample :complex-sample-array :rectangular :hann :blackman :triangle :bartlett :gaussian :gaussian*bartlett^x :blackman-harris :window-vector :extract-window :extract-window-into :extract-centered-window :extract-centered-window-into :windowed-fft :windowed-fft! :*fft-instance* :*ifft-instance*)) (in-package :bordeaux-fft) (deftype complex-sample () `(complex double-float)) (deftype complex-sample-array () `(simple-array complex-sample (*))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; FFT implementation (defclass fft-instance () ((size :initarg :size :reader size) (inter :initarg :inter) (coeffs :initarg :coeffs))) (defun make-fourier-instance (size direction) ;; direction 1 direct, -1 inverse ;; check here that size is a power of two (let ((inter (make-array size :element-type 'complex-sample)) (coeffs (make-array size :element-type 'complex-sample)) (coeff #c(1d0 0d0)) (factor (exp (/ (* direction -2 pi #c(0 1)) size)))) (loop for i of-type fixnum from (ash size -1) below size do (setf (aref coeffs i) coeff) do (setf coeff (* coeff factor))) (do ((src (ash size -1) (ash src -1)) (src-size (ash size -1) (ash src-size -1)) (dst (ash size -2) (ash dst -1))) ((< src-size 1)) (loop for s from src below (+ src src-size) by 2 for d upfrom dst do (setf (aref coeffs d) (aref coeffs s)))) (make-instance 'fft-instance :size size :inter inter :coeffs coeffs))) (defun make-fft-instance (size) (make-fourier-instance size 1)) (defun fft-common (instance source dest) (let ((inter (slot-value instance 'inter)) (coeffs (slot-value instance 'coeffs)) (size (slot-value instance 'size))) (declare (type complex-sample-array source dest inter coeffs)) (declare (type (and unsigned-byte fixnum) size)) (assert (= size (length source))) (assert (= size (length dest))) (labels ((aux (inter dest n starts steps startd) (declare (optimize (speed 3) (safety 0)) (type complex-sample-array inter dest) (type (and fixnum unsigned-byte) starts steps startd)) (if (= n 2) (let ((a (aref source starts)) (b (aref source (+ starts steps)))) (declare (type (complex double-float) a b)) (setf (aref dest startd) (+ a b) (aref dest (1+ startd)) (- a b)) nil) (let ((2*steps (ash steps 1)) (n/2 (ash n -1))) (declare (type fixnum 2*steps n/2)) (aux dest inter n/2 starts 2*steps startd) (aux dest inter n/2 (+ starts steps) 2*steps (+ startd n/2)) (loop for i of-type fixnum from (the fixnum (+ startd n/2)) by 2 for c of-type fixnum from n/2 by 2 for dummy of-type fixnum from 0 below (truncate n/2 2) do (let ((i0 (aref inter i)) (i1 (aref inter (1+ i))) (c0 (aref coeffs c)) (c1 (aref coeffs (1+ c)))) (setf (aref inter i) (* i0 c0) (aref inter (1+ i)) (* i1 c1)))) (loop for i of-type fixnum from startd by 2 for j of-type fixnum from (the fixnum (+ startd n/2)) by 2 for dummy of-type fixnum from 0 below (truncate n/2 2) do (let ((a0 (aref inter i)) (a1 (aref inter (1+ i))) (b0 (aref inter j)) (b1 (aref inter (1+ j)))) (setf (aref dest i) (+ a0 b0) (aref dest (1+ j)) (- a1 b1) (aref dest (1+ i)) (+ a1 b1) (aref dest j) (- a0 b0)))) nil)))) (aux inter dest size 0 1 0) dest))) (defvar *fft-instance* (make-fft-instance 1024)) (defun fft (source) "Returns the Fourier transform of source, allocating a new array for the result." (unless (and *fft-instance* (= (size *fft-instance*) (length source))) (setf *fft-instance* (make-fft-instance (length source)))) (let ((dest (make-array (length source) :element-type '(complex double-float)))) (fft-common *fft-instance* source dest))) (defun fft! (source dest) "Destructive version of fft, since it fills dest." (unless (and *fft-instance* (= (size *fft-instance*) (length source))) (setf *fft-instance* (make-fft-instance (length source)))) (fft-common *fft-instance* source dest)) (defun power-of-two (x) (and (> x 0) (zerop (logand x (1- x))) (1- (integer-length x)))) (defun sfft (source &optional len) "This is the generic fft function. Stands for stupid fft. Can take any kind of array as input." (let* ((l (or len (length source))) (power (power-of-two l)) (lp (expt 2 (or power (error "Input size is not a power of two")))) (new-source (make-array lp :element-type 'complex-sample))) (loop for i fixnum from 0 below l do (setf (aref new-source i) (complex (float (realpart (aref source i)) 0.0d0) (float (imagpart (aref source i)) 0.0d0)))) (fft new-source))) (defmacro with-fft-instance (instance size &body body) `(let ((,instance (make-ftt-instance ,size))) ,@body)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Inverse Fast Fourier Transform (defun make-ifft-instance (size) (make-fourier-instance size -1)) (defun ifft-common (instance source dest) (declare (type complex-sample-array dest)) (fft-common instance source dest) (let ((1/length (/ (float (length source) 0.0d0)))) (map-into dest (lambda (x) (* x 1/length )) dest))) (defvar *ifft-instance* (make-ifft-instance 1024)) (defun ifft (source) "Returns the inverse Fourier transform of source, allocating a new array for the result." (unless (and *ifft-instance* (= (size *ifft-instance*) (length source))) (setf *ifft-instance* (make-ifft-instance (length source)))) (let ((dest (make-array (length source) :element-type '(complex double-float)))) (ifft-common *ifft-instance* source dest))) (defun ifft! (source dest) "Destructive version of ifft, since it fills dest." (unless (and *ifft-instance* (= (size *ifft-instance*) (length source))) (setf *ifft-instance* (make-ifft-instance (length source)))) (ifft-common *ifft-instance* source dest)) (defun sifft (source) "This is the generic inverse fft function. Stands for stupid inverse fft. Can take any kind of array as input." (let* ((l (length source)) (lp (expt 2 (power-of-two l))) (new-source (if (typep source 'complex-sample-array) source (map 'complex-sample-array #'(lambda (x) (coerce x 'complex-sample)) source))) (modified-source (adjust-array new-source lp :initial-element #c(0.0d0 0.0d0) :element-type 'complex-sample))) (ifft modified-source))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Signal windows (defun rectangular (i n) (declare (ignore i n)) 1.0f0) (defun hann (i n) (* 0.5 (- 1.0 (cos (/ (* 2 pi i) (1- n)))))) (defun blackman* (alpha i n) (let ((a0 (/ (- 1 alpha) 2)) (a1 0.5) (a2 (/ alpha 2))) (+ a0 (- (* a1 (cos (/ (* 2 pi i) (1- n))))) (* a2 (cos (/ (* 4 pi i) (1- n))))))) (defun blackman (i n) (blackman* 0.16 i n)) (defun triangle (i n) (* (/ 2 n) (- (* n 0.5) (abs (- i (* 0.5 (1- n))))))) (defun bartlett (i n) (* (/ 2 (1- n)) (- (* (1- n) 0.5) (abs (- i (* 0.5 (1- n))))))) (defun gauss* (sigma i n) (let (([n-1]/2 (* 0.5 (1- n)))) (exp (* -0.5 (expt (/ (- i [n-1]/2) (* sigma [n-1]/2)) 2))))) (let ((cache (make-hash-table))) (defun gaussian (sigma) (or (gethash sigma cache) (setf (gethash sigma cache) (lambda (i n) (gauss* sigma i n)))))) (let ((cache (make-hash-table :test 'equal))) (defun gaussian*bartlett^x (sigma triangle-exponent) (or (gethash (list sigma triangle-exponent) cache) (setf (gethash (list sigma triangle-exponent) cache) (lambda (i n) (* (realpart (expt (bartlett i n) triangle-exponent)) (gauss* sigma i n))))))) (defun cosine-series (i n a0 a1 a2 a3) (flet ((f (scale x) (* scale (cos (/ (* x pi i) (1- n)))))) (+ a0 (- (f a1 2)) (f a2 4) (- (f a3 6))))) (defun blackman-harris (i n) (cosine-series i n 0.35875f0 0.48829f0 0.14128f0 0.01168f0)) (let ((cache (make-hash-table :test 'equalp))) (defun window-vector (function n) (or (gethash (list function n) cache) (setf (gethash (list function n) cache) (let ((v (make-sequence '(simple-array double-float (*)) n))) (dotimes (i n v) (setf (aref v i) (float (funcall function i n) 0.0d0)))))))) (defun clip-in-window (x start end) (max start (min x end))) (defun extract-window-into (vector start length destination) "Copy an extent of VECTOR to DESTINATION. Outside of its legal array indices, VECTOR is considered to be zero." (assert (<= length (length destination))) (let ((start* (clip-in-window start 0 (length vector))) (end* (clip-in-window (+ start length) 0 (length vector)))) (unless (= length (- end* start*)) (fill destination (coerce 0 (array-element-type destination)))) (when (< -1 (- start* start) (length destination)) (replace destination vector :start1 (- start* start) :end1 (+ (- start* start) (- end* start*)) :start2 start* :end2 end*))) destination) (defun extract-window (vector start length &optional (element-type (array-element-type vector))) (extract-window-into vector start length (make-array length :initial-element (coerce 0 element-type) :element-type element-type :adjustable nil :fill-pointer nil))) (defun extract-centered-window-into (vector center size destination) "Extract a subsequence of SIZE from VECTOR, centered on OFFSET and padding with zeros beyond the boundaries of the vector, storing it to DESTINATION." (extract-window-into vector (- center (floor size 2)) size destination)) (defun extract-centered-window (vector center size &optional (element-type (array-element-type vector))) "Extract a subsequence of SIZE from VECTOR, centered on CENTER and padding with zeros beyond the edges of the vector." (extract-centered-window-into vector center size (make-array size :initial-element (coerce 0 element-type) :element-type element-type :adjustable nil :fill-pointer nil))) (defun convert-to-complex-sample-array (array) (let ((output (make-array (length array) :element-type 'complex-sample :adjustable nil :fill-pointer nil))) (typecase array ((simple-array single-float 1) (loop for index from 0 below (length array) for x across array do (setf (aref output index) (complex (float x 0.0d0) 0.0d0)))) ((simple-array double-float 1) (loop for index from 0 below (length array) do (setf (aref output index) (complex (aref array index) 0.0d0)))) (t (loop for index from 0 below (length array) for x across array do (setf (aref output index) (complex (float (realpart x) 0.0d0) 0.0d0))))) output)) (defun windowed-fft! (signal-vector window-dest dest center length &optional (window-fn 'hann)) "Perform an FFT on the window of a signal, centered on the given index, multiplied by a window generated by the chosen window function" (declare (type fixnum length) (optimize (speed 3))) (unless (power-of-two length) (error "FFT size ~D is not a power of two" length)) (unless (typep signal-vector 'complex-sample-array) (setf signal-vector (convert-to-complex-sample-array signal-vector))) (let* ((input-window (extract-centered-window-into signal-vector center length window-dest)) (window (the (simple-array double-float 1) (window-vector window-fn length)))) (declare (type complex-sample-array input-window)) (loop for index from 0 below length do (setf (aref input-window index) (* (aref input-window index) (aref window index)))) (unless (and *fft-instance* (= (size *fft-instance*) length)) (setf *fft-instance* (make-fft-instance length))) (fft-common *fft-instance* input-window dest))) (defun windowed-fft (signal-vector center length &optional (window-fn 'hann)) "Perform an FFT on the window of a signal, centered on the given index, multiplied by a window generated by the chosen window function" (declare (type fixnum length) (optimize (speed 3))) (unless (power-of-two length) (error "FFT size ~D is not a power of two" length)) (unless (typep signal-vector 'complex-sample-array) (setf signal-vector (convert-to-complex-sample-array signal-vector))) (let* ((element-type (array-element-type signal-vector)) (input-window (make-array length :element-type 'complex-sample :adjustable nil :fill-pointer nil)) (dest (make-array length :element-type 'complex-sample :adjustable nil :fill-pointer nil))) (declare (type complex-sample-array input-window)) (windowed-fft! signal-vector input-window dest center length window-fn) dest))
15,927
Common Lisp
.lisp
357
35.420168
95
0.570922
ahefner/bordeaux-fft
14
4
2
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
2a760083aec249daa89ec01c02d6dca34951ffd6e510fe833ac29f8f96daa818
9,559
[ -1 ]
9,560
bordeaux-fft.asd
ahefner_bordeaux-fft/bordeaux-fft.asd
(asdf:defsystem :bordeaux-fft :name "Bordeaux FFT" :description "An efficient and portable implementation of the Fast Fourier Transform" :version "1.0.1" :author "Various" :license "GNU Public License version 2" :serial t :components ((:file "fft")))
265
Common Lisp
.asd
8
30.375
87
0.735409
ahefner/bordeaux-fft
14
4
2
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
961de6e1a0e052fea316f84be3bd5e9d85842cc3bc79f7c3021c73d0a4fdb661
9,560
[ -1 ]
9,563
manual.html
ahefner_bordeaux-fft/doc/manual.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Bordeaux-FFT User Manual</title> <style type="text/css" title="currentStyle" media="screen"> @import "style.css"; </style> </head> <body> <h1>Bordeaux-FFT User Manual</h1> <!-- Contents --> <h2>Table of Contents</h2> <ol> <li><a href="#Introduction">Introduction</a></li> <li><a href="#Installation">Installation</a></li> <li><a href="#Funcs">FFT/IFFT Functions</a></li> <li><a href="#Windows">Signal Window Functions</a></li> <li><a href="#Muliprocessing">Multiprocessing Notes</a></li> <li><a href="#Changelog">Revision History</a></li> <li><a href="#Contact">Contact</a></li> </ol> <!-- Body Text --> <!-- ----------------------------------------------------------------- --> <h2><a name="Introduction"></a>Introduction</h2> <p>The Bordeaux-FFT library provides a reasonably efficient implementation of the Fast Fourier Transform and its inverse for complex-valued inputs, in portable Common Lisp. This is the manual for version 2 of the library.</p> <p>It was originally written by Robert Strandh, Sylvain Marchand, Martin Raspaud. Andy Hefner added the signal windowing code, other minor improvements, and wrote the manual. Paul Khuong contributed performance enhancements.</p> <p>Functions and types documented in this manual are exported from the <tt>BORDEAUX-FFT</tt> package.</p> <!-- ----------------------------------------------------------------- --> <h2><a name="Installation"></a>Installation</h2> <p>Bordeaux-FFT can be loaded either by compiling and loading the <tt>fft.lisp</tt> file directly, or using ASDF. An ASDF system definition file is included. Under typical ASDF configurations, a symbolic link to the file <tt>bordeaux-fft.asd</tt> should be created in a path included in your <tt>ASDF:*CENTRAL-REGISTRY*</tt>. For SBCL users, <tt>~/.sbcl/systems/</tt> is a common choice. You will then be able to load the <tt>BORDEAUX-FFT</tt> system using ASDF as follows: <tt> (asdf:oos 'asdf:load-op :bordeaux-fft)</tt> </p> <p>The most current version of Bordeaux-FFT may be obtained from GitHub at <a href="https://github.com/ahefner/bordeaux-fft">https://github.com/ahefner/bordeaux-fft</a>.</p> <!-- ----------------------------------------------------------------- --> <h2><a name="Funcs"></a>FFT / IFFT Functions</h2> <p>The FFT and IFFT functions each come in three variations: a simple version which handles converting its input to the required format, and two more efficient versions which assume the input is a <a href="#complex-sample-array"><tt>complex-sample-array</tt></a>. Versions are available which allocate a new output vector, or write into an existing output vector. In all cases, the input vector must have a size which is a power of two.</p> <div class="def"><a name="complex-sample">Type</a> <b>complex-sample</b> <div class="docbody"> <pre>(deftype complex-sample () `(complex double-float))</pre> </div> </div> <div class="def"><a name="complex-sample-array">Type</a> <b>complex-sample-array</b> <div class="docbody"> <pre>(deftype complex-sample-array () `(simple-array complex-sample (*)))</pre> </div> </div> <div class="def"><a name="fft">Function</a> <b>fft</b> <i>source</i> &rArr; <i>result</i> <div class="docbody"> <p>Returns the Fourier transform of <i>source</i> (a <a href="#complex-sample-array"><tt>complex-sample-array</tt></a> of a power of two in size), allocating a new array for the <i>result</i> (a <a href="#complex-sample-array"><tt>complex-sample-array</tt></a> of the same size as the <i>source</i>). </div> </div> <div class="def"><a name="fft!">Function</a> <b>fft!</b> <i>source dest</i> &rArr; <i>dest</i> <div class="docbody"> <p>Desctructive version of <a href="#fft"><tt>fft</tt></a>. Computes the Fourier transform of <i>source</i>, writing the result into <i>dest</i>. The <i>source</i> and <i>dest</i> vectors must both be of type <a href="#complex-sample-array"><tt>complex-sample-array</tt></a> and have a size which is a power of two. Additionally, <i>dest</i> cannot be smaller than <i>source</i>. </div> </div> <div class="def"><a name="sfft">Function</a> <b>sfft</b> <i>source <tt>&amp;optional</tt> len</i> &rArr; <i>result</i> <div class="docbody"> <p>Simple version of <a href="#fft"><tt>fft</tt></a>. It can take any kind of array as input. If <i>len</i> is supplied, only the first <i>len</i> elements of <i>source</i> are used.</p> </div> </div> <div class="def"><a name="ifft">Function</a> <b>ifft</b> <i>source</i> &rArr; <i>result</i> <div class="docbody"> <p>Returns the inverse Fourier transform of <i>source</i> (a <a href="#complex-sample-array"><tt>complex-sample-array</tt></a> of a power of two in size), allocating a new array for the <i>result</i> (a <a href="#complex-sample-array"><tt>complex-sample-array</tt></a> of the same size as the <i>source</i>). </div> </div> <div class="def"><a name="ifft!">Function</a> <b>ifft!</b> <i>source dest</i> &rArr; <i>dest</i> <div class="docbody"> <p>Desctructive version of <a href="#ifft"><tt>ifft</tt></a>. Computes the inverse Fourier transform of <i>source</i>, writing the result into <i>dest</i>. The <i>source</i> and <i>dest</i> vectors must both be of type <a href="#complex-sample-array"><tt>complex-sample-array</tt></a> and have a size which is a power of two. Additionally, <i>dest</i> cannot be smaller than <i>source</i>. </div> </div> <div class="def"><a name="sifft">Function</a> <b>sifft</b> <i>source <tt>&amp;optional</tt> len</i> &rArr; <i>result</i> <div class="docbody"> <p>Simple version of <a href="#ifft"><tt>ifft</tt></a>. It can take any kind of array as input. If <i>len</i> is supplied, only the first <i>len</i> elements of <i>source</i> are used.</p> </div> </div> <!-- ----------------------------------------------------------------- --> <h2><a name="Windows"></a>Signal Window Functions</h2> <div class="def"><a name="windowed-fft">Function</a> <b>windowed-fft</b> <i>signal-vector center length <tt>&amp;optional</tt> (window-fn 'hann)</i> &rArr; <i>result</i> <div class="docbody"> <p>Returns the FFT of a window of <i>length</i> samples from <i>signal-vector</i> (a <a href="#complex-sample-array"><tt>complex-sample-array</tt></a>), centered on the offset <i>center</i>. Areas where the window would extend outside the bounds of the array are taken to be zeros. Before being computing the FFT, the specified region of the signal is multiplied by the result of a window function, <i>window-fn</i>, which takes as arguments an array index (from 0 below <i>length</i>) and <i>length</i>, the window size, and must return a double float. Windows for a given <i>window-fn</i> and <i>length</i> are memoized, so the cost of computing the window is paid only once for any particular combination. Several built-in choices for <i>window-fn</i> are presented below. A new <i>result</i> vector is allocated; the original <i>signal-vector</i> is not modified.</p> <p>The following expressions produce equivalent results: <tt>(windowed-fft vector 256 512 'rectangular)</tt> and <tt>(fft vector)</tt>. </div> </div> <div class="def"><a name="windowed-fft!">Function</a> <b>windowed-fft!</b> <i>signal-vector window-dest dest center length <tt>&amp;optional</tt> (window-fn 'hann)</i> &rArr; <i>result</i> <div class="docbody"> <p>Destructive version of <a href="#windowed-fft"><tt>windowed-fft</tt></a>. Computes the specified window values from <i>signal-vector</i> into <i>window-dest</i>, and then computes the FFT into <i>dest</i>.</p> </div> </div> <div class="def"><a name="window-vector">Function</a> <b>window-vector</b> <i>function length</i> &rArr; <i>vector</i> <div class="docbody"> <p>Compute and return a <i>vector</i> of <i>length</i> samples by evaluating <i>function</i> at 0, 1, 2, ..., <i>length</i>. The resulting <i>vector</i> for a given <i>function</i> and <i>length</i> is memoized so that it is computed only once, and subsequent requests will return the same <i>vector</i> again.</p> </div> </div> <p>Several window functions are provided. These can be used as arguments to <a href="#windowed-fft"><tt>windowed-fft</tt></a> or <a href="#window-vector"><tt>window-vector</tt></a>.</p> <div class="def"><a name="rectangular">Function</a> <b>rectangular</b> <i>i n</i> &rArr; <i>result</i> <div class="docbody"> <p>Returns the <i>i</i>-th point of the <i>n</i>-point rectangular window.</p> </div> </div> <div class="def"><a name="triangle">Function</a> <b>triangle</b> <i>i n</i> &rArr; <i>result</i> <div class="docbody"> <p>Returns the <i>i</i>-th point of the <i>n</i>-point triangular window.</p> </div> </div> <div class="def"><a name="hann">Function</a> <b>hann</b> <i>i n</i> &rArr; <i>result</i> <div class="docbody"> <p>Returns the <i>i</i>-th point of the <i>n</i>-point Hann window.</p> </div> </div> <div class="def"><a name="blackman">Function</a> <b>blackman</b> <i>i n</i> &rArr; <i>result</i> <div class="docbody"> <p>Returns the <i>i</i>-th point of the <i>n</i>-point Blackman window (with &alpha;=0.16).</p> </div> </div> <div class="def"><a name="bartlett">Function</a> <b>bartlett</b> <i>i n</i> &rArr; <i>result</i> <div class="docbody"> <p>Returns the <i>i</i>-th point of the <i>n</i>-point Bartlett window.</p> </div> </div> <div class="def"><a name="blackman-harris">Function</a> <b>blackman-harris</b> <i>i n</i> &rArr; <i>result</i> <div class="docbody"> <p>Returns the <i>i</i>-th point of the <i>n</i>-point Blackman-Harris window.</p> </div> </div> <div class="def"><a name="gaussian">Function</a> <b>gaussian</b> <i>sigma</i> &rArr; <i>window-function</i> <div class="docbody"> <p>Returns a <i>window-function</i> for evaluating a Gaussian window, given the parameter <i>sigma.</i> The result is memoized.</p> </div> </div> <div class="def"><a name="gaussian*bartlett^x">Function</a> <b>gaussian*bartlett^x</b> <i>sigma triangle-exponent</i> &rArr; <i>window-function</i> <div class="docbody"> <p>Returns a <i>window-function</i> to evaluate< <i>i</i>-th point from the product of the <i>n</i>-point Gaussian (with parameter <i>sigma</i>) and Bartlett (raised to <i>triangle-exponent</i>) windows.</p> </div> </div> <!-- ----------------------------------------------------------------- --> <h2><a name="Multiprocessing"></a>Multiprocessing Notes</h2> <p>Coefficients and temporary buffers are saved and reused between calls to <a href="#fft"><tt>fft</tt></a> and <a href="#ifft"><tt>ifft</tt></a>. These are contained in <tt>fft-instance</tt> and <tt>ifft-instance</tt> objects, which are stored in the variables <tt>*fft-instance*</tt> and <tt>*ifft-instance*</tt>, respectively. In a multiprocessing environment, simultaneous use of the same <tt>fft-instance</tt> or <tt>ifft-instance</tt> object will produce corrupted results. For this reason, a program performing simultaneous FFT/IFFT operations in multiple threads should ensure that each thread establishes its own dynamic binding of the <tt>*fft-instance*</tt> and <tt>*ifft-instance*</tt> variables, containing unique instances. It is sufficient to bind these to <tt>nil</tt> initially.</p> <!-- ----------------------------------------------------------------- --> <h2><a name="Changelog"></a>Revision History</h2> <ul> <li>Version 1.0.1: Fixes infinite recursion when a non-power of two window size is passed to <a href="#windowed-fft"><tt>windowed-fft</tt></a></li> <li>Version 1.0.0: Initial public release.</li> </ul> <!-- ----------------------------------------------------------------- --> <h2><a name="Contact"></a>Contact</h2> Report bugs to Andy Hefner &lt;ahefner at gmail dot com&gt; <!-- ----------------------------------------------------------------- --> </body> </html>
12,332
Common Lisp
.l
185
62.216216
872
0.634568
ahefner/bordeaux-fft
14
4
2
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
94e0e46521693cdff23e0103f75b7fd41b6d4ebd838173a3d8e6767c4bf7c6ec
9,563
[ -1 ]
9,564
style.css
ahefner_bordeaux-fft/doc/style.css
@charset "utf-8"; pre.lisp { background: #eee; margin: 10px 40px 10px 40px; border: 1px solid #ccc; padding: 8px; } div.def { margin-left: 2em; margin-bottom: 1em; } div.docbody { margin-left: 2em; margin-right: 2em; }
256
Common Lisp
.l
15
13.6
32
0.639831
ahefner/bordeaux-fft
14
4
2
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
ca63d196bcfebc8aa00e358bc518cece6c63b78be4962a49409476266ceca5f2
9,564
[ -1 ]
9,579
package.lisp
szos_defconfig/package.lisp
;;;; package.lisp (defpackage #:defconfig (:use #:cl) (:import-from #-clisp #:trivial-cltl2 #+clisp #:ext #:compiler-let) (:export #:defconfig ; main macro #:define-accessor-config #:define-variable-config #:define-minimal-config #:defconfig-minimal #:*setv-permissiveness* ;; setters and searchers #:setv #:psetv #:with-atomic-setv #:with-atomic-setv* #:reset-place #:reset-computed-place #:clean-previous-value #:search-configurable-objects #:tag-configurable-place ;; readers #:config-info-predicate #:config-info-coercer #:config-info-db #:config-info-place #:config-info-default-value #:config-info-previous-value #:config-info-name #:config-info-tags #:config-info-documentation #:config-info-valid-values-description #:config-info-typespec ;; errors #:config-error #:invalid-datum-error #:invalid-coerced-datum-error #:no-config-found-error #:database-already-exists-error #:untrackable-place-error #:no-bound-default-value-error #:not-resettable-place-error #:setv-wrapped-error ;; database creation and lookup #:define-defconfig-db #:get-db #:get-db-var #:list-dbs #:delete-db))
1,365
Common Lisp
.lisp
50
20.76
42
0.632353
szos/defconfig
12
2
0
LGPL-2.1
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
58d4de22b6f5a375e0aa1b4bf6ae239635224c2773a5b2c2a81d70511802b984
9,579
[ -1 ]
9,580
database.lisp
szos_defconfig/database.lisp
(in-package :defconfig) (defun defconfig-database-p (db) (and (consp db) (hash-table-p (car db)) (hash-table-p (cdr db)) (eql (hash-table-test (car db)) 'eql) (eql (hash-table-test (cdr db)) 'eql))) (deftype defconfig-database () `(satisfies defconfig-database-p)) (defvar *db-plist* '() "A plist holding all databases for defconfig") (defun make-config-database () "Return a cons of two hash tables" (cons (make-hash-table) (make-hash-table))) (defun add-db-to-plist (key varname) "add a database to *db-plist* in the correct format of (KEY (VARNAME value)). VARNAME is the quoted variable referencing the database, while value is the symbol-value of VARNAME. for internal use only" (declare (type keyword key) (type symbol varname)) (setf *db-plist* (cons key (cons (cons varname (symbol-value varname)) *db-plist*)))) (defun db-key-exists-p (key) "return t/nil if KEY denotes a pre-existing db" (declare (type keyword key)) (if (getf *db-plist* key) t nil)) (defun getdb (key) "used internally by defconfig to wrap around getf - think of it as currying getf with *db-plist* as the place" (declare (type keyword key)) (getf *db-plist* key)) (defun get-db (key) "get the database associated with KEY" (declare (type keyword key)) (cdr (getdb key))) (defun get-db-var (key) "get the variable holding the database associated with KEY" (declare (type keyword key)) (car (getdb key))) (defun list-dbs () "list all defconfig databases" (loop for (key db) on *db-plist* by 'cddr collect key)) (defun delete-db (key &optional makunbound) "delete the database associated with KEY. if MAKUNBOUND is T, then unbind the symbol holding the database associated with KEY" (declare (type keyword key) (type boolean makunbound)) (let ((dbvar (get-db-var key))) (when (and makunbound dbvar) (makunbound dbvar))) (remf *db-plist* key)) (defun def-defconfig-db-error-check (key var) "Check that KEY is a keyword and doesnt already denotes a database in *db-plist*. If it does signal an error within the context of a use-value restart to allow the user to provide a new value to use instead of KEY" (declare (type keyword key) (type symbol var)) (restart-bind ((use-value (lambda (new-key) (return-from def-defconfig-db-error-check new-key)) :interactive-function (lambda () (list (read *query-io*))) :report-function (lambda (stream) (format stream "Supply a new key to use")) :test-function (lambda (condition) (typecase condition (type-error t) (database-already-exists-error t) (t nil)))) (continue (lambda () (return-from def-defconfig-db-error-check nil)) :report-function (lambda (s) (format s "Continue using existing database")) :test-function (lambda (c) (typep c 'database-already-exists-error))) (redefine (lambda () (return-from def-defconfig-db-error-check key)) :report-function (lambda (stream) (format stream "Reinitialize the database denoted by ~A" key)) :test-function (lambda (c) (typep c 'database-already-exists-error)))) (cond ((not (keywordp key)) (error 'type-error :expected-type 'keyword :datum key :context (format nil "when defining defconfig database ~S" var))) ((db-key-exists-p key) (error 'database-already-exists-error :key key)) (t key)))) (defmacro define-defconfig-db (var key &key (parameter t) if-exists (doc "A defconfig database")) "define a dynamic variable name VAR to be a defconfig database accessible by passing KEY to the function get-db. If PARAMETER is true, create this var with a defparameter form, otherwise use defvar. DOC is the documentation to pass to the def(parameter|var) form." (alexandria:with-gensyms (realkey) `(let ((,realkey (,@(case if-exists (:use '(handler-bind ((database-already-exists-error (lambda (c) (let ((r (find-restart 'continue c))) (when r (invoke-restart r)))))))) (:redefine '(handler-bind ((database-already-exists-error (lambda (c) (let ((r (find-restart 'redefine c))) (when r (invoke-restart r)))))))) (otherwise '(progn))) (def-defconfig-db-error-check ,key ',var)))) (declare (special ,var)) (when ,realkey (,(if parameter 'defparameter 'defvar) ,var (make-config-database) ,doc) (add-db-to-plist ,realkey ',var))))) (define-defconfig-db *default-db* :default :doc "The default database for defconfig" :if-exists :use)
5,699
Common Lisp
.lisp
123
33.056911
83
0.547825
szos/defconfig
12
2
0
LGPL-2.1
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
d5c89fe4e6a7641d17f5f7497ae5122fb0f2efe2c5a3c45eb7d39c058ba7fbfd
9,580
[ -1 ]
9,581
conditions.lisp
szos_defconfig/conditions.lisp
(in-package :defconfig) (define-condition config-error (error) () (:documentation "This condition is the root condition for all defconfig conditions. If one wants to catch all defconfig conditions (such as with handler-case) then config-error should be used.")) (define-condition with-atomic-setv-internal-error (config-error) ()) (define-condition invalid-datum-error (config-error) ((place-form :initarg :place :reader invalid-datum-error-place :initform nil) (value :initarg :value :reader invalid-datum-error-value :initform nil) (config-object :initarg :config-object :initform nil :reader invalid-datum-error-config-object)) (:report (lambda (c s) (with-slots (place-form value) c (format s "The value ~S is invalid for place ~S." value place-form)))) (:documentation "This condition indicates that VALUE is invalid for PLACE-FORM")) (define-condition invalid-coerced-datum-error (invalid-datum-error) ((coerced-value :initarg :coerced-value :initform nil :reader invalid-coerced-datum-error-value)) (:report (lambda (c s) (with-slots (place-form value coerced-value) c (format s "The value ~S is invalid for place ~S.~%Coercion produced the value ~S, which is also invalid" value place-form coerced-value)))) (:documentation "This condition indicates that coercion was attempted on VALUE, producing COERCED-VALUE, and that COERCED-VALUE is invalid for PLACE-FORM")) (define-condition no-config-found-error (config-error) ((place-form :initarg :place :reader no-config-found-error-place :initform nil) (database :initarg :db :reader no-config-found-error-db :initform nil)) (:report (lambda (c s) (with-slots (place-form database) c (format s "Unable to find config-info for place ~S in database ~S" place-form database)))) (:documentation "This condition indicates that PLACE-FORM does not denote a config-info object in DATABASE")) (define-condition database-already-exists-error (config-error) ((key :initarg :key :reader database-already-exists-error-key)) (:report (lambda (condition stream) (format stream "The key ~S already denotes a defconfig database" (database-already-exists-error-key condition)))) (:documentation "This condition indicates KEY already denotes a database in *db-plist*")) (define-condition untrackable-place-error (config-error) ((object :initarg :object :reader untrackable-place-error-object) (place :initarg :place :reader untrackable-place-error-place)) (:report (lambda (condition stream) (format stream "The place ~S does not track default or previous values" (untrackable-place-error-place condition))))) (define-condition no-bound-default-value-error (untrackable-place-error) () (:report (lambda (condition stream) (format stream "No default value bound when trying to reset ~S" (untrackable-place-error-place condition)))) (:documentation "This condition indicates that the default-value slot of OBJECT is unbound. This will only be signalled when trying to reset a place to its default value.")) (define-condition not-resettable-place-error (untrackable-place-error) () (:report (lambda (condition stream) (format stream "Place ~S is an accessor and is not resettable" (untrackable-place-error-place condition)))) (:documentation "This condition indicates that a reset was attempted on an accessor place.")) (define-condition setv-wrapped-error (config-error) ((condition :initarg :error :accessor setv-wrapped-error-condition)) (:report (lambda (c s) (with-slots (condition) c (format s "WITH-ATOMIC-SETV encountered the error ~S and reset." (type-of condition))))) (:documentation "This condition is only ever signalled from within WITH-ATOMIC-SETV, and indicates that an error was caught which caused WITH-ATOMIC-SETV to reset all places found within its body. It has one slot, CONDITION, which contains the condition that was caught."))
4,113
Common Lisp
.lisp
81
45.753086
143
0.728177
szos/defconfig
12
2
0
LGPL-2.1
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
a47e2a17b7c6518efc85bddc0ded817f5362ab78a152630b8003ffeac09e4623
9,581
[ -1 ]
9,582
classes.lisp
szos_defconfig/classes.lisp
(in-package :defconfig) (defun generate-valid-values-predicate-string (&key typespec predicate) (cond (typespec (format nil "Valid values must conform to the typespec ~A" typespec)) (t (format nil "Valid values must are tested using ~S" (cond ((symbolp predicate) predicate) ((functionp predicate) (let ((fname (nth-value 2 (function-lambda-expression predicate)))) (cond ((symbolp fname) fname) ((listp fname) (list (car fname) (cadr fname))) (t 'unknown-function))))))))) (defun generate-valid-values-coercer-string (&optional coercer) (if coercer (format nil ". Coercion is attempted with the function ~S." (cond ((symbolp coercer) coercer) ((functionp coercer) (let ((fname (nth-value 2 (function-lambda-expression coercer)))) (cond ((symbolp fname) fname) ((listp fname) (list (car fname) (cadr fname))) (t 'unknown-function)))))) ".")) (defun generate-vv-string (spec obj) (destructuring-bind (typespec-or-fn-indicator typespec-or-fn) spec (concatenate 'string (if (eql typespec-or-fn-indicator 'typespec) (generate-valid-values-predicate-string :typespec typespec-or-fn) (generate-valid-values-predicate-string :predicate typespec-or-fn)) (generate-valid-values-coercer-string (config-info-coercer obj))))) (defclass config-info-functions () ((predicate :initarg :predicate :initform #'identity :type (function (t) boolean) :reader config-info-predicate :documentation "The predicate against which valid values are checked") (coercer :initarg :coercer :initform nil :type (or function null) :reader config-info-coercer :documentation "The function by which invalid datum will attempt to be coerced"))) (defclass config-info-direct-info () ((db :initarg :db :type (or symbol cons) :reader config-info-db :documentation "the database that the config info object is housed in.") (place :initarg :place :type symbol :reader config-info-place :documentation "The place which this config info governs."))) (defclass config-info-values () ((default-value :initarg :default :reader config-info-default-value :documentation "The default value of this config-info object") (prev-value :initarg :previous :reader config-info-previous-value :accessor config-info-prev-value :documentation "holds the value previously assigned to the config-info object. initially the same as default-value"))) (defclass config-info-metadata () ((name :initarg :name :initform "Unnamed config-info object" :reader config-info-name :documentation "The formal name by which this config-info object can be searched for" ;; one cant yet search by name - searching needs to be reworked/rethought ) (tags :initarg :tags :initform '() :reader config-info-tags :accessor config-info-tag-list :documentation "Tags which can be used for finding a config-info object") (docstring :initarg :documentation :initform nil :type (or string null) :reader config-info-documentation :documentation "The docstring for the place being governed. if a variable it is the same as the variables docstring") (valid-values :initarg :valid-values :reader config-info-valid-values-description :documentation "An explanation of the valid values and predicate function") (typespec :initform nil :reader config-info-typespec :documentation "When a typespec is provided instead of a validator, this slot will hold it"))) (defclass minimal-config-info (config-info-functions config-info-direct-info) ()) (defclass accessor-config-info (config-info-metadata minimal-config-info) ()) (defclass config-info (accessor-config-info config-info-values) ()) (defmethod print-object ((object minimal-config-info) stream) (print-unreadable-object (object stream) (format stream "MINIMAL-CONFIG-INFO ~A" (config-info-place object)))) (defmethod print-object ((object config-info) stream) (print-unreadable-object (object stream) (format stream "CONFIG-INFO ~A" (config-info-place object)))) (defmethod print-object ((object accessor-config-info) stream) (print-unreadable-object (object stream) (format stream "ACCESSOR-CONFIG-INFO ~A" (config-info-place object)))) (defun slot-bound-p (obj slot) (slot-boundp obj slot)) (defmethod initialize-instance :after ((obj accessor-config-info) &key) (cond ((slot-bound-p obj 'valid-values) (unless (typep (slot-value obj 'valid-values) 'string) (psetf (slot-value obj 'valid-values) (generate-vv-string (slot-value obj 'valid-values) obj) (slot-value obj 'typespec) (let ((ts (slot-value obj 'valid-values))) (if (eq (car ts) 'typespec) (cadadr ts) ts))))) (t (setf (slot-value obj 'valid-values) "Unspecified")))) (defmethod initialize-instance :after ((obj config-info) &key) (unless (slot-boundp obj 'prev-value) (setf (slot-value obj 'prev-value) (slot-value obj 'default-value))))
5,885
Common Lisp
.lisp
114
39.885965
133
0.616026
szos/defconfig
12
2
0
LGPL-2.1
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
7ab313a432b8053b17d0ae80042b76a96341c97cbc6c2502095d6402b56b04d3
9,582
[ -1 ]
9,583
access.lisp
szos_defconfig/access.lisp
(in-package :defconfig) (defun list-of-strings-p (thing) (when (listp thing) (every 'stringp thing))) (defun place->config-info (place &key (db *default-db*)) (declare (type (or symbol cons) db) (type (or symbol cons) place)) (let ((rdb (if (symbolp db) (symbol-value db) db))) (declare (type cons rdb)) (if (listp place) (gethash (car place) (car rdb)) (gethash place (cdr rdb))))) (defun %%with-config-info (fn place database policy) (declare (type (member :strict :greedy) policy) (type function fn) (type (or symbol list) place) (type (or keyword symbol cons) database)) (check-type policy (member :strict :greedy)) (let ((*setv-permissiveness* policy) (db (cond ((keywordp database) (get-db database)) ((symbolp database) (symbol-value database)) (t database)))) (declare (type cons db)) (funcall fn (restart-case (%fsetv-get-config-info-object place (if (listp place) (car db) (cdr db)) database) (use-value (new-database) :test (lambda (c) (and (typep c 'no-config-found-error) (not (eql (no-config-found-error-db c) 'all-registered-databases)))) :report "Supply a new database" :interactive (lambda () (format *query-io* "Enter database key or variable: ") (force-output *query-io*) (list (read *query-io*))) (%%with-config-info fn place new-database policy)))))) (defmacro with-config-info ((var place &key (db '*default-db*) (unfound-policy :strict)) &body body) `(%%with-config-info (lambda (,var) ,@body) ,place ,db ,unfound-policy)) (defun tag-configurable-place (tag place &key (db *default-db*) reclass) "Push TAG onto the list of tags for the config-info object associated with PLACE in DB." (declare (type (or string symbol) tag) (type (or symbol list) place) (type (or symbol cons) db)) (atypecase (place->config-info place :db db) (minimal-config-info (if reclass (progn (change-class it 'accessor-config-info) (push tag (config-info-tag-list it))) (error 'type-error :expected-type 'config-info-metadata :datum it :context (format nil "when pushing tagging ~S" it)))) ((or accessor-config-info config-info) (push tag (config-info-tag-list it))))) (defun config-info-search-tags (tags &key (namespace :both) (db *default-db*)) (declare (type list tags) (type keyword namespace) (type cons db)) (flet ((fmap () (let (fobjs) (maphash (lambda (k v) (declare (ignore k)) (loop for tag in (when (typep v 'config-info-metadata) (config-info-tags v)) do (loop for el in tags if (string= el tag) do (push v fobjs)))) (car db)) fobjs)) (vmap () (let (vobjs) (maphash (lambda (k v) (declare (ignore k)) (block tagblock (loop for tag in (when (typep v 'config-info-metadata) (config-info-tags v)) do (loop for el in tags if (string= el tag) do (push v vobjs))))) (cdr db)) vobjs))) (case namespace ((:accessors) (list (fmap) nil)) ((:variables) (list nil (vmap))) (otherwise (list (fmap) (vmap)))))) (defun config-info-search-in-db (term &key (namespace :both) (db *default-db*)) "takes a term, as well as a namespace and a database. the :db keyarg should be a database as returned by make-config-database. the :namespace keyarg should be one of :both :accessor or :variable. Note that the namespace keyarg isnt used if term is a symbol. Term should be either a string, a list of strings, a symbol, or a list of symbols representing an accessor and a place." (declare (type (or string list symbol) term) (type keyword namespace) (type cons db)) (cond ((stringp term) (config-info-search-tags (list term) :namespace namespace :db db)) ((list-of-strings-p term) (config-info-search-tags term :namespace namespace :db db)) ((or (symbolp term) (listp term)) (place->config-info term :db db)))) (defun search-configurable-objects (term &optional database-key) "Returns a list of all configurable objects matching TERM. If DATABASE-KEY is provided, search only in that database." (declare (type (or keyword null) database-key)) (let ((dbs (if database-key (list (get-db-var database-key)) (loop for (key (dbsym ahash . vhash)) on *db-plist* by 'cddr collect dbsym)))) (alexandria:flatten (loop for db in dbs collect (config-info-search-in-db term :db (symbol-value db)))))) (defgeneric reset-computed-place (place &key db previous-value test) (:documentation "Reset PLACE to its default value, unless PREVIOUS-VALUE is true, then reset to the previous value. TEST is used to check if a reset is needed.") (:method ((place symbol) &key (db *default-db*) (test 'eql) previous-value) (with-config-info (obj place :db db) (reset-computed-place obj :db db :test test :previous-value previous-value))) (:method ((object config-info) &key db (test 'eql) previous-value) (declare (ignore db)) (let ((curval (symbol-value (config-info-place object))) (newval (if previous-value (config-info-previous-value object) (config-info-default-value object)))) (unless (funcall test curval newval) (setf (symbol-value (config-info-place object)) newval (config-info-prev-value object) curval)))) (:method ((place list) &key db test previous-value) (declare (ignore test previous-value)) (with-config-info (obj place :db db) (error 'not-resettable-place-error :place place :object obj))) (:method ((object accessor-config-info) &key db test previous-value) (declare (ignore db test previous-value)) (error 'not-resettable-place-error :place (config-info-place object) :object object)) (:method ((object minimal-config-info) &key db test previous-value) (declare (ignore db test previous-value)) (error 'not-resettable-place-error :place (config-info-place object) :object object))) (defmacro reset-place (place &key (db '*default-db*) previous-value) "looks up PLACE in DB and set it to its default or previous value." `(reset-computed-place ',place :db ,db :previous-value ,previous-value)) (defgeneric clean-previous-value (place &key db) (:documentation "use to set the previous value of PLACE to the default value. This is useful for places that may hold a large object which you want gc'd") (:method ((place symbol) &key (db *default-db*)) (with-config-info (object place :db db) (setf (config-info-prev-value object) (config-info-default-value object)))) (:method ((object config-info) &key db) (declare (ignore db)) (setf (config-info-prev-value object) (config-info-default-value object))) (:method ((place list) &key db) (with-config-info (object place :db db) (error 'untrackable-place-error :place place :object object))) (:method ((object accessor-config-info) &key db) (declare (ignore db)) (error 'untrackable-place-error :place (config-info-place object) :object object)))
7,244
Common Lisp
.lisp
164
38.457317
83
0.662555
szos/defconfig
12
2
0
LGPL-2.1
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
8a716aa3387cc93f43a7b39d0ff5fca60c9d0fb31bfb6b99a458599124ebc40e
9,583
[ -1 ]
9,584
defconfig.lisp
szos_defconfig/defconfig.lisp
(in-package :defconfig) ;;; Minimal configs (defmacro define-min (place &key predicate coercer db regen-config) (alexandria:with-gensyms (hash obj pred) `(let* ((,pred ,(if predicate predicate #'cl::identity)) (,hash (,(if (listp place) 'car 'cdr) ,(if db db '*default-db*))) (,obj (gethash ',place ,hash))) (declare (type function ,pred) (type hash-table ,hash) (type (or minimal-config-info accessor-config-info config-info null) ,obj)) (if (or (not ,obj) ,regen-config) (setf (gethash ',place ,hash) (make-instance 'minimal-config-info :place ',place :db ,(if db db '*default-db*) :predicate ,pred ,@(when coercer `(:coercer ,coercer)))) ,obj)))) (defmacro define-minimal-config (place &key (type :accessor) validator typespec coercer db regen-config) "define a minimal config object for PLACE and in DB." (when (and validator typespec) (error "The arguments :VALIDATOR and :TYPESPEC cannot both be supplied")) `(define-min ,(if (and (eq type :accessor) (symbolp place)) (list place) place) :predicate ,(cond (typespec `(lambda (x) (typep x ,typespec))) (t validator)) :coercer ,coercer :db ,db :regen-config ,regen-config)) (defmacro defconfig-minimal (place &rest args) "Define a minimal config, with no value tracking." (cond ((consp place) `(define-minimal-config ,place ,@args)) ((and (keywordp (car args)) (not (keywordp (cadr args)))) ;; then we have no default value and we want to use the current value of ;; place. (destructuring-bind (&key validator typespec coercer db regen-config) args `(define-minimal-config ,place ,place :validator ,validator :typespec ,typespec :coercer ,coercer :db ,db :regen-config ,regen-config :type :variable))) (t (destructuring-bind (default &key validator typespec coercer db regen-config reinitialize documentation) args `(prog1 (restart-case (define-minimal-config ,place :validator ,validator :typespec ,typespec :coercer ,coercer :db ,db :regen-config ,regen-config :type :variable) (define-variable-regardless () nil)) (,(if reinitialize 'defparameter 'defvar) ,place ,default ,@(when documentation (list documentation)))))))) ;;; Accessor configs (defmacro defconf-a (place &key predicate coercer db tags documentation regen valid-values) (alexandria:with-gensyms (hash obj pred) `(let* ((,pred ,(if predicate predicate #'cl::identity)) (,hash (car ,(if db db '*default-db*))) (,obj (gethash ',place ,hash))) (declare (type function ,pred) (type hash-table ,hash) (type (or minimal-config-info accessor-config-info null) ,obj)) (if (or (not ,obj) ,regen) (setf (gethash ',place ,hash) (make-instance 'accessor-config-info :name ,(format nil "config-info-~A" place) :predicate ,pred :place ',place :db ,(if db db '*default-db*) :valid-values ,valid-values ,@(when documentation (list :documentation documentation)) ,@(when coercer (list :coercer coercer)) ,@(when tags (list :tags tags)))) ,obj)))) (defmacro define-accessor-config (accessor &key validator typespec coercer db tags regen-config documentation) "Define an accessor config object and place it in DB with the key ACCESSOR" (when (and validator typespec) (error "The arguments :VALIDATOR and :TYPESPEC cannot both be supplied")) `(defconf-a ,accessor ,@(cond (typespec `(:predicate (lambda (x) (typep x ,typespec)))) (validator `(:predicate ,validator))) :coercer ,coercer :db ,db :tags ,tags :documentation ,documentation :regen ,regen-config :valid-values ',(if typespec `(typespec ,typespec) `(function ,validator)))) ;;; Variable configs (defmacro defconf-v (place default &key predicate coercer db tags documentation regen valid-values) (alexandria:with-gensyms (hold hash validated obj pred) `(let* ((,pred ,(if predicate predicate #'cl::identity)) (,hold ,default) (,hash (cdr ,(if db db '*default-db*))) (,validated (funcall ,pred ,hold)) (,obj (gethash ',place ,hash))) (declare (type function ,pred) (type hash-table ,hash) (type (or config-info minimal-config-info null) ,obj)) (unless ,validated (error 'invalid-datum-error :place ',place :value ,hold)) (if (or (not ,obj) ,regen) (setf (gethash ',place ,hash) (make-instance 'config-info :name ,(format nil "config-info-~A" place) :predicate ,pred ,@(when coercer `(:coercer ,coercer)) ,@(when documentation `(:documentation ,documentation )) ,@(when tags `(:tags ,tags)) :place ',place :default ,hold :db ,(if db db '*default-db*) :valid-values ,valid-values)) ,obj)))) (defmacro define-variable-config (place default-value &key validator typespec coercer db tags documentation regen-config) "Define a variable config object and place it in DB with the key PLACE." (when (and validator typespec) (error "The arguments :VALIDATOR and :TYPESPEC cannot both be supplied")) `(defconf-v ,place ,default-value ,@(cond (typespec `(:predicate (lambda (x) (typep x ,typespec)))) (validator `(:predicate ,validator))) :coercer ,coercer :db ,db :tags ,tags :documentation ,documentation :regen ,regen-config :valid-values ',(if typespec `(typespec ,typespec) `(function ,validator)))) (defmacro defconfig (place &rest args) "Defconfig defines a config-info object and potentially a dynamic variable. PLACE may be either a symbol or a list of length 1. If PLACE is a list, defconfig functions as a wrapper around define-accessor-config. If it is a symbol, defconfig defines a variable config as well as a dynamic variable. Additionally, if the first element of ARGS is a keyword and the second element of ARGS is not a keyword, the default value will be the value of PLACE. The following keys are acceptable in ARGS: VALIDATOR, TYPESPEC, COERCER, DOCUMENTATION, DB, TAGS, and REGEN-CONFIG. REINITIALIZE is also acceptable if PLACE is a symbol. VALIDATOR and TYPESPEC may not coexist in a single defconfig call. VALIDATOR is for providing a function to validate values. It must take a single value, the value to validate. TYPESPEC takes a type specification and generates a validation function from it. If provided, COERCER must be a function taking a single argument: the value to coerce. It is called iff an invalid value is passed to setv, and it is called on the invalid value in an attempt to generate a valid one. The return value of COERCER is checked against the VALIDATOR (or the function generated with TYPESPEC) and if it is valid it is used in place of the original value. DOCUMENTATION is the documentation of PLACE and is used in the defvar/defparameter form when PLACE is a symbol and is placed in the config-info object regardless of whether PLACE is a symbol or a list. DB is the database to place the generated config-info object into, and defaults to *default-db*. Defconfig does not check if DB is in the plist of databases before placing the config-info object into DB. It is assumed that if a DB has been removed from the database plist the user has a good understanding of what they are doing and is managing the database themselves. (databases must be manually removed from the plist). TAGS are strings that can be used to search for a config-info object. The search functionality is currently only partially implemented." (cond ((consp place) `(define-accessor-config ,(car place) ,@args)) ((and (keywordp (car args)) (not (keywordp (cadr args)))) ;; then we have no default value and we want to use the current value of ;; place. (destructuring-bind (&key validator typespec coercer db tags reinitialize documentation regen-config) args (declare (ignore reinitialize)) `(define-variable-config ,place ,place :validator ,validator :typespec ,typespec :coercer ,coercer :db ,db :tags ,tags :documentation ,documentation :regen-config ,regen-config))) (t (destructuring-bind (default &key validator typespec coercer db tags reinitialize documentation regen-config) args (alexandria:with-gensyms (hold) `(let ((,hold ,default)) (prog1 (restart-case (define-variable-config ,place ,hold :validator ,validator :typespec ,typespec :coercer ,coercer :db ,db :tags ,tags :documentation ,documentation :regen-config ,regen-config) (define-variable-regardless () nil)) (,(if reinitialize 'defparameter 'defvar) ,place ,hold ,@(when documentation (list documentation))))))))))
10,147
Common Lisp
.lisp
202
38.881188
82
0.607334
szos/defconfig
12
2
0
LGPL-2.1
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
9ba6a1d945fbed1c12ea506da1defc42d519c59fbf86650cbb8670c7da6c12b2
9,584
[ -1 ]
9,585
macros.lisp
szos_defconfig/macros.lisp
(in-package :defconfig) (defmacro atypecase (thing &body cases) `(let ((it ,thing)) (typecase it ,@cases)))
123
Common Lisp
.lisp
5
20.6
39
0.632479
szos/defconfig
12
2
0
LGPL-2.1
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
80b533b7c196b68b12dfbfb4ce4af86419bfddb7762388f460cc427296ca6edf
9,585
[ -1 ]
9,586
setv.lisp
szos_defconfig/setv.lisp
(in-package :defconfig) (defconfig *setv-permissiveness* :STRICT :typespec '(member :STRICT :GREEDY :PERMISSIVE :GREEDY+PERMISSIVE) :tags '("setv" "permissiveness" "allow other values") :documentation "Determines how setv will act when no config-info object is found. :STRICT means to error out. :GREEDY means to search through all registered databases for a config-info object and use the first one that is found, or if none is found error out. :PERMISSIVE means to setf when a config-info object isnt found. :GREEDY+PERMISSIVE means to search through all registered databases and use the first object found, but if one isnt found to setf regardless.") (defun remove-keys (list keys) "returns two values - accumulated non-keys and keys " (declare (type list list) (type list keys)) (labels ((wanted-key-p (thing) (loop for el in keys for keys-key = (if (listp el) (car el) el) when (eql keys-key thing) do (return-from wanted-key-p t))) (churn (list accum-rest accum-keys) (cond ((not list) (values (reverse accum-rest) (reverse accum-keys))) ((wanted-key-p (car list)) (churn (cddr list) accum-rest (cons (cadr list) (cons (car list) accum-keys)))) (t (churn (cdr list) (cons (car list) accum-rest) accum-keys))))) (churn list nil nil))) (defmacro destructuring-keys ((var &rest keys) list &body body) "separates keys from list, storing the remainder in VAR, and making each key a variable via destructuring-bind." (alexandria:with-gensyms (key-hold) `(multiple-value-bind (,var ,key-hold) (remove-keys ,list ',keys) (destructuring-bind (&key ,@(loop for k in keys if (listp k) collect (cons (read-from-string (symbol-name (car k))) (cdr k)) else collect (read-from-string (symbol-name k)))) ,key-hold ,@body)))) (defmacro %setv-ensure-setf (place value config-info-object) (alexandria:with-gensyms (holdover) `(progn ,(if (listp place) `(setf ,place ,value) `(let ((,holdover ,place)) (setf ,place ,value) (when (typep ,config-info-object 'config-info) (setf (config-info-prev-value ,config-info-object) ,holdover)))) ,value))) (defun %fsetv-ensure-validity (throwtag config-info-object value invalid-symbol &optional errorp place error extra-args) "check VALUE against CONFIG-INFO-OBJECTs predicate. return VALUE if it passes. If ERRORP is true error if VALUE doesnt pass. If ERRORP is nil and VALUE doesnt pass, return INVALID-SYMBOL. Restarts are put in place to provide a value or set regardless." (declare (type symbol throwtag) (type (or config-info accessor-config-info minimal-config-info) config-info-object) (type (or symbol null) invalid-symbol) (type boolean errorp) (type (or symbol list) place) (type (or symbol null) error) (type list extra-args)) (let ((real-place (or place (config-info-place config-info-object)))) (declare (type (or symbol list) real-place)) (restart-case (let ((valid? (funcall (config-info-predicate config-info-object) value))) (cond (valid? value) (errorp (if error (apply 'error error (append extra-args (list :config-object config-info-object :place real-place :value value))) (error 'invalid-datum-error :config-object config-info-object :place real-place :value value))) (t invalid-symbol))) (continue () :report (lambda (s) (format s "Return NIL without setting ~A" real-place)) (throw throwtag nil)) (use-value (provided) :test (lambda (c) (typep c 'invalid-datum-error)) :report (lambda (s) (format s "Supply a new value for ~S" real-place)) :interactive (lambda () (format *query-io* "Enter Value: ") (force-output *query-io*) (list (read *query-io*))) (return-from %fsetv-ensure-validity provided)) (use-validated-value (provided) :test (lambda (c) (typep c 'invalid-datum-error)) :report (lambda (s) (format s "Supply a new value to be validated for ~S" real-place)) :interactive (lambda () (format *query-io* "Enter Value: ") (force-output *query-io*) (list (read *query-io*))) (%fsetv-ensure-validity throwtag config-info-object provided invalid-symbol errorp real-place)) (set-regardless () :test (lambda (c) (typep c 'invalid-datum-error)) :report (lambda (s) (format s "Regardless of validity, set ~S to ~S" real-place value)) (return-from %fsetv-ensure-validity value))))) (defmacro %%setv-coerced (place value config-object coercer throwtag) (alexandria:with-gensyms (coer-hold validated-value invalid-sym) `(if ,coercer (let* ((,coer-hold (funcall ,coercer ,value)) (,validated-value (%fsetv-ensure-validity ,throwtag ,config-object ,coer-hold ',invalid-sym t ',place 'invalid-coerced-datum-error (list :coerced-value ,coer-hold)))) ;; we dont need to check ,validated-values here as we will ALWAYS error ;; if we get a invalid coerced data. (%setv-ensure-setf ,place ,validated-value ,config-object)) (case *setv-permissiveness* ((:permissive :greedy+permissive) (%setv-ensure-setf ,place ,value ,config-object)) (otherwise (error 'invalid-datum-error :config-object ,config-object :place ',place :value ,value)))))) (defun %fsetv-get-config-info-object (place hash db &optional setf-symbol) "return setf symbol if we want the caller to setf place. setf-symbol only needs to be provided if were calling this in a setv expansion." (declare (type (or symbol list) place) (type hash-table hash) (type (or symbol cons) db) (type (or symbol null) setf-symbol)) (handler-case (or (gethash (if (listp place) (car place) place) hash) (error 'no-config-found-error :place place :db db)) (no-config-found-error (c) (case *setv-permissiveness* (:strict (error c)) (:permissive (return-from %fsetv-get-config-info-object setf-symbol)) ((:greedy :greedy+permissive) (let* ((config-obj (loop for (key db) on *db-plist* by 'cddr for obj = (place->config-info place :db (cdr db)) when obj return (cons obj db)))) (cond (config-obj (warn "*SETV-PERMISSIVENESS* is ~S, using configuration object from database ~S rather than ~S" *setv-permissiveness* (cadr config-obj) db) (return-from %fsetv-get-config-info-object (car config-obj))) ((eql *setv-permissiveness* :greedy+permissive) (return-from %fsetv-get-config-info-object setf-symbol)) (t (error 'no-config-found-error :place place :db 'all-registered-databases))))))))) (defmacro %%setv (place value db) (alexandria:with-gensyms (hold hash config-info-object invalid-sym validated-value coer setf?-sym block) `(let ((,hold ,value)) (catch ',block (let* ((,hash ,(if (listp place) `(car ,db) `(cdr ,db))) (,config-info-object (let ((obj (%fsetv-get-config-info-object ',place ,hash ',db ',setf?-sym))) (if (eql obj ',setf?-sym) (progn (setf ,place ,hold) (throw ',block ,hold)) obj))) (,coer (config-info-coercer ,config-info-object)) (,validated-value ;; get a validated value - we use this instead of hold because ;; if there is a coercer for the place we will return invalid-sym ;; when ,hold is invalid, and if not we will error out with ;; restarts in place to provide a value or set regardless (%fsetv-ensure-validity ',block ,config-info-object ,hold ',invalid-sym (not ,coer) ',place))) (declare (type hash-table ,hash) (type (or minimal-config-info accessor-config-info config-info null) ,config-info-object) (type (or function null) ,coer)) (if (eql ,validated-value ',invalid-sym) (%%setv-coerced ,place ,hold ,config-info-object ,coer ',block) (%setv-ensure-setf ,place ,validated-value ,config-info-object))))))) (defmacro setv (&rest args) "Setv must get an even number of ARGS - every place must have a value. Setv can also take the key argument :db, to specify which database to look up config objects in. " (destructuring-keys (pairs (:db '*default-db*)) args `(progn ,@(loop for (p v) on pairs by 'cddr collect `(%%setv ,p ,v ,db))))) (defmacro setv-atomic (&rest args) "this version of setv saves the original value of the places being set, and resets all to their original value if an error is encountered. the error is then resignalled. It is generally advisable to use WITH-ATOMIC-SETV instead." (alexandria:with-gensyms (c) (multiple-value-bind (pairs db) (remove-keys args '(:db)) (let ((syms (loop for (p v) on pairs by 'cddr collect (gensym)))) `(let ,(loop for (place value) on pairs by 'cddr for gensym in syms collect `(,gensym ,place)) (handler-case (progn ,@(loop for (place value) on pairs by 'cddr collect `(%%setv ,place ,value ,@(if db (cdr db) '(*default-db*))))) (error (,c) ,@(loop for (place value) on pairs by 'cddr for gensym in syms collect `(setf ,place ,gensym)) (error ,c)))))))) (defmacro %psetv (db pairs) (let ((gensyms (loop for x in pairs collect (gensym "NEW")))) `(let* ,(loop for (p v) on pairs by 'cddr for gensym in gensyms collect `(,gensym ,v)) ,@(loop for (p v) on pairs by 'cddr for gensym in gensyms collect `(%%setv ,p ,gensym ,db)) nil))) (defmacro psetv (&rest args) "The setv equivalent of psetf - set all places in parallel" (destructuring-keys (pairs (:db '*default-db*)) args `(%psetv ,db ,pairs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Compile-time with-atomic-setv ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro %atomic-setv-reset (accumulator &key (pop t)) "this macro resets all encountered places within a call to with-atomic-setv*." (declare (special *setv-place-accumulator*)) (let ((place-list (if pop (cdr *setv-place-accumulator*) *setv-place-accumulator*))) `(progn ,@(when pop `((pop ,accumulator))) ,@(loop for (db place) in place-list collect `(setf ,place (pop ,accumulator)))))) (defmacro %setv-with-reset (block-name reset-on accumulator place value db) "Wrap setv in a handler to catch all errors, which will reset all encountered places, after which it returns the condition from the named block." (declare (special *setv-place-accumulator*)) (push (list db place) *setv-place-accumulator*) (alexandria:with-gensyms (c) `(progn (push ,place ,accumulator) (handler-case (%%setv ,place ,value ,db) (,reset-on (,c) (%atomic-setv-reset ,accumulator) (return-from ,block-name ,c)))))) (defmacro %atomic-setv (block-name reset-on-errors accumulator database &rest args) "generates a set of calls to %setv-with-reset." (declare (special *setv-place-accumulator*)) (destructuring-keys (pairs (:db database)) args `(progn ,@(loop for (p v) on pairs by 'cddr collect `(%setv-with-reset ,block-name ,reset-on-errors ,accumulator ,p ,v ,db))))) (defmacro %with-atomic-setv* ((&key (re-error t) handle-conditions db) &body body) "This macro utilizes compiler-let to allow rollbacks of accessor stuff. " (alexandria:with-gensyms (args block-name c inner-c accumulator) `(compiler-let ((*setv-place-accumulator* nil)) (let ((,c (block ,block-name (let ((,accumulator '())) (macrolet ((setv (&rest ,args) `(%atomic-setv ,',block-name ,',handle-conditions ,',accumulator ,',db ,@,args))) (handler-case (restart-case (progn ,@body) (abort-and-reset () :report "Exit WITH-ATOMIC-SETV* and reset" (error 'with-atomic-setv-internal-error)) (abort-without-resetting () :report "Exit WITH-ATOMIC-SETV* without resetting" (return-from ,block-name nil))) ((or with-atomic-setv-internal-error ,handle-conditions) (,inner-c) (%atomic-setv-reset ,accumulator :pop nil) (return-from ,block-name ,inner-c)))))))) (if (and ,re-error (typep ,c ',handle-conditions)) (error 'setv-wrapped-error :error ,c) ,c))))) (defmacro with-atomic-setv* ((&key (re-error t) handle-conditions db) &body body) `(%with-atomic-setv* (:re-error ,re-error :handle-conditions ,(or handle-conditions 'error) :db ,(or db '*default-db*)) ,@body)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Runtime with-atomic-setv ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro %runtime-atomic-setv-reset (accumulator &key pop) `(let ((already-reset nil)) (loop for (var val varplace) in (reverse (,(if pop 'cdr 'identity) ,accumulator)) unless (member var already-reset :test 'equalp) do (if (symbolp var) (setf (symbol-value var) val) (funcall (fdefinition `(setf ,(car var))) val varplace)) (push var already-reset)))) (defmacro %runtime-setv-with-reset (ac block-name reset-errors place value db) (alexandria:with-gensyms (c acplace) `(let ((,acplace ,(if (listp place) (cadr place) place))) (push (list ',place (funcall ',(if (listp place) (car place) 'identity) ,acplace) ,acplace) ,ac) (handler-case (%%setv ,(if (listp place) `(,(car place) ,acplace) place) ,value ,db) (,reset-errors (,c) (%runtime-atomic-setv-reset ,ac :pop t) (return-from ,block-name ,c)))))) (defmacro %runtime-atomic-setv (accumulator block-name reset-errors database &rest args) (destructuring-keys (pairs (:db database)) args `(progn ,@(loop for (p v) on pairs by 'cddr collect `(%runtime-setv-with-reset ,accumulator ,block-name ,reset-errors ,p ,v ,db))))) (defmacro with-runtime-atomic-setv ((&key (re-error t) handle-conditions db) &body body) (alexandria:with-gensyms (block-name args c inner-c outer-block accumulator) `(block ,outer-block (let ((,c (block ,block-name (let ((,accumulator nil)) (macrolet ((setv (&rest ,args) `(%runtime-atomic-setv ,',accumulator ,',block-name ,',handle-conditions ,',db ,@,args))) (handler-case (restart-case (progn ,@body) (abort-and-reset () :report "Exit WITH-ATOMIC-SETV and reset everything" ;; (%runtime-atomic-setv-reset ,accumulator) ;; (return-from ,outer-block nil) (error 'with-atomic-setv-internal-error)) (abort-without-resetting () :report "Exit WITH-ATOMIC-SETV without resetting" (return-from ,outer-block nil))) ((or with-atomic-setv-internal-error ,handle-conditions) (,inner-c) (%runtime-atomic-setv-reset ,accumulator) (return-from ,block-name ,inner-c)))))))) (if (and ,re-error (typep ,c ',handle-conditions)) (error 'setv-wrapped-error :error ,c) (progn (typecase ,c (error (warn "WITH-ATOMIC-SETV encountered the error~%~S~%and reset." ,c)) (warning (warn ,c))) ,c)))))) (defmacro with-atomic-setv ((&key (errorp t) handle-conditions db) &body body) "This macro, upon encountering an error, resets all places encountered within calls to setv to be reset to the value they held before the call to with-atomic-setv. Which errors to reset upon can be controlled with HANDLE-CONDITIONS. If it is nil, it defaults to 'error. If a handled condition is encountered, it will be wrapped in SETV-WRAPPED-ERROR, unless RE-ERROR is nil, in which case a warning will be generated and the condition will be returned. " `(with-runtime-atomic-setv (:re-error ,errorp :handle-conditions ,(or handle-conditions 'error) :db ,(or db '*default-db*)) ,@body))
16,857
Common Lisp
.lisp
387
35.700258
143
0.61632
szos/defconfig
12
2
0
LGPL-2.1
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
696e7e1c3964a29cc5589eddf658182e00675e56a9c85155a177fe92e9134def
9,586
[ -1 ]
9,587
defconfig-tests.lisp
szos_defconfig/tests/defconfig-tests.lisp
(defpackage #:defconfig/tests (:use #:cl) ;; (:local-nicknames (#:am #:fiveam)) (:import-from #:defconfig #:defconfig #:setv #:with-atomic-setv #:setv-atomic #:make-config-database #:reset-place #:with-atomic-setv* #:define-defconfig-db #:get-db #:delete-db #:*setv-permissiveness* #:define-accessor-config #:define-minimal-config #:defconfig-minimal #:psetv) (:import-from #:fiveam #:is #:signals)) (in-package :defconfig/tests) (defparameter *counter* 0) (defconfig:delete-db :testing t) (define-defconfig-db *testing-db* :testing) (defconfig *light-dark* 'dark :typespec '(member dark light) :db *testing-db* :reinitialize t :regen-config t) (defconfig *bounded-number* 0 :typespec '(integer 0 10) :coercer (lambda (x) (if (stringp x) (parse-integer x) x)) :documentation "A number with the bounds 0 to 10 inclusive" :tags '("bounded number" "integer") :db *testing-db* :reinitialize t :regen-config t) (defconfig *other-bounded-number* 0 :typespec '(integer 0 10) :coercer (lambda (x) (if (stringp x) (parse-integer x) x)) :documentation "A number with the bounds 0 to 10 inclusive" :tags '("bounded number" "integer") :db *testing-db* :reinitialize t :regen-config t) (defclass testing-class () ((slot1 :initarg :1 :accessor testing-class-slot-1) (slot2 :initarg :2 :accessor testing-class-slot-2))) (defparameter *testing-class* (make-instance 'testing-class :1 1 :2 -2)) (deftype non-positive-integer () '(integer * 0)) (defconfig (testing-class-slot-1) :typespec '(integer -10 10) :regen-config t) (define-accessor-config testing-class-slot-2 :typespec 'non-positive-integer :coercer (lambda (x) (if (numberp x) (- x) x)) :regen-config t) (defparameter *testing-class* (make-instance 'testing-class :1 0 :2 0)) (fiveam:test makedb (fiveam:is (consp *testing-db*)) (fiveam:is (hash-table-p (car *testing-db*))) (fiveam:is (hash-table-p (cdr *testing-db*))) (fiveam:is (eq (get-db :testing) *testing-db*))) (fiveam:test test-defconfig (fiveam:is (eql 'dark *light-dark*)) (fiveam:is (typep (defconfig::place->config-info '*light-dark* :db *testing-db*) 'defconfig::config-info))) (fiveam:test test-setv (fiveam:is (eql 'dark *light-dark*)) (let ((defconfig::*setv-permissiveness* :strict)) (fiveam:signals defconfig::no-config-found-error (setv *light-dark* 'light))) (fiveam:is (eql (setv *light-dark* 'light :db *testing-db*) 'light)) (fiveam:signals defconfig::invalid-datum-error (setv *light-dark* 'neither-light-nor-dark :db *testing-db*)) (is (eql *light-dark* 'light)) ;; why does (signals warning ...) not allow us to continue? i think we need ;; another macro here specifically for warnings - signals expands into a ;; handler-bind on the condition and returns from the block prematurely, which ;; is fine and dandy if were dealing with errors, but the warning here is meant ;; to warn the user but still process the setv, not abort early... (signals warning (let ((defconfig::*setv-permissiveness* :greedy)) (setv *light-dark* 'dark))) (is (eql *light-dark* 'light)) (is (eql (let ((defconfig::*setv-permissiveness* :greedy)) (setv *light-dark* 'dark)) 'dark)) (is (eql *light-dark* 'dark)) (let ((*setv-permissiveness* :permissive)) (setv *light-dark* "invalid value")) (is (string= *light-dark* "invalid value")) (setf *light-dark* 'dark) (signals defconfig:config-error (let ((*setv-permissiveness* :greedy+permissive)) (setv *light-dark* "invalid value"))) (is (eql *light-dark* 'dark))) (fiveam:test fine-grained-w-a-s-signal-setv-wrapped-error (unless (= *bounded-number* 0) (setv *bounded-number* 0 :db *testing-db*)) (is (= *bounded-number* 0)) (signals defconfig::setv-wrapped-error (with-atomic-setv () (setv *bounded-number* 1 :db *testing-db*) (error "testing-error"))) (is (= *bounded-number* 0)) (signals defconfig::setv-wrapped-error (with-atomic-setv* () (setv *bounded-number* 1 :db *testing-db*) (error "testing-error"))) (is (= *bounded-number* 0))) (fiveam:test fine-grained-w-a-s-invalid-datum-error (setv *bounded-number* 0 :db *testing-db*) (is (= *bounded-number* 0)) (signals defconfig:invalid-datum-error (handler-case (with-atomic-setv () (setv *bounded-number* 20 :db *testing-db*)) (defconfig::setv-wrapped-error (c) (error (defconfig::setv-wrapped-error-condition c))))) (is (= *bounded-number* 0)) (signals defconfig:invalid-datum-error (handler-case (with-atomic-setv* () (setv *bounded-number* 20 :db *testing-db*)) (defconfig::setv-wrapped-error (c) (error (defconfig::setv-wrapped-error-condition c))))) (is (= *bounded-number* 0))) (fiveam:test test-with-atomic-setv (setv *bounded-number* 0 :db *testing-db*) (is (= *bounded-number* 0)) (signals defconfig::setv-wrapped-error (with-atomic-setv () (setv *bounded-number* 1 :db *testing-db*) (error "testing-error"))) (signals defconfig::setv-wrapped-error (with-atomic-setv* () (setv *bounded-number* 1 :db *testing-db*) (error "testing-error"))) (is (= *bounded-number* 0)) (is (= 3 (with-atomic-setv () (setv *bounded-number* 3 :db *testing-db*)))) (is (= 1 (with-atomic-setv* () (setv *bounded-number* 1 :db *testing-db*)))) (signals defconfig:invalid-datum-error (handler-case (with-atomic-setv () (setv *bounded-number* 20 :db *testing-db*)) (defconfig::setv-wrapped-error (c) (error (defconfig::setv-wrapped-error-condition c))))) (signals defconfig:invalid-datum-error (handler-case (with-atomic-setv* () (setv *bounded-number* 20 :db *testing-db*)) (defconfig::setv-wrapped-error (c) (error (defconfig::setv-wrapped-error-condition c)))))) (fiveam:test test-w-a-s-specific-errors (with-atomic-setv (:handle-conditions defconfig::config-error) (setv *other-bounded-number* 1 *bounded-number* 1 :db *testing-db*)) (is (and (equal *bounded-number* 1) (equal *other-bounded-number* 1))) (with-atomic-setv* (:handle-conditions defconfig::config-error) (setv *other-bounded-number* 2 *bounded-number* 2 :db *testing-db*)) (is (and (equal *bounded-number* 2) (equal *other-bounded-number* 2))) (setf *bounded-number* 0 *other-bounded-number* 0) (signals simple-error (with-atomic-setv (:handle-conditions defconfig::config-error) (setv *other-bounded-number* 2 *bounded-number* 2 :db *testing-db*) (error "ahhhh!!!"))) (is (and (equal *bounded-number* 2) (equal *other-bounded-number* 2))) (signals simple-error (with-atomic-setv* (:handle-conditions defconfig::config-error) (setv *other-bounded-number* 3 *bounded-number* 3 :db *testing-db*) (error "ahhhh!!!"))) (is (and (equal *bounded-number* 3) (equal *other-bounded-number* 3)))) (fiveam:test test-for-prev-value-with-atomic-setv (setv *bounded-number* 0 :db *testing-db*) (signals defconfig:config-error (with-atomic-setv () (setv *bounded-number* 1 :db *testing-db*) (setv *bounded-number* 2 :db *testing-db*) (setv *bounded-number* 50 :db *testing-db*))) (is (= *bounded-number* 0)) (signals defconfig:config-error (with-atomic-setv* () (setv *bounded-number* 1 :db *testing-db*) (setv *bounded-number* 2 :db *testing-db*) (setv *bounded-number* 50 :db *testing-db*))) (is (= *bounded-number* 0)) (is (= (setv *bounded-number* 5 :db *testing-db*) 5)) (signals defconfig:config-error (with-atomic-setv () (setv *bounded-number* 1 :db *testing-db*) (setv *bounded-number* 2 :db *testing-db*) (setv *bounded-number* 50 :db *testing-db*))) (is (= *bounded-number* 5)) (signals simple-error (with-atomic-setv (:handle-conditions defconfig:config-error) (setv *bounded-number* 1 :db *testing-db*) (setv *bounded-number* 2 :db *testing-db*) (error "simple error") (setv *bounded-number* 3 :db *testing-db*) (setv *bounded-number* 4 :db *testing-db*))) (is (= *bounded-number* 2)) (setf *bounded-number* 0) (signals simple-error (with-atomic-setv* (:handle-conditions defconfig:config-error) (setv *bounded-number* 1 :db *testing-db*) (setv *bounded-number* 2 :db *testing-db*) (error "simple error") (setv *bounded-number* 3 :db *testing-db*) (setv *bounded-number* 4 :db *testing-db*))) (is (= *bounded-number* 2))) (fiveam:test test-setv-atomic (is (eql (setv *light-dark* 'dark :db *testing-db*) 'dark)) (signals defconfig:invalid-datum-error (setv *light-dark* 'invalid :db *testing-db*))) (fiveam:test test-coercion (is (= (setv *bounded-number* 0 :db *testing-db*) 0)) (is (= *bounded-number* 0)) (is (= (setv *bounded-number* "1" :db *testing-db*) 1)) (is (= *bounded-number* 1)) (signals defconfig:invalid-coerced-datum-error (setv *bounded-number* "20" :db *testing-db*)) (is (= *bounded-number* 1))) (fiveam:test test-accessor-validation (setv (testing-class-slot-1 *testing-class*) 2) (is (= (testing-class-slot-1 *testing-class*) 2)) (signals defconfig:invalid-datum-error (setv (testing-class-slot-1 *testing-class*) 20)) (is (= (setv (testing-class-slot-2 *testing-class*) 0) 0)) (signals defconfig:invalid-datum-error (setv (testing-class-slot-2 *testing-class*) "hi")) (is (= (setv (testing-class-slot-2 *testing-class*) 8) -8))) (fiveam:test test-with-atomic-setv-on-accessors (with-atomic-setv () (setv (testing-class-slot-1 *testing-class*) 4)) (is (= (testing-class-slot-1 *testing-class*) 4)) ;; this will not work with the pure runtime version of w-a-s. ;; below this we use w-a-s* which does its computations jointly at runtime ;; and macroexpansion time via compiler-let. (signals error (with-atomic-setv () (setv (testing-class-slot-1 *testing-class*) 8) (error "foo"))) (is (= (testing-class-slot-1 *testing-class*) 4)) ;; this was the test that is failing... ;; ;; test with compiler-let w-a-s* (setf (testing-class-slot-1 *testing-class*) 0) (signals defconfig:config-error (with-atomic-setv* () (setv (testing-class-slot-1 *testing-class*) 1) (error "foo"))) (is (= (testing-class-slot-1 *testing-class*) 0))) (fiveam:test test-w-a-s* (let ((*setv-permissiveness* :greedy)) (with-atomic-setv* () (setv *bounded-number* 1))) (is (= *bounded-number* 1))) (defconfig *var1* 0 :typespec 'integer) (defmacro var1 () '*var1*) (defconfig *var2* 0 :typespec 'integer) (defconfig *var3* 0 :typespec 'integer) (defconfig *var4* 0 :typespec 'integer) (defconfig *var5* 0 :typespec 'integer) (fiveam:test test-many-setvs* (setf *var1* 0) (signals error (with-atomic-setv* () (setv *var1* 1) (setv *var2* 1) (setv *var3* 1) (setv *var4* 1) (setv *var5* 1) (error "foo"))) (is (= *var1* 0)) (is (= *var2* 0)) (is (= *var3* 0)) (is (= *var4* 0)) (is (= *var5* 0))) (fiveam:test test-side-effects-within-accessor-w-a-s (setf *counter* 0) (setf (testing-class-slot-1 *testing-class*) 0) (with-atomic-setv () (setv (testing-class-slot-1 (progn (incf *counter*) *testing-class*)) -9) (setv (testing-class-slot-1 (progn (incf *counter*) *testing-class*)) -8) (setv (testing-class-slot-1 (progn (incf *counter*) *testing-class*)) -7)) (is (= *counter* 3)) (is (= (testing-class-slot-1 *testing-class*) -7)) (setf *counter* 0) (setv (testing-class-slot-1 *testing-class*) 0) (signals defconfig:setv-wrapped-error (with-atomic-setv () (setv (testing-class-slot-1 (progn (incf *counter*) *testing-class*)) -9) (setv (testing-class-slot-1 (progn (incf *counter*) *testing-class*)) -8) (setv (testing-class-slot-1 (progn (incf *counter*) *testing-class*)) -7) (error "ohnoerror"))) (is (= *counter* 3)) (is (= (testing-class-slot-1 *testing-class*) 0))) (fiveam:test test-setv-with-macro (setf *var1* 0) (setf *setv-permissiveness* :strict) (signals defconfig:no-config-found-error (setv (var1) 1)) (is (= *var1* 0)) (setf *setv-permissiveness* :permissive) (setv (var1) 1) (is (= *var1* 1)) (setf *var1* 0)) (defconfig-minimal *min* 0 :typespec '(integer 0 10) :coercer (lambda (n) (handler-case (abs n) (error () n))) :reinitialize t :regen-config t) (fiveam:test minimal-configs (signals defconfig:config-error (setv *min* 300)) (is (= *min* 0))) (defconfig-minimal *a* 'a :typespec 'symbol) (defconfig-minimal *b* "b" :typespec 'string) (defconfig-minimal *c* 'c :typespec 'symbol) (fiveam:test test-psetv (is (and (eql *a* 'a) (eql *c* 'c))) (psetv *a* *c* *c* *a*) (is (and (eql *a* 'c) (eql *c* 'a))) (signals defconfig:invalid-datum-error (psetv *a* *c* *b* *a* *c* *a*)) (is (and (eql *a* 'a) (string= *b* "b") (eql *c* 'a))) (psetv *a* 'a *c* 'c *b* "b") (is (and (eql *a* 'a) (string= *b* "b") (eql *c* 'c)))) (fiveam:test test-predicateless (defconfig *mytester* 'mytester)) (fiveam:test test-w-a-s-use-default-db (setv *bounded-number* 0 *other-bounded-number* 0 :db *testing-db*) (setv *setv-permissiveness* :strict) (is (and (= *bounded-number* 0) (= *other-bounded-number* 0))) (with-atomic-setv (:db *testing-db*) (setv *bounded-number* 2) (setv *other-bounded-number* 1)) (is (and (= *bounded-number* 2) (= *other-bounded-number* 1))) (with-atomic-setv* (:db *testing-db*) (setv *bounded-number* 0) (setv *other-bounded-number* 0)) (is (and (= *bounded-number* 0) (= *other-bounded-number* 0))))
14,209
Common Lisp
.lisp
427
28.681499
82
0.63766
szos/defconfig
12
2
0
LGPL-2.1
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
0a953d721f972789f896d5255798f1c82b23a710c1357c739829f98a64568c22
9,587
[ -1 ]
9,588
defconfig.asd
szos_defconfig/defconfig.asd
;;;; defconfig.asd (asdf:defsystem #:defconfig :description "A configuration system for user exposed variables" :author "szos at posteo dot net" :license "GPLv3" :version "1.2.1" :serial t :depends-on (#:alexandria #-clisp #:trivial-cltl2) :components ((:file "package") (:file "macros") (:file "database") (:file "classes") (:file "conditions") (:file "defconfig") (:file "setv") (:file "access"))) (asdf:defsystem #:defconfig/tests :description "test suite for defconfig" :author "Your Name <[email protected]>" :license "GPLv3" :version "0.0.1" :serial t :depends-on (#:fiveam #:defconfig) :components ((:file "tests/defconfig-tests")))
759
Common Lisp
.asd
25
24.76
66
0.618852
szos/defconfig
12
2
0
LGPL-2.1
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
3b75830f80bb8f3c50b780d67fcfe951ca0688ae14aefd2b7ebd4da355a491cc
9,588
[ -1 ]
9,596
.travis.yml
szos_defconfig/.travis.yml
language: lisp sudo: required env: matrix: - LISP=sbcl - LISP=ccl - LISP=abcl - LISP=ecl - LISP=allegro # either use a local install.sh script or install it via curl. Feel # free to simplify this section in your own .travis.yml file. install: - if [ -x ./install.sh ] && head -2 ./install.sh | grep '^# cl-travis' > /dev/null; then ./install.sh; else curl https://raw.githubusercontent.com/luismbo/cl-travis/master/install.sh | sh; fi # this serves as an example of how to use the 'cl' script (provided by # CIM) to test your Lisp project. Here, we're using the RT framework # to do unit testing; other frameworks will have different ways of # determining whether a test suite fails or succeeds. script: - cl -e '(ql:quickload :defconfig) (ql:quickload :defconfig/tests)' -e '(in-package :common-lisp-user)' -e '(setf *debugger-hook* (function (lambda (mysym h) (declare (ignore mysym h)) (uiop:quit -1))))' -e '(unless (fiveam:run!) (uiop:quit 1))' [ $? -eq 1 ]
1,146
Common Lisp
.l
33
28.181818
86
0.610261
szos/defconfig
12
2
0
LGPL-2.1
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
464bc0b8b3fa70946f22f15c37ae908a7bf2981c246452ee104407edb9880e11
9,596
[ -1 ]
9,614
package.lisp
glv2_cl-zstd/src/package.lisp
;;; This file is part of cl-zstd ;;; Copyright 2020-2022 Guillaume LE VAILLANT ;;; Distributed under the GNU GPL v3 or later. ;;; See the file LICENSE for terms of use and distribution. (defpackage :zstd (:use :cl :trivial-gray-streams) (:export #:compress-stream #:compress-file #:compress-buffer #:decompress-stream #:decompress-file #:decompress-buffer #:make-compressing-stream #:make-decompressing-stream #:with-compressing-stream #:with-decompressing-stream #:zstd-error))
594
Common Lisp
.lisp
17
27.176471
59
0.630208
glv2/cl-zstd
15
4
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
c883e4a492c93456adf051af9516a87a097871dd29b845e654f0051d9675c4f7
9,614
[ -1 ]
9,615
libzstd.lisp
glv2_cl-zstd/src/libzstd.lisp
;;; This file is part of cl-zstd ;;; Copyright 2020 Guillaume LE VAILLANT ;;; Distributed under the GNU GPL v3 or later. ;;; See the file LICENSE for terms of use and distribution. (in-package :zstd) (cffi:define-foreign-library libzstd (:darwin "libzstd.dylib") (:unix (:or "libzstd.so" "libzstd.so.1")) (t (:default "libzstd"))) (cffi:use-foreign-library libzstd) ;;; ;;; Types ;;; (deftype i32 () '(signed-byte 32)) (deftype u32 () '(unsigned-byte 32)) (deftype u64 () '(unsigned-byte 64)) (cffi:defcstruct zstd-in-buffer (src :pointer) (size :unsigned-long-long) (pos :unsigned-long-long)) (cffi:defcstruct zstd-out-buffer (dst :pointer) (size :unsigned-long-long) (pos :unsigned-long-long)) (cffi:defcenum zstd-c-parameter (:zstd-c-compression-level 100) (:zstd-c-checksum-flag 201) (:zstd-c-nb-workers 400)) (cffi:defcenum zstd-end-directive :zstd-e-continue :zstd-e-flush :zstd-e-end) ;;; ;;; Error functions ;;; (declaim (ftype (function (u64) u32) zstd-is-error)) (cffi:defcfun ("ZSTD_isError" zstd-is-error) :unsigned-int "Tell if a function result is an error code." (code :unsigned-long-long)) (declaim (ftype (function (u64) t) zstd-get-error-name)) (cffi:defcfun ("ZSTD_getErrorName" zstd-get-error-name) :string "Return a readable string from an error code." (code :unsigned-long-long)) ;;; ;;; Compression functions ;;; (declaim (ftype (function () t) zstd-create-cctx)) (cffi:defcfun ("ZSTD_createCCtx" zstd-create-cctx) :pointer "Create a compression context.") (declaim (ftype (function (t) u64) zstd-free-cctx)) (cffi:defcfun ("ZSTD_freeCCtx" zstd-free-cctx) :unsigned-long-long "Free a compression context." (cctx :pointer)) (declaim (ftype (function (t t i32) u64) zstd-cctx-set-parameter)) (cffi:defcfun ("ZSTD_CCtx_setParameter" zstd-cctx-set-parameter) :unsigned-long-long "Set one compression parameter." (cctx :pointer) (param zstd-c-parameter) (value :int)) (declaim (ftype (function () i32) zstd-min-c-level)) (cffi:defcfun ("ZSTD_minCLevel" zstd-min-c-level) :int "Minimum compression level available.") (declaim (ftype (function () i32) zstd-max-c-level)) (cffi:defcfun ("ZSTD_maxCLevel" zstd-max-c-level) :int "Maximum compression level available.") (declaim (ftype (function (t t t t) u64) zstd-compress-stream2)) (cffi:defcfun ("ZSTD_compressStream2" zstd-compress-stream2) :unsigned-long-long "Compress the data with additional control on end directive." (cctx :pointer) (output :pointer) (input :pointer) (endop zstd-end-directive)) (declaim (ftype (function () u64) zstd-c-stream-in-size)) (cffi:defcfun ("ZSTD_CStreamInSize" zstd-c-stream-in-size) :unsigned-long-long "Recommended size for compression input buffer.") (declaim (ftype (function () u64) zstd-c-stream-out-size)) (cffi:defcfun ("ZSTD_CStreamOutSize" zstd-c-stream-out-size) :unsigned-long-long "Recommended size for compression output buffer.") ;;; ;;; Decompression functions ;;; (declaim (ftype (function () t) zstd-create-dctx)) (cffi:defcfun ("ZSTD_createDCtx" zstd-create-dctx) :pointer "Create a decompression context.") (declaim (ftype (function (t) u64) zstd-free-dctx)) (cffi:defcfun ("ZSTD_freeDCtx" zstd-free-dctx) :unsigned-long-long "Free a decompression context." (dctx :pointer)) (declaim (ftype (function (t t t) u64) zstd-decompress-stream)) (cffi:defcfun ("ZSTD_decompressStream" zstd-decompress-stream) :unsigned-long-long "Decompress the data." (zds :pointer) (output :pointer) (input :pointer)) (declaim (ftype (function () u64) zstd-d-stream-in-size)) (cffi:defcfun ("ZSTD_DStreamInSize" zstd-d-stream-in-size) :unsigned-long-long "Recommended size for decompression input buffer.") (declaim (ftype (function () u64) zstd-d-stream-out-size)) (cffi:defcfun ("ZSTD_DStreamOutSize" zstd-d-stream-out-size) :unsigned-long-long "Recommended size for decompression output buffer.")
3,934
Common Lisp
.lisp
101
36.623762
84
0.732176
glv2/cl-zstd
15
4
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
ee622af5f0c41293610d97b9ce1b274f0df575ecdcbcaa646fcd1545d3863149
9,615
[ -1 ]
9,616
zstd.lisp
glv2_cl-zstd/src/zstd.lisp
;;; This file is part of cl-zstd ;;; Copyright 2020-2022 Guillaume LE VAILLANT ;;; Distributed under the GNU GPL v3 or later. ;;; See the file LICENSE for terms of use and distribution. (in-package :zstd) (deftype u8 () '(unsigned-byte 8)) (defconstant +buffer-size+ 4096) ;;; ;;; Errors ;;; (define-condition zstd-error (simple-error) ()) (defmacro zstd-error (message &rest args) `(error 'zstd-error :format-control ,message :format-arguments (list ,@args))) (defmacro zstd-check (form) (let ((code (gensym))) `(let ((,code ,form)) (declare (type u64 ,code)) (if (= (zstd-is-error ,code) 1) (zstd-error (zstd-get-error-name ,code)) ,code)))) ;;; ;;; Compression Gray streams ;;; (defclass compressing-stream (fundamental-binary-output-stream) ((output-stream :accessor output-stream) (zstd-context :accessor zstd-context) (input-buffer :accessor input-buffer) (zstd-in-buffer :accessor zstd-in-buffer) (output-buffer :accessor output-buffer) (zstd-out-buffer :accessor zstd-out-buffer))) (defmethod stream-element-type ((stream compressing-stream)) '(unsigned-byte 8)) (defun compress-and-write (stream) (with-slots (output-stream zstd-context input-buffer zstd-in-buffer output-buffer zstd-out-buffer) stream (zstd-check (zstd-compress-stream2 zstd-context zstd-out-buffer zstd-in-buffer :zstd-e-continue)) (cffi:with-foreign-slots ((size pos) zstd-in-buffer (:struct zstd-in-buffer)) (when (plusp pos) (replace input-buffer input-buffer :start2 pos :end2 size) (decf size pos) (setf pos 0))) (cffi:with-foreign-slots ((pos) zstd-out-buffer (:struct zstd-out-buffer)) (when (plusp pos) (write-sequence output-buffer output-stream :end pos) (setf pos 0))))) (defmethod stream-write-byte ((stream compressing-stream) byte) (with-slots (input-buffer zstd-in-buffer) stream (cffi:with-foreign-slots ((size pos) zstd-in-buffer (:struct zstd-in-buffer)) (setf (aref input-buffer size) byte) (incf size))) (compress-and-write stream) byte) (defmethod stream-write-sequence ((stream compressing-stream) seq start end &key &allow-other-keys) (with-slots (input-buffer zstd-in-buffer) stream (loop :while (< start end) :do (cffi:with-foreign-slots ((size) zstd-in-buffer (:struct zstd-in-buffer)) (let* ((available-space (- (length input-buffer) size)) (n (min (- end start) available-space))) (replace input-buffer seq :start1 size :start2 start :end2 (+ start n)) (incf size n) (incf start n))) (compress-and-write stream))) seq) (defmethod stream-finish-output ((stream compressing-stream)) (with-slots (output-stream zstd-context zstd-in-buffer output-buffer zstd-out-buffer) stream (do ((frame-complete-p nil)) (frame-complete-p) (setf frame-complete-p (zerop (zstd-check (zstd-compress-stream2 zstd-context zstd-out-buffer zstd-in-buffer :zstd-e-end)))) (cffi:with-foreign-slots ((pos) zstd-out-buffer (:struct zstd-out-buffer)) (when (plusp pos) (write-sequence output-buffer output-stream :end pos) (setf pos 0)))) (cffi:with-foreign-slots ((size pos) zstd-in-buffer (:struct zstd-in-buffer)) (setf pos 0) (setf size 0)) (cffi:with-foreign-slots ((pos) zstd-out-buffer (:struct zstd-out-buffer)) (setf pos 0)) (finish-output output-stream)) nil) (defmethod close ((stream compressing-stream) &key &allow-other-keys) (when (open-stream-p stream) (finish-output stream) (with-slots (zstd-context input-buffer zstd-in-buffer output-buffer zstd-out-buffer) stream (zstd-check (zstd-free-cctx zstd-context)) (setf zstd-context nil) (setf input-buffer nil) (cffi:foreign-free zstd-in-buffer) (setf zstd-in-buffer nil) (setf output-buffer nil) (cffi:foreign-free zstd-out-buffer) (setf zstd-out-buffer nil))) t) (defun initialize-context (context level) "Initialize the CONTEXT for the given compression LEVEL." (zstd-check (zstd-cctx-set-parameter context :zstd-c-compression-level level)) (zstd-check (zstd-cctx-set-parameter context :zstd-c-checksum-flag 1)) context) (defun make-compressing-stream (output-stream &key (level 3)) "Return a stream that will compress the bytes written to it at the given compression LEVEL and write them to the OUTPUT-STREAM." (let ((stream (make-instance 'compressing-stream)) (input-buffer-size (zstd-c-stream-in-size)) (output-buffer-size (zstd-c-stream-out-size)) (min-level (zstd-min-c-level)) (max-level (zstd-max-c-level))) (setf (output-stream stream) output-stream) (with-slots (zstd-context input-buffer zstd-in-buffer output-buffer zstd-out-buffer) stream (if (and (integerp level) (<= min-level level max-level)) (let ((context (zstd-create-cctx))) (if (cffi:null-pointer-p context) (zstd-error "Failed to create compression context.") (setf zstd-context (initialize-context context level)))) (zstd-error "LEVEL must be between ~d and ~d." min-level max-level)) (setf input-buffer (cffi:make-shareable-byte-vector input-buffer-size)) (setf zstd-in-buffer (cffi:foreign-alloc '(:struct zstd-in-buffer))) (cffi:with-pointer-to-vector-data (ffi-input-buffer input-buffer) (cffi:with-foreign-slots ((src size pos) zstd-in-buffer (:struct zstd-in-buffer)) (setf src ffi-input-buffer) (setf size 0) (setf pos 0))) (setf output-buffer (cffi:make-shareable-byte-vector output-buffer-size)) (setf zstd-out-buffer (cffi:foreign-alloc '(:struct zstd-out-buffer))) (cffi:with-pointer-to-vector-data (ffi-output-buffer output-buffer) (cffi:with-foreign-slots ((dst size pos) (zstd-out-buffer stream) (:struct zstd-out-buffer)) (setf dst ffi-output-buffer) (setf size output-buffer-size) (setf pos 0)))) stream)) (defmacro with-compressing-stream ((stream output-stream &key (level 3)) &body body) "Within BODY, STREAM is bound to a compressing stream for the given compression LEVEL and OUTPUT-STREAM. The result of the last form of BODY is returned." `(with-open-stream (,stream (make-compressing-stream ,output-stream :level ,level)) ,@body)) ;;; ;;; Decompression Gray streams ;;; (defclass decompressing-stream (fundamental-binary-input-stream) ((input-stream :accessor input-stream) (zstd-context :accessor zstd-context) (input-buffer :accessor input-buffer) (zstd-in-buffer :accessor zstd-in-buffer) (output-buffer :accessor output-buffer) (zstd-out-buffer :accessor zstd-out-buffer) (frame-complete-p :accessor frame-complete-p))) (defmethod stream-element-type ((stream decompressing-stream)) '(unsigned-byte 8)) (defun read-and-decompress (stream) (with-slots (input-stream zstd-context input-buffer zstd-in-buffer zstd-out-buffer frame-complete-p) stream (let ((end-of-input-p nil)) (cffi:with-foreign-slots ((size) zstd-in-buffer (:struct zstd-in-buffer)) (setf size (read-sequence input-buffer input-stream :start size)) (setf end-of-input-p (zerop size))) (unless end-of-input-p (setf frame-complete-p (zerop (zstd-check (zstd-decompress-stream zstd-context zstd-out-buffer zstd-in-buffer)))) (cffi:with-foreign-slots ((size pos) zstd-in-buffer (:struct zstd-in-buffer)) (when (plusp pos) (replace input-buffer input-buffer :start2 pos :end2 size) (decf size pos) (setf pos 0)))) end-of-input-p))) (defmethod stream-listen ((stream decompressing-stream)) (with-slots (input-stream zstd-in-buffer zstd-out-buffer) stream (or (plusp (cffi:foreign-slot-value zstd-out-buffer '(:struct zstd-out-buffer) 'pos)) (plusp (cffi:foreign-slot-value zstd-in-buffer '(:struct zstd-in-buffer) 'size)) (listen input-stream)))) (defmethod stream-read-byte ((stream decompressing-stream)) (with-slots (output-buffer zstd-out-buffer) stream (let ((end-of-input-p (read-and-decompress stream))) (cffi:with-foreign-slots ((pos) zstd-out-buffer (:struct zstd-out-buffer)) (cond ((plusp pos) (let ((byte (aref output-buffer 0))) (replace output-buffer output-buffer :start2 1 :end2 pos) (decf pos) byte)) ((and end-of-input-p (not (frame-complete-p stream))) (zstd-error "Truncated stream.")) (t :eof)))))) (defmethod stream-read-sequence ((stream decompressing-stream) seq start end &key &allow-other-keys) (with-slots (output-buffer zstd-out-buffer) stream (let ((end-of-input-p nil)) (loop :until (or (= start end) end-of-input-p) :do (setf end-of-input-p (read-and-decompress stream)) (cffi:with-foreign-slots ((pos) zstd-out-buffer (:struct zstd-out-buffer)) (loop :while (and (< start end) (plusp pos)) :do (let ((n (min (- end start) pos))) (replace seq output-buffer :start1 start :end2 n) (replace output-buffer output-buffer :start2 n :end2 pos) (decf pos n) (incf start n))))) (when (and end-of-input-p (not (frame-complete-p stream))) (zstd-error "Truncated stream.")))) start) (defmethod close ((stream decompressing-stream) &key &allow-other-keys) (when (open-stream-p stream) (with-slots (zstd-context input-buffer zstd-in-buffer output-buffer zstd-out-buffer) stream (zstd-check (zstd-free-dctx zstd-context)) (setf zstd-context nil) (setf input-buffer nil) (cffi:foreign-free zstd-in-buffer) (setf zstd-in-buffer nil) (setf output-buffer nil) (cffi:foreign-free zstd-out-buffer) (setf zstd-out-buffer nil))) t) (defun make-decompressing-stream (input-stream) "Return a stream that will supply the bytes resulting from the decompression of the data read from the INPUT-STREAM." (let ((stream (make-instance 'decompressing-stream)) (input-buffer-size (zstd-d-stream-in-size)) (output-buffer-size (zstd-d-stream-out-size))) (setf (input-stream stream) input-stream) (with-slots (zstd-context input-buffer zstd-in-buffer output-buffer zstd-out-buffer frame-complete-p) stream (let ((context (zstd-create-dctx))) (if (cffi:null-pointer-p context) (zstd-error "Failed to create decompression context.") (setf zstd-context context))) (setf input-buffer (cffi:make-shareable-byte-vector input-buffer-size)) (setf zstd-in-buffer (cffi:foreign-alloc '(:struct zstd-in-buffer))) (cffi:with-pointer-to-vector-data (ffi-input-buffer input-buffer) (cffi:with-foreign-slots ((src size pos) zstd-in-buffer (:struct zstd-in-buffer)) (setf src ffi-input-buffer) (setf size 0) (setf pos 0))) (setf output-buffer (cffi:make-shareable-byte-vector output-buffer-size)) (setf zstd-out-buffer (cffi:foreign-alloc '(:struct zstd-out-buffer))) (cffi:with-pointer-to-vector-data (ffi-output-buffer output-buffer) (cffi:with-foreign-slots ((dst size pos) zstd-out-buffer (:struct zstd-out-buffer)) (setf dst ffi-output-buffer) (setf size output-buffer-size) (setf pos 0))) (setf frame-complete-p t)) stream)) (defmacro with-decompressing-stream ((stream input-stream) &body body) "Within BODY, STREAM is bound to a decompressing stream for the given INPUT-STREAM. The result of the last form of BODY is returned." `(with-open-stream (,stream (make-decompressing-stream ,input-stream)) ,@body)) ;;; ;;; Compression functions ;;; (defun compress-stream (input output &key (level 3)) "Read the data from the INPUT octet stream, compress it, and write the result to the OUTPUT octet stream." (with-compressing-stream (stream output :level level) (let ((buffer (make-array +buffer-size+ :element-type 'u8))) (do ((n (read-sequence buffer input) (read-sequence buffer input))) ((zerop n) t) (write-sequence buffer stream :end n))))) (defun compress-file (input output &key (level 3)) "Read the data from the INPUT file, compress it, and write the result to the OUTPUT file." (with-open-file (input-stream input :element-type 'u8) (with-open-file (output-stream output :direction :output :element-type 'u8) (compress-stream input-stream output-stream :level level)))) (defun compress-buffer (buffer &key (start 0) end (level 3)) "Read the data between the START and END offsets in the BUFFER, compress it, and return the resulting octet vector." (let ((end (or end (length buffer)))) (octet-streams:with-octet-output-stream (output) (with-compressing-stream (stream output :level level) (write-sequence buffer stream :start start :end end))))) ;;; ;;; Decompression functions ;;; (defun decompress-stream (input output) "Read the data from the INPUT octet stream, decompress it, and write the result to the OUTPUT octet stream." (with-decompressing-stream (stream input) (let ((buffer (make-array +buffer-size+ :element-type 'u8))) (do ((n (read-sequence buffer stream) (read-sequence buffer stream))) ((zerop n) t) (write-sequence buffer output :end n))))) (defun decompress-file (input output) "Read the data from the INPUT file, decompress it, and write the result to the OUTPUT file." (with-open-file (input-stream input :element-type 'u8) (with-open-file (output-stream output :direction :output :element-type 'u8) (decompress-stream input-stream output-stream)))) (defun decompress-buffer (buffer &key (start 0) end) "Read the data between the START and END offsets in the BUFFER, decompress it, and return the resulting octet vector." (let ((end (or end (length buffer)))) (octet-streams:with-octet-output-stream (output) (octet-streams:with-octet-input-stream (input buffer start end) (decompress-stream input output)))))
15,610
Common Lisp
.lisp
339
36.554572
80
0.621478
glv2/cl-zstd
15
4
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
8b8059755bcb5b8e31ed98ea3329db050ce4c4ae1bfe546028e1531475615105
9,616
[ -1 ]
9,617
tests.lisp
glv2_cl-zstd/tests/tests.lisp
;;; This file is part of cl-zstd ;;; Copyright 2020-2022 Guillaume LE VAILLANT ;;; Distributed under the GNU GPL v3 or later. ;;; See the file LICENSE for terms of use and distribution. (defpackage :zstd-tests (:use :cl :cl-octet-streams :fiveam :zstd)) (in-package :zstd-tests) (defun data-file-path (filename) (let ((path (concatenate 'string "tests/" filename))) (asdf:system-relative-pathname "zstd-tests" path))) (defun load-data-file (filename) (with-open-file (file (data-file-path filename) :element-type '(unsigned-byte 8)) (let* ((size (file-length file)) (buffer (make-array size :element-type '(unsigned-byte 8)))) (read-sequence buffer file) buffer))) (defun same-files-p (path-1 path-2) (with-open-file (file-1 path-1 :element-type '(unsigned-byte 8)) (with-open-file (file-2 path-2 :element-type '(unsigned-byte 8)) (let ((buffer-1 (make-array 16384 :element-type '(unsigned-byte 8))) (buffer-2 (make-array 16384 :element-type '(unsigned-byte 8)))) (loop for read-1 = (read-sequence buffer-1 file-1) for read-2 = (read-sequence buffer-2 file-2) never (or (/= read-1 read-2) (mismatch buffer-1 buffer-2 :end1 read-1 :end2 read-1)) until (zerop read-1)))))) (def-suite zstd-unit-tests :description "Unit tests for Zstandard (de)compression.") (in-suite zstd-unit-tests) (test decompressing-stream (with-octet-input-stream (input #(40 181 47 253 36 5 41 0 0 1 2 3 4 5 47 214 192 132)) (let ((stream (make-decompressing-stream input)) (tmp (make-array 2 :element-type '(unsigned-byte 8)))) (is (= 1 (read-byte stream))) (is (= 2 (read-byte stream))) (is (= 2 (read-sequence tmp stream))) (is (equalp #(3 4) tmp)) (is (= 5 (read-byte stream))) (is (eql :eof (read-byte stream nil :eof))) (close stream)))) (test decompress-stream (is (equalp #() (with-octet-output-stream (output) (with-octet-input-stream (input #(40 181 47 253 36 0 1 0 0 153 233 216 81)) (decompress-stream input output))))) (is (equalp #(1 2 3 4 5) (with-octet-output-stream (output) (with-octet-input-stream (input #(40 181 47 253 36 5 41 0 0 1 2 3 4 5 47 214 192 132)) (decompress-stream input output))))) (let ((tmp (with-octet-output-stream (output) (with-octet-input-stream (input #(40 181 47 253 164 160 134 1 0 85 0 0 16 115 115 1 0 155 134 57 192 2 13 41 68 46)) (decompress-stream input output))))) (is (= 100000 (length tmp))) (is-true (every (lambda (x) (= x 115)) tmp)))) (test decompress-file (let ((decompressed (data-file-path "test1.txt")) (compressed (data-file-path "test1.txt.zst")) (tmp "/tmp/zstd-test1.txt")) (unwind-protect (progn (is-true (decompress-file compressed tmp)) (is (same-files-p decompressed tmp))) (uiop:delete-file-if-exists tmp))) (let ((decompressed (data-file-path "test2.txt")) (compressed (data-file-path "test2.txt.zst")) (tmp "/tmp/zstd-test2.txt")) (unwind-protect (progn (is-true (decompress-file compressed tmp)) (is (same-files-p decompressed tmp))) (uiop:delete-file-if-exists tmp)))) (test decompress-buffer (let ((decompressed (load-data-file "test1.txt")) (compressed (load-data-file "test1.txt.zst"))) (is (equalp decompressed (decompress-buffer compressed)))) (is (equalp #(1 2 3 4 5) (decompress-buffer #(40 181 47 253 36 5 41 0 0 1 2 3 4 5 47 214 192 132))))) (test decompress-corrupt-archive (signals zstd-error (decompress-buffer #(1 1 1 1))) (signals zstd-error (decompress-buffer #(40 181 47 253))) (signals zstd-error (decompress-buffer #(40 181 47 253 36 5 41 0 0 1 2 3)))) (test compressing-stream (let ((compressed (with-octet-output-stream (output) (let ((stream (make-compressing-stream output :level 9))) (write-byte 1 stream) (write-byte 2 stream) (write-sequence #(3 4 1 2 3 4 1 2 3 4) stream) (write-byte 5 stream) (close stream))))) (is (equalp #(1 2 3 4 1 2 3 4 1 2 3 4 5) (decompress-buffer compressed))))) (test compress-stream (is (equalp #() (with-octet-output-stream (output) (with-octet-pipe (pipe) (with-octet-input-stream (input #()) (compress-stream input pipe) (decompress-stream pipe output)))))) (is (equalp #(1 2 3 4 5) (with-octet-output-stream (output) (with-octet-pipe (pipe) (with-octet-input-stream (input #(1 2 3 4 5)) (compress-stream input pipe) (decompress-stream pipe output)))))) (let* ((data (make-array 100000 :element-type '(unsigned-byte 8) :initial-element 115)) (tmp (with-octet-output-stream (output) (with-octet-pipe (pipe) (with-octet-input-stream (input data) (compress-stream input pipe) (decompress-stream pipe output)))))) (is (equalp data tmp)))) (test compress-file (let ((decompressed (data-file-path "test1.txt")) (tmp-1 "/tmp/zstd-test1.txt.lz") (tmp-2 "/tmp/zstd-test1.txt")) (unwind-protect (progn (is-true (compress-file decompressed tmp-1)) (is-true (decompress-file tmp-1 tmp-2)) (is (same-files-p decompressed tmp-2))) (uiop:delete-file-if-exists tmp-1) (uiop:delete-file-if-exists tmp-2))) (let ((decompressed (data-file-path "test2.txt")) (tmp-1 "/tmp/zstd-test2.txt.lz") (tmp-2 "/tmp/zstd-test2.txt")) (unwind-protect (progn (is-true (compress-file decompressed tmp-1)) (is-true (decompress-file tmp-1 tmp-2)) (is (same-files-p decompressed tmp-2))) (uiop:delete-file-if-exists tmp-1) (uiop:delete-file-if-exists tmp-2)))) (test compress-buffer (let* ((decompressed (load-data-file "test1.txt")) (tmp-1 (compress-buffer decompressed)) (tmp-2 (decompress-buffer tmp-1))) (is (< (length tmp-1) (length decompressed))) (is-false (mismatch decompressed tmp-2))) (let* ((decompressed (make-array 123456 :element-type '(unsigned-byte 8) :initial-element 55)) (tmp-1 (compress-buffer decompressed)) (tmp-2 (decompress-buffer tmp-1))) (is (< (length tmp-1) (length decompressed))) (is-false (mismatch decompressed tmp-2)))) (test compress-bad-options (signals zstd-error (compress-buffer #(7 6 6 7 6 6) :level nil)) (signals zstd-error (compress-buffer #(7 6 6 7 6 6) :level 200)))
7,576
Common Lisp
.lisp
161
34.888199
79
0.54902
glv2/cl-zstd
15
4
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
1dc0c0f40d43b6f3fd84d51231b25cf132aa6d1656a6feb86176628c8e536d2d
9,617
[ -1 ]
9,618
zstd.asd
glv2_cl-zstd/zstd.asd
;;; This file is part of cl-zstd ;;; Copyright 2020-2022 Guillaume LE VAILLANT ;;; Distributed under the GNU GPL v3 or later. ;;; See the file LICENSE for terms of use and distribution. (defsystem "zstd" :name "zstd" :description "Zstandard (de)compression using bindings to libzstd" :version "2.0" :author "Guillaume Le Vaillant" :license "GPL-3" :depends-on ("cffi" "cl-octet-streams" "trivial-gray-streams") :in-order-to ((test-op (test-op "zstd-tests"))) :components ((:module "src" :serial t :components ((:file "package") (:file "libzstd") (:file "zstd")))))
672
Common Lisp
.asd
17
32.235294
68
0.610092
glv2/cl-zstd
15
4
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
0ff50c9308266e169d6e23c217109b271c924df4500e557a2bbd71f1763c9cd6
9,618
[ -1 ]
9,619
zstd-tests.asd
glv2_cl-zstd/zstd-tests.asd
;;; This file is part of cl-zstd ;;; Copyright 2020-2022 Guillaume LE VAILLANT ;;; Distributed under the GNU GPL v3 or later. ;;; See the file LICENSE for terms of use and distribution. (defsystem "zstd-tests" :name "zstd-tests" :description "Tests for zstd" :version "2.0" :author "Guillaume Le Vaillant" :license "GPL-3" :depends-on ("cl-octet-streams" "fiveam" "uiop" "zstd") :in-order-to ((test-op (load-op "zstd-tests"))) :perform (test-op (op s) (let ((tests (uiop:find-symbol* 'zstd-unit-tests :zstd-tests))) (uiop:symbol-call :fiveam 'run! tests))) :components ((:module "tests" :serial t :components ((:static-file "test1.txt") (:static-file "test1.txt.zst") (:static-file "test2.txt") (:static-file "test2.txt.zst") (:file "tests")))))
941
Common Lisp
.asd
22
32.909091
76
0.562092
glv2/cl-zstd
15
4
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
1ae9abb1b00cc3275b3ad51f2163499c6b73c90af42f14a0781ec399c3c0249d
9,619
[ -1 ]
9,639
bio-sequence-interval-test.lisp
keithj_cl-genomic/test/bio-sequence-interval-test.lisp
;;; ;;; Copyright (c) 2008-2011 Keith James. All rights reserved. ;;; ;;; 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 :cl-genomic-test) (deftestsuite bio-sequence-interval-tests (cl-genomic-tests) ((ss-seq (make-dna *dna-residues* :num-strands 1)) (ds-seq (make-dna *dna-residues* :num-strands 2)))) (addtest (bio-sequence-interval-tests) interval/1 (let* ((lower 2) (upper 5) (interval (make-instance 'interval :reference ss-seq :lower lower :upper upper))) (ensure (= lower (lower-of interval))) (ensure (= upper (upper-of interval))) (ensure-same ss-seq (reference-of interval)) (ensure-error 'invalid-argument-error (setf (reference-of interval) (make-dna "a"))))) (addtest (bio-sequence-interval-tests) na-sequence-interval/1 (ensure-error 'invalid-argument-error (make-instance 'na-sequence-interval :lower 10 :upper 1)) (ensure-error 'invalid-argument-error (make-instance 'na-sequence-interval :reference (make-dna "acgt" :num-strands 1) :lower 0 :upper 5 :strand *reverse-strand*)) (ensure-error 'invalid-argument-error (make-instance 'na-sequence-interval :lower 0 :upper 5 :strand *forward-strand* :reference (make-dna "acgt" :num-strands 1) :num-strands 2) :report "Made a double-stranded interval with a single-stranded reference.")) (addtest (bio-sequence-interval-tests) na-sequence-interval/2 (let* ((lower 2) (upper 5) (interval1 (make-instance 'na-sequence-interval :reference ss-seq :lower lower :upper upper :num-strands 1)) (interval2 (make-instance 'na-sequence-interval :reference ds-seq :lower lower :upper upper :strand *forward-strand*)) (interval3 (make-instance 'na-sequence-interval :reference ds-seq :lower lower :upper upper :strand *forward-strand* :num-strands 2)) (interval4 (make-instance 'na-sequence-interval :reference ds-seq :lower lower :upper upper :strand *reverse-strand*))) ;; single strand (ensure (= lower (lower-of interval1))) (ensure (= upper (upper-of interval1))) (ensure-same ss-seq (reference-of interval1)) ;; double strand (ensure (= lower (lower-of interval2))) (ensure (= upper (upper-of interval2))) (ensure-same ds-seq (reference-of interval2)) ;; single strand errors (ensure-error 'invalid-argument-error (setf (reference-of interval3) ss-seq)) (ensure-error 'invalid-argument-error (setf (reference-of interval4) ss-seq)) (ensure-error 'invalid-argument-error (setf (num-strands-of interval1) 2)))) (addtest (bio-sequence-interval-tests) na-sequence-interval/3 (ensure (= 5 (length-of (make-instance 'na-sequence-interval :reference ss-seq :lower 0 :upper 5 :num-strands 1))))) (addtest (bio-sequence-interval-tests) na-sequence-interval/4 (ensure (string= "-----" (coerce-sequence (make-instance 'na-sequence-interval :reference nil :lower 0 :upper 5) 'string)))) (addtest (bio-sequence-interval-tests) na-sequence-interval/5 (ensure (string= "tagcr" (coerce-sequence (make-instance 'na-sequence-interval :reference ss-seq :lower 0 :upper 5 :num-strands 1) 'string)))) (addtest (bio-sequence-interval-tests) na-sequence-interval/7 (ensure (string= "tagcr" (coerce-sequence (make-instance 'na-sequence-interval :reference ss-seq :lower 0 :upper 5 :num-strands 1 :strand *forward-strand*) 'string)))) (addtest (bio-sequence-interval-tests) na-sequence-interval/7 (ensure (string= "ygcta" (coerce-sequence (make-instance 'na-sequence-interval :reference ds-seq :lower 0 :upper 5 :strand *reverse-strand*) 'string)))) (let* ((reference1 (make-dna "aagggct")) (reference2 (make-dna "aagggct" :num-strands 2))) (addtest (bio-sequence-interval-tests) na-sequence-interval/8 (let ((interval1 (make-instance 'na-sequence-interval :reference reference1 :lower 1 :upper 6))) ;; interval *unknown-strand* (ensure (string= "aggg" (coerce-sequence (subsequence interval1 0 4) 'string))) (ensure (string= "ggg" (coerce-sequence (subsequence interval1 1 4) 'string))) (ensure (string= "gggc" (coerce-sequence (subsequence interval1 1) 'string))))) (addtest (bio-sequence-interval-tests) na-sequence-interval/9 (let ((interval2 (make-instance 'na-sequence-interval :reference reference1 :lower 1 :upper 6 :strand *forward-strand*))) ;; interval *forward-strand* (ensure (string= "aggg" (coerce-sequence (subsequence interval2 0 4) 'string))) (ensure (string= "ggg" (coerce-sequence (subsequence interval2 1 4) 'string))) (ensure (string= "gggc" (coerce-sequence (subsequence interval2 1) 'string))))) (addtest (bio-sequence-interval-tests) na-sequence-interval/10 (let ((interval3 (make-instance 'na-sequence-interval :reference reference2 :lower 1 :upper 6 :strand *reverse-strand*))) ;; interval *reverse-strand* (ensure (string= "ccct" (coerce-sequence (subsequence interval3 0 4) 'string))) (ensure (string= "ccc" (coerce-sequence (subsequence interval3 1 4) 'string))) (ensure (string= "gccc" (coerce-sequence (subsequence interval3 1) 'string)))))) (addtest (bio-sequence-interval-tests) na-sequence-interval/11 (let ((reference-ss (make-dna "aaacgtttgc" :num-strands 1)) (reference-ds (make-dna "aaacgtttgc" :num-strands 2)) (lower 0) (upper 4) (strand *forward-strand*)) (let* ((interval1 (make-instance 'na-sequence-interval :lower lower :upper upper :strand strand :reference reference-ds)) (interval2 (reverse-complement interval1)) (interval3 (reverse-complement interval2)) (interval4 (make-instance 'na-sequence-interval :lower lower :upper upper :strand strand :num-strands 1 :reference reference-ss))) ;; interval2 is the reverse-complement of interval1 (ensure (eql *reverse-strand* (strand-of interval2))) (ensure (= 6 (lower-of interval2))) (ensure (= 10 (upper-of interval2))) (ensure (string= "gcaa" (coerce-sequence interval2 'string))) ;; interval3 is the reverse-complement of interval2, so should ;; be identical to interval1 (ensure (eql *forward-strand* (strand-of interval3))) (ensure (= 0 (lower-of interval3))) (ensure (= 4 (upper-of interval3))) (ensure (string= "aaac" (coerce-sequence interval3 'string))) (ensure-error 'invalid-argument-error (reverse-complement interval4) :report "Successfully called reverse-complement on an interval with a single-stranded reference.")))) (addtest (bio-sequence-interval-tests) na-sequence-interval/12 (let ((reference-ss (make-dna "aaacgtttgc" :num-strands 1)) (reference-ds (make-dna "aaacgtttgc" :num-strands 2)) (lower 0) (upper 4) (strand *forward-strand*)) (let* ((interval1 (make-instance 'na-sequence-interval :lower lower :upper upper :strand strand :reference reference-ds)) (interval2 (make-instance 'na-sequence-interval :lower lower :upper upper :strand strand :num-strands 1 :reference reference-ss))) (nreverse-complement interval1) (ensure (eql *reverse-strand* (strand-of interval1))) (ensure (= 6 (lower-of interval1))) (ensure (= 10 (upper-of interval1))) (ensure (string= "gcaa" (coerce-sequence interval1 'string))) (nreverse-complement interval1) (ensure (eql *forward-strand* (strand-of interval1))) (ensure (= 0 (lower-of interval1))) (ensure (= 4 (upper-of interval1))) (ensure (string= "aaac" (coerce-sequence interval1 'string))) (ensure-error 'invalid-argument-error (reverse-complement interval2) :report "Successfully called nreverse-complement on an interval with a single-stranded reference.")))) (defun interval-predicates () (list #'beforep #'afterp #'meetsp #'met-by-p #'overlapsp #'startsp #'started-by-p #'duringp #'containsp #'finishesp #'finished-by-p #'interval-equal)) (defun test-intervals (interval1 interval2 expected) (ensure (equal expected (remove-if #'null (mapcar #'(lambda (fn) (when (funcall fn interval1 interval2) fn)) (interval-predicates)))))) (addtest (bio-sequence-interval-tests) beforep/1 (let ((ref (make-dna "acttacggccgt"))) (test-intervals (make-interval ref :lower 0 :upper 4) (make-interval ref :lower 5 :upper 9) (list #'beforep)))) (addtest (bio-sequence-interval-tests) afterp/1 (let ((ref (make-dna "acttacggccgt"))) (test-intervals (make-interval ref :lower 5 :upper 9) (make-interval ref :lower 0 :upper 4) (list #'afterp)))) (addtest (bio-sequence-interval-tests) meetsp/1 (let ((ref (make-dna "acttacggccgt"))) (test-intervals (make-interval ref :lower 0 :upper 4) (make-interval ref :lower 4 :upper 8) (list #'meetsp)))) (addtest (bio-sequence-interval-tests) meetsp/2 (let ((ref (make-dna "acttacggccgt"))) (ensure (not (meetsp (make-interval ref :lower 0 :upper 0) (make-interval ref :lower 0 :upper 0)))) (ensure (not (meetsp (make-interval ref :lower 0 :upper 0) (make-interval ref :lower 0 :upper 1)))))) (addtest (bio-sequence-interval-tests) met-by-p/1 (let ((ref (make-dna "acttacggccgt"))) (test-intervals (make-interval ref :lower 4 :upper 8) (make-interval ref :lower 0 :upper 4) (list #'met-by-p)))) (addtest (bio-sequence-interval-tests) met-by-p/2 (let ((ref (make-dna "acttacggccgt"))) (ensure (not (met-by-p (make-interval ref :lower 0 :upper 0) (make-interval ref :lower 0 :upper 0)))) (ensure (not (met-by-p (make-interval ref :lower 0 :upper 1) (make-interval ref :lower 0 :upper 0)))))) (addtest (bio-sequence-interval-tests) overlapsp/1 (let ((ref (make-dna "acttacggccgt"))) (test-intervals (make-interval ref :lower 0 :upper 6) (make-interval ref :lower 2 :upper 8) (list #'overlapsp)) (test-intervals (make-interval ref :lower 2 :upper 8) (make-interval ref :lower 0 :upper 6) (list #'overlapsp)))) (addtest (bio-sequence-interval-tests) startsp/1 (let ((ref (make-dna "acttacggccgt"))) (test-intervals (make-interval ref :lower 0 :upper 4) (make-interval ref :lower 0 :upper 8) (list #'startsp)))) (addtest (bio-sequence-interval-tests) startsp/2 (let ((ref (make-dna "acttacggccgt"))) (ensure (not (startsp (make-interval ref :lower 0 :upper 0) (make-interval ref :lower 0 :upper 0)))) (ensure (not (startsp (make-interval ref :lower 0 :upper 0) (make-interval ref :lower 0 :upper 1)))))) (addtest (bio-sequence-interval-tests) started-by-p/1 (let ((ref (make-dna "acttacggccgt"))) (test-intervals (make-interval ref :lower 0 :upper 8) (make-interval ref :lower 0 :upper 4) (list #'started-by-p)))) (addtest (bio-sequence-interval-tests) started-by-p/2 (let ((ref (make-dna "acttacggccgt"))) (ensure (not (started-by-p (make-interval ref :lower 0 :upper 0) (make-interval ref :lower 0 :upper 0)))) (ensure (not (started-by-p (make-interval ref :lower 0 :upper 1) (make-interval ref :lower 0 :upper 0)))))) (addtest (bio-sequence-interval-tests) duringp/1 (let ((ref (make-dna "acttacggccgt"))) (test-intervals (make-interval ref :lower 1 :upper 5) (make-interval ref :lower 0 :upper 6) (list #'duringp)))) (addtest (bio-sequence-interval-tests) containsp/1 (let ((ref (make-dna "acttacggccgt"))) (test-intervals (make-interval ref :lower 0 :upper 6) (make-interval ref :lower 1 :upper 5) (list #'containsp)))) (addtest (bio-sequence-interval-tests) finishesp/1 (let ((ref (make-dna "acttacggccgt"))) (test-intervals (make-interval ref :lower 4 :upper 8) (make-interval ref :lower 0 :upper 8) (list #'finishesp)))) (addtest (bio-sequence-interval-tests) finishesp/2 (let ((ref (make-dna "acttacggccgt"))) (ensure (not (finishesp (make-interval ref :lower 0 :upper 0) (make-interval ref :lower 0 :upper 0)))) (ensure (not (finishesp (make-interval ref :lower 1 :upper 1) (make-interval ref :lower 0 :upper 1)))))) (addtest (bio-sequence-interval-tests) finished-by-p/1 (let ((ref (make-dna "acttacggccgt"))) (test-intervals (make-interval ref :lower 0 :upper 8) (make-interval ref :lower 4 :upper 8) (list #'finished-by-p)))) (addtest (bio-sequence-interval-tests) finished-by-p/2 (let ((ref (make-dna "acttacggccgt"))) (ensure (not (finished-by-p (make-interval ref :lower 0 :upper 0) (make-interval ref :lower 0 :upper 0)))) (ensure (not (finished-by-p (make-interval ref :lower 0 :upper 1) (make-interval ref :lower 1 :upper 1)))))) (addtest (bio-sequence-interval-tests) interval-equal/1 (let ((ref (make-dna "acttacggccgt"))) (test-intervals (make-interval ref :lower 0 :upper 4) (make-interval ref :lower 0 :upper 4) (list #'interval-equal)))) (addtest (bio-sequence-interval-tests) inclusive-afterp/1 (let ((ref (make-dna "acttacggccgt"))) (ensure (inclusive-afterp (make-interval ref :lower 4 :upper 8) (make-interval ref :lower 0 :upper 4))) (ensure (inclusive-afterp (make-interval ref :lower 4 :upper 8) (make-interval ref :lower 0 :upper 3))))) (addtest (bio-sequence-interval-tests) inclusive-containsp/1 (let ((ref (make-dna "acttacggccgt"))) (ensure (inclusive-containsp (make-interval ref :lower 0 :upper 8) (make-interval ref :lower 1 :upper 7))) (ensure (inclusive-containsp (make-interval ref :lower 0 :upper 8) (make-interval ref :lower 0 :upper 7))) (ensure (inclusive-containsp (make-interval ref :lower 0 :upper 8) (make-interval ref :lower 1 :upper 8))) (ensure (inclusive-containsp (make-interval ref :lower 0 :upper 8) (make-interval ref :lower 0 :upper 8))))) (addtest (bio-sequence-interval-tests) inclusive-overlapsp/1 (let ((ref (make-dna "acttacggccgt"))) (ensure (inclusive-overlapsp (make-interval ref :lower 0 :upper 8) (make-interval ref :lower 1 :upper 7))) (ensure (inclusive-overlapsp (make-interval ref :lower 0 :upper 8) (make-interval ref :lower 0 :upper 7))) (ensure (inclusive-overlapsp (make-interval ref :lower 0 :upper 8) (make-interval ref :lower 1 :upper 8))) (ensure (inclusive-overlapsp (make-interval ref :lower 0 :upper 8) (make-interval ref :lower 0 :upper 8))) (ensure (inclusive-overlapsp (make-interval ref :lower 0 :upper 6) (make-interval ref :lower 2 :upper 8))) (ensure (inclusive-overlapsp (make-interval ref :lower 2 :upper 8) (make-interval ref :lower 0 :upper 6))) (ensure (inclusive-overlapsp (make-interval ref :lower 1 :upper 7) (make-interval ref :lower 0 :upper 8))) (ensure (inclusive-overlapsp (make-interval ref :lower 0 :upper 7) (make-interval ref :lower 0 :upper 8))) (ensure (inclusive-overlapsp (make-interval ref :lower 1 :upper 8) (make-interval ref :lower 0 :upper 8)))))
20,123
Common Lisp
.lisp
383
36.579634
79
0.532392
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
2446a1f86acfa50fa11356edc71d1b393bc7866a1bd73b80210d96a58cced7db
9,639
[ -1 ]
9,640
cl-genomic-ontology-test.lisp
keithj_cl-genomic/test/cl-genomic-ontology-test.lisp
;;; ;;; Copyright (c) 2010-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :cl-genomic-ontology-test) ;; The base test of all cl-genomic-ontology tests (deftestsuite cl-genomic-ontology-tests () () (:setup (unless (modulep :sofa) (load-ontology (merge-pathnames "ontology/sofa_2_4_2.plm")) (load-ontology (merge-pathnames "ontology/sofa_addenda.plm"))))) (addtest (cl-genomic-ontology-tests) modulep/1 (ensure (modulep "SOFA")) (ensure (modulep :sofa)) (ensure (not (modulep :foo)))) (addtest (cl-genomic-ontology-tests) get-module/1 (ensure (get-module "SOFA")) (ensure (get-module :sofa)))
1,344
Common Lisp
.lisp
32
39.6875
76
0.71789
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
0fcb0c4f881e49e221ae94837e9ece9a83d072d897391d0b88719ec54cc4d16c
9,640
[ -1 ]
9,641
package.lisp
keithj_cl-genomic/test/package.lisp
;;; ;;; Copyright (c) 2007-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :cl-user) (defpackage :cl-genomic-test (:use #:common-lisp #:deoxybyte-utilities #:deoxybyte-io #:bio-sequence #:lift) (:export #:cl-genomic-tests) (:documentation "cl-genomic tests."))
988
Common Lisp
.lisp
24
39.458333
73
0.726327
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
8824d2db2aac0b76397beb8b1458931dfefd6908c2426df0c845179162c526ab
9,641
[ -1 ]
9,642
bio-sequence-alignment-test.lisp
keithj_cl-genomic/test/bio-sequence-alignment-test.lisp
;;; ;;; Copyright (c) 2008-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :cl-genomic-test) (deftestsuite bio-sequence-alignment-tests (cl-genomic-tests) ()) (defparameter *swg-aa-score* #2A((0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0) (0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0) (0.0 0.0 0.0 5.0 0.0 5.0 0.0 0.0 0.0 0.0 0.0) (0.0 0.0 0.0 0.0 2.0 0.0 20.0 0.0 0.0 0.0 0.0) (0.0 10.0 0.0 0.0 0.0 0.0 0.0 18.0 20.0 9.0 8.0) (0.0 0.0 16.0 0.0 0.0 0.0 0.0 7.0 18.0 26.0 16.0) (0.0 0.0 0.0 21.0 6.0 10.0 1.0 9.0 6.0 17.0 25.0) (0.0 0.0 6.0 5.0 18.0 10.0 7.0 6.0 9.0 15.0 23.0))) (defparameter *swg-aa-insertx* #2A((0.0f0 0.0f0 0.0f0 0.0f0 0.0f0 0.0f0 0.0f0 0.0f0 0.0f0 0.0f0 0.0f0) (0.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0) (0.0f0 -10.0f0 -10.0f0 -10.0f0 -5.0f0 -6.0f0 -5.0f0 -6.0f0 -7.0f0 -8.0f0 -9.0f0) (0.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -8.0f0 -9.0f0 10.0f0 9.0f0 8.0f0 7.0f0) (0.0f0 -10.0f0 0.0f0 -1.0f0 -2.0f0 -3.0f0 -4.0f0 0.0f0 8.0f0 10.0f0 9.0f0) (0.0f0 -10.0f0 -10.0f0 6.0f0 5.0f0 4.0f0 3.0f0 2.0f0 1.0f0 8.0f0 16.0f0) (0.0f0 -10.0f0 -10.0f0 -4.0f0 11.0f0 10.0f0 9.0f0 8.0f0 7.0f0 6.0f0 7.0f0) (0.0f0 -10.0f0 -10.0f0 -4.0f0 1.0f0 8.0f0 7.0f0 6.0f0 5.0f0 4.0f0 5.0f0))) (defparameter *swg-aa-inserty* #2A((0.0f0 0.0f0 0.0f0 0.0f0 0.0f0 0.0f0 0.0f0 0.0f0 0.0f0 0.0f0 0.0f0) (0.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0) (0.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0) (0.0f0 -10.0f0 -10.0f0 -5.0f0 -10.0f0 -5.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0 -10.0f0) (0.0f0 -10.0f0 -10.0f0 -6.0f0 -8.0f0 -6.0f0 10.0f0 0.0f0 -1.0f0 -2.0f0 -3.0f0) (0.0f0 0.0f0 -10.0f0 -7.0f0 -9.0f0 -7.0f0 9.0f0 8.0f0 10.0f0 0.0f0 -1.0f0) (0.0f0 -1.0f0 6.0f0 -4.0f0 -5.0f0 -6.0f0 8.0f0 7.0f0 9.0f0 16.0f0 6.0f0) (0.0f0 -2.0f0 5.0f0 11.0f0 1.0f0 0.0f0 7.0f0 6.0f0 8.0f0 15.0f0 15.0f0))) (defparameter *dna-query* (make-dna "GATCGGAAGAGCTCGTATGCCGTCTTCTGCTTG")) (defun swg-aa-test (seqm seqn subst-fn gap-open gap-extend) (let ((vecm (bs::vector-of seqm)) (vecn (bs::vector-of seqn))) (flet ((subn (x y) ; local fn to avoid boxing of returned floats (funcall subst-fn x y))) (let ((m (length vecm)) (n (length vecn))) (bs::with-affine-gap-matrices (score insertx inserty backtrace) ((1+ m) (1+ n)) (bs::define-affine-gap-dp (((row col) (prev-row prev-col) (max-row max-col)) (cell-score max-score) (score insertx inserty backtrace (gap-open gap-extend)) (subn (aref vecm prev-row) (aref vecn prev-col)) ()) ; no cell exclusion form (values score insertx inserty))))))) ; return matrices for checking (addtest (bio-sequence-alignment-tests) smith-waterman-gotoh-aa/1 (let ((seqm (make-aa "PAWHEAE")) (seqn (make-aa "HEAGAWGHEE")) (subst-fn #'blosum-50-subst) (gap-open -10.0f0) (gap-extend -1.0f0)) (multiple-value-bind (score insertx inserty) (swg-aa-test seqm seqn subst-fn gap-open gap-extend) (ensure (equalp *swg-aa-score* score)) (ensure (equalp *swg-aa-insertx* insertx)) (ensure (equalp *swg-aa-inserty* inserty))) (multiple-value-bind (align-score alignment) (align-local seqm seqn subst-fn :gap-open gap-open :gap-extend gap-extend :alignment t) (ensure (= 26.0 align-score)) (let ((intervalm (first (intervals-of alignment))) (intervaln (second (intervals-of alignment)))) ;; Check coordinates of alignment (ensure (= 1 (lower-of intervalm))) (ensure (= 5 (upper-of intervalm))) ; interval like subseq (ensure (= 4 (lower-of intervaln))) (ensure (= 9 (upper-of intervaln))) ; interval like subseq ;; Check sequence and gapping (ensure (= 1 (num-gaps-of (aligned-of intervalm)))) (ensure (= 0 (num-gaps-of (aligned-of intervaln)))) (ensure (string= "AW-HE" (coerce-sequence (aligned-of intervalm) 'string))) (ensure (string= "AWGHE" (coerce-sequence (aligned-of intervaln) 'string))))))) (addtest (bio-sequence-alignment-tests) smith-waterman-gotoh-dna/1 (let ((subst-fn #'iupac-dna-subst) (gap-open -5.0f0) (gap-extend -1.0f0) ;; 1000 Fasta sequences (seqs (with-seq-input (seqi (merge-pathnames "data/alignment_test_db.fasta") :fasta) (loop while (has-more-p seqi) collect (next seqi)))) ;; Scores from aligning with EMBOSS 5.0 water (scores (with-open-file (s (merge-pathnames "data/alignment-test-scores.sexp")) (read s)))) (mapc (lambda (seq score) (multiple-value-bind (s a) (align-local *dna-query* seq subst-fn :gap-open gap-open :gap-extend gap-extend) (declare (ignore a)) (ensure (= score s)))) seqs scores)))
6,259
Common Lisp
.lisp
116
45.344828
95
0.565862
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
4965b6ba38af98611ea4ef04a06beca1d802e12095bbf5507066bc74fd4a1eb7
9,642
[ -1 ]
9,643
fjoin-test.lisp
keithj_cl-genomic/test/fjoin-test.lisp
;;; ;;; Copyright (c) 2009-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :cl-genomic-test) (deftestsuite fjoin-tests (cl-genomic-tests) ()) (defun make-intervals (coord-pairs) (make-array (length coord-pairs) :initial-contents (mapcar (lambda (pair) (make-instance 'interval :lower (first pair) :upper (second pair))) coord-pairs))) (defun test-fjoin-intervals (xspecs yspecs rspecs exclude test) (let ((x (make-intervals xspecs)) (y (make-intervals yspecs)) (expected-result (mapcar #'make-intervals rspecs)) (result ())) (flet ((store-intervals (a b) (push (list a b) result))) (compare-intervals x y exclude test #'store-intervals)) (setf result (reverse result)) (ensure (every (lambda (observed expected) (every #'interval-equal observed expected)) result expected-result) :report "Expected ~a but observed ~a" :arguments (expected-result result)))) ;; TODO -- extend tests to cover all the interval predicates (addtest (fjoin-tests) compare-intervals/1 (let ((in1 '(( 0 9) (10 19) (20 29) (30 39) (40 49))) (in2 '( (10 18) (20 28) (40 48))) (out1 '(((10 19) (10 18)) ((20 29) (20 28)) ((40 49) (40 48)))) (out2 '(((10 18) (10 19)) ((20 28) (20 29)) ((40 48) (40 49))))) (test-fjoin-intervals in1 in2 out1 #'beforep #'inclusive-overlapsp) (test-fjoin-intervals in2 in1 out2 #'beforep #'inclusive-overlapsp))) (addtest (fjoin-tests) compare-intervals/2 (let ((in1 '((0 9) (10 19) (20 29) (30 39) (40 49))) (in2 '((8 18) (48 59))) (out1 '(((0 9) ( 8 18)) (( 8 18) (10 19)) ((40 49) (48 59)))) (out2 '(((0 9) ( 8 18)) (( 8 18) (10 19)) ((40 49) (48 59))))) (test-fjoin-intervals in1 in2 out1 #'beforep #'inclusive-overlapsp) (test-fjoin-intervals in2 in1 out2 #'beforep #'inclusive-overlapsp)))
3,104
Common Lisp
.lisp
70
34.085714
73
0.543263
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
bda686d4858bdbaa6b2764a0e1a69ff645bd90ea5b53949a2fd3687f431816a1
9,643
[ -1 ]
9,644
bio-sequence-io-test.lisp
keithj_cl-genomic/test/bio-sequence-io-test.lisp
;;; ;;; Copyright (c) 2007-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :cl-genomic-test) (defun count-seq-records (filespec format) (with-seq-input (seqi filespec format :alphabet :dna :metric :sanger) (loop for seq = (next seqi) count seq into total while (has-more-p seqi) finally (return total)))) (defmacro with-test-file ((stream filespec) &body body) (with-gensyms (fs) `(let ((,fs (merge-pathnames ,filespec))) (with-seqi (,stream ,fs) ,@body)))) (defmacro with-test-mapped-seq ((mseq seq filespec) &body body) (with-gensyms (tmp-filespec seqi) `(let* ((,seq (with-seq-input (,seqi ,filespec :fasta) (next ,seqi))) (,tmp-filespec (tmp-pathname :tmpdir (merge-pathnames "data")))) (write-pure-sequence ,seq ,tmp-filespec) (with-mapped-dna (,mseq :filespec ,tmp-filespec :length (length-of ,seq)) ,@body) (delete-file ,tmp-filespec)))) (deftestsuite bio-sequence-io-tests (cl-genomic-tests) ()) (addtest (bio-sequence-io-tests) fasta/1 (with-seq-input (seqi (merge-pathnames "data/simple-dna1.fasta") :fasta :alphabet :dna) (let ((seq (next seqi))) (ensure (subtypep (type-of seq) 'dna-sequence)) (ensure (eql (find-alphabet :dna) (alphabet-of seq))) (ensure (not (virtualp seq))) (ensure (= 210 (length-of seq))) (ensure (string= "Test1" (identity-of seq)))))) (addtest (bio-sequence-io-tests) fasta/2 (with-seq-input (seqi (merge-pathnames "data/simple-dna1.fasta") :fasta :alphabet :dna :virtual t) (let ((seq (next seqi))) (ensure (subtypep (type-of seq) 'dna-sequence)) (ensure (eql (find-alphabet :dna) (alphabet-of seq))) (ensure (virtualp seq)) (ensure (= 210 (length-of seq))) (ensure (string= "Test1" (identity-of seq)))))) (addtest (bio-sequence-io-tests) fasta/3 (with-seq-input (seqi (merge-pathnames "data/iupac-dna1.fasta") :fasta :alphabet :dna) (let ((seq (next seqi))) (ensure (subtypep (type-of seq) 'dna-sequence)) (ensure (eql (find-alphabet :dna) (alphabet-of seq))) (ensure (= 210 (length-of seq))) (ensure (string= "Test1" (identity-of seq)))))) (addtest (bio-sequence-io-tests) fasta/4 (with-seq-input (seqi (merge-pathnames "data/simple-dna2.fasta") :fasta :alphabet :dna) (dotimes (n 2) (let ((seq (next seqi))) (ensure (subtypep (type-of seq) 'dna-sequence)) (ensure (eql (find-alphabet :dna) (alphabet-of seq))) (ensure (= 280 (length-of seq))) (ensure (string= (format nil "Test~a" (1+ n)) (identity-of seq))))) (ensure-null (next seqi)))) (addtest (bio-sequence-io-tests) fasta/5 (with-seq-input (seqi (merge-pathnames "data/simple-dna2.fasta") :fasta :alphabet :dna :virtual t) (dotimes (n 2) (let ((seq (next seqi))) (ensure (subtypep (type-of seq) 'dna-sequence)) (ensure (eql (find-alphabet :dna) (alphabet-of seq))) (ensure (virtualp seq)) (ensure (= 280 (length-of seq))) (ensure (string= (format nil "Test~a" (1+ n)) (identity-of seq))))) (ensure-null (next seqi)))) (addtest (bio-sequence-io-tests) fasta/6 (with-seq-input (seqi (merge-pathnames "data/iupac-dna2.fasta") :fasta :alphabet :dna) (dotimes (n 2) (let ((seq (next seqi))) (ensure (subtypep (type-of seq) 'dna-sequence)) (ensure (eql (find-alphabet :dna) (alphabet-of seq))) (ensure (= 280 (length-of seq))) (ensure (string= (format nil "Test~a" (1+ n)) (identity-of seq))))) (ensure-null (next seqi)))) (addtest (bio-sequence-io-tests) fasta/7 (with-seq-input (seqi (merge-pathnames "data/iupac-dna2.fasta") :fasta :alphabet :dna :parser (make-instance 'raw-sequence-parser)) (dotimes (n 2) (let ((seq (next seqi))) (ensure (eql :dna (assocdr :alphabet seq))) (ensure (= 280 (length (assocdr :residues seq)))) (ensure (string= (format nil "Test~a" (1+ n)) (assocdr :identity seq))))) (ensure-null (next seqi)))) (addtest (bio-sequence-io-tests) fasta/8 (with-seq-input (seqi (merge-pathnames "data/phred.fastq") :fasta :alphabet :dna) ; fastq! (ensure-condition malformed-record-error (next seqi)))) (addtest (bio-sequence-io-tests) write-fasta-sequence/1 (let ((seq (make-dna "acgtn" :identity "foo")) (tmp-filespec (tmp-pathname :tmpdir (merge-pathnames "data") :type "fa"))) (dolist (args '((nil "acgtn") (:lower "acgtn") (:upper "ACGTN"))) (with-open-file (stream tmp-filespec :direction :io :element-type 'base-char :external-format :ascii) (write-fasta-sequence seq stream :token-case (first args)) (finish-output stream) (file-position stream 0) (ensure (string= ">foo" (read-line stream))) (ensure (string= (second args) (read-line stream)))) (delete-file tmp-filespec)))) (addtest (bio-sequence-io-tests) fastq/1 (with-seq-input (seqi (merge-pathnames "data/phred.fastq") :fastq :alphabet :dna) (do ((seq (next seqi) (next seqi))) ((null seq) t) (ensure (subtypep (type-of seq) 'dna-quality-sequence)) (ensure (eql (find-alphabet :dna) (alphabet-of seq))) (ensure (= 35 (length-of seq))) (ensure (string= "IL13" (identity-of seq) :start2 0 :end2 4))))) (addtest (bio-sequence-io-tests) fastq/2 (with-seq-input (seqi (merge-pathnames "data/phred.fastq") :fastq :alphabet :dna :parser (make-instance 'raw-sequence-parser)) (do ((seq (next seqi) (next seqi))) ((null seq) t) (ensure (eql :dna (assocdr :alphabet seq))) (ensure (= 35 (length (assocdr :residues seq)))) (ensure (= 35 (length (assocdr :quality seq)))) (ensure (string= "IL13" (assocdr :identity seq) :start2 0 :end2 4))))) (addtest (bio-sequence-io-tests) fastq/3 (with-seq-input (seqi (merge-pathnames "data/simple-dna1.fasta") ; fasta! :fastq :alphabet :dna :metric :sanger) (ensure-condition malformed-record-error (next seqi)))) (addtest (bio-sequence-io-tests) fastq/4 ;; Identifier is an empty string. This is technically legal because ;; the Fastq paper explicitly states that there is no length limit ;; on the title field. The authors probably meant no upper length ;; limit only. (with-seq-input (seqi (merge-pathnames "data/no_identifier.fastq") :fastq :alphabet :dna :metric :sanger) (ensure (string= "" (identity-of (next seqi)))) (let ((seq2 (next seqi))) (ensure (string= "" (identity-of seq2))) ;; Currently we ignore the description for Fastq ;; (ensure (string= "a description" (description-of seq2))) (ensure (null (description-of seq2)))))) (addtest (bio-sequence-io-tests) write-fastq-sequence/1 (let ((seq (make-dna-quality "acgtn" "<<<<<" :identity "foo" :metric :sanger)) (tmp-filespec (tmp-pathname :tmpdir (merge-pathnames "data") :type "fq"))) (dolist (args '((nil "acgtn") (:lower"acgtn") (:upper "ACGTN"))) (with-open-file (stream tmp-filespec :direction :io :element-type 'base-char :external-format :ascii) (write-fastq-sequence seq stream :token-case (first args)) (finish-output stream) (file-position stream 0) (ensure (string= "@foo" (read-line stream))) (ensure (string= (second args) (read-line stream))) (ensure (string= "+" (read-line stream))) (ensure (string= "<<<<<" (read-line stream)))) (delete-file tmp-filespec)))) (addtest (bio-sequence-io-tests) split-sequence-file/1 (let ((filespec (namestring (merge-pathnames "data/split-test-dna1.fasta")))) (split-sequence-file filespec :fasta (pathname-extender filespec :type "fasta" :separator #\.) :chunk-size 2)) (dolist (args '(("data/split-test-dna1.0.fasta" 2) ("data/split-test-dna1.1.fasta" 2) ("data/split-test-dna1.2.fasta" 2) ("data/split-test-dna1.3.fasta" 1))) (let ((chunk (merge-pathnames (first args)))) (ensure (= (second args) (count-seq-records chunk :fasta))) (delete-file chunk)))) (addtest (bio-sequence-io-tests) split-sequence-file/2 (let ((filespec (namestring (merge-pathnames "data/phred.fastq")))) (split-sequence-file filespec :fastq (pathname-extender filespec :type "fastq" :separator #\.) :chunk-size 2)) (dolist (args '(("data/phred.0.fastq" 2) ("data/phred.1.fastq" 2) ("data/phred.2.fastq" 2) ("data/phred.3.fastq" 1))) (let ((chunk (merge-pathnames (first args)))) (ensure (= (second args) (count-seq-records chunk :fastq))) (delete-file chunk)))) (addtest (bio-sequence-io-tests) convert-sequence-file/1 (let ((in-filespec (merge-pathnames "data/phred.fastq")) (out-filespec (namestring (tmp-pathname :tmpdir (merge-pathnames "data") :type "fasta")))) (convert-sequence-file in-filespec :fastq out-filespec :fasta) (with-seq-input (fqi in-filespec :fastq :alphabet :dna :metric :sanger) (with-seq-input (fai out-filespec :fasta :alphabet :dna) (ensure (loop for fq = (next fqi) while fq always (let ((fa (next fai))) (and (string= (identity-of fq) (identity-of fa)) (string= (coerce-sequence fq 'string) (coerce-sequence fa 'string)))))) (ensure-null (next fai)))) (delete-file out-filespec))) (addtest (bio-sequence-io-tests) mapped-dna-sequence/1 (with-test-mapped-seq (mseq seq (merge-pathnames "data/simple-dna1.fasta")) (ensure (dna-sequence-p mseq)) (ensure (double-stranded-p mseq)) (ensure (simplep mseq)) (ensure (not (ambiguousp mseq))) (ensure (= (length-of seq) (length-of mseq))) (dotimes (n (length-of seq)) (setf (residue-of mseq n) #\n) (ensure (char= #\n (residue-of mseq n)))))) (addtest (bio-sequence-io-tests) mapped-dna-sequence/2 (with-test-mapped-seq (mseq seq (merge-pathnames "data/simple-dna1.fasta")) (let ((str (coerce-sequence seq 'string))) ;; no args (ensure (string= str (coerce-sequence mseq 'string))) ;; optional arg start (dotimes (n (length str)) (ensure (string= (subseq str n) (coerce-sequence mseq 'string :start n)))) ;; optional arg start end (dotimes (n (length str)) (ensure (string= (subseq str 0 n) (coerce-sequence mseq 'string :start 0 :end n))))))) (addtest (bio-sequence-io-tests) mapped-dna-sequence/3 (with-test-mapped-seq (mseq seq (merge-pathnames "data/simple-dna1.fasta")) (ensure (string= (coerce-sequence (reverse-sequence seq) 'string) (coerce-sequence (reverse-sequence mseq) 'string))))) (addtest (bio-sequence-io-tests) mapped-dna-sequence/4 (with-test-mapped-seq (mseq seq (merge-pathnames "data/simple-dna1.fasta")) (ensure (string= (coerce-sequence (nreverse-sequence seq) 'string) (coerce-sequence (nreverse-sequence mseq) 'string))))) (addtest (bio-sequence-io-tests) mapped-dna-sequence/5 (with-test-mapped-seq (mseq seq (merge-pathnames "data/simple-dna1.fasta")) (ensure (string= (coerce-sequence (complement-sequence seq) 'string) (coerce-sequence (complement-sequence mseq) 'string))))) (addtest (bio-sequence-io-tests) mapped-dna-sequence/6 (with-test-mapped-seq (mseq seq (merge-pathnames "data/simple-dna1.fasta")) (ensure (string= (coerce-sequence (ncomplement-sequence seq) 'string) (coerce-sequence (ncomplement-sequence mseq) 'string))))) (addtest (bio-sequence-io-tests) mapped-dna-sequence/7 (with-test-mapped-seq (mseq seq (merge-pathnames "data/simple-dna1.fasta")) (ensure (string= (coerce-sequence (reverse-complement seq) 'string) (coerce-sequence (reverse-complement mseq) 'string))))) (addtest (bio-sequence-io-tests) mapped-dna-sequence/8 (with-test-mapped-seq (mseq seq (merge-pathnames "data/simple-dna1.fasta")) (ensure (string= (coerce-sequence (nreverse-complement seq) 'string) (coerce-sequence (nreverse-complement mseq) 'string)))))
14,009
Common Lisp
.lisp
280
40.235714
79
0.595488
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
95641f262eab621565a62406d3993ac4b6dc0814b4bfbe75bb1f0c1ae1a9751f
9,644
[ -1 ]
9,645
bio-sequence-test.lisp
keithj_cl-genomic/test/bio-sequence-test.lisp
;;; ;;; Copyright (c) 2007-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :cl-genomic-test) (deftestsuite bio-sequence-tests (cl-genomic-tests) ()) ;;; Alphabets (addtest (bio-sequence-tests) find-alphabet/1 (ensure-same bs::*dna* (find-alphabet :dna)) (ensure-same bs::*rna* (find-alphabet :rna)) (ensure-error (find-alphabet :foo))) (addtest (bio-sequence-tests) standard-alphabets/1 (mapc (lambda (alphabet tokens) (ensure (= (length tokens) (size-of alphabet))) (ensure (loop for token in tokens always (memberp token alphabet)))) (mapcar #'find-alphabet '(:dna :rna)) (mapcar (lambda (str) (loop for c across str collect c)) (list *dna-residues* *rna-residues*)))) (addtest (bio-sequence-tests) alphabet/1 (let ((name "test name")) (ensure (string= name (name-of (make-instance 'alphabet :name name)))))) (addtest (bio-sequence-tests) alphabet/2 (let ((tokens '(#\a #\b #\c #\d))) (ensure (equal tokens (tokens-of (make-instance 'alphabet :tokens tokens)))))) ;;; Sequence constructors (addtest (bio-sequence-tests) make-dna/1 (let ((seqs (list (make-dna "tagc") ; unambiguous (make-dna "nnnn"))) ; ambiguous (class-names (list 'dna-sequence 'dna-sequence)) (alphabets (list (find-alphabet :dna) (find-alphabet :dna)))) (mapcar (lambda (seq class-name alphabet) (ensure (subtypep (class-name (class-of seq)) class-name)) (ensure-same alphabet (alphabet-of seq))) seqs class-names alphabets)) ;; We now allow empty sequences ;; (ensure-error ;; (make-dna "")) (ensure-error (make-dna "u")) (ensure-error (make-dna '(#\t #\a #\g #\c)))) (addtest (bio-sequence-tests) make-dna/2 (ensure (= 1 (num-strands-of (make-dna "tagc" :num-strands 1)))) (ensure (= 2 (num-strands-of (make-dna "tagc"))))) (addtest (bio-sequence-tests) make-dna/3 (ensure (string= "nnnn" (coerce-sequence (make-dna nil :length 4) 'string)))) (addtest (bio-sequence-tests) make-dna/4 (ensure-error (make-dna "acgt" :encode nil))) ; non-encoded dna not implemented (addtest (bio-sequence-tests) make-rna/1 (let ((seqs (list (make-rna "uagc") ; unambiguous (make-rna "nnnn"))) ; ambiguous (class-names (list 'rna-sequence 'rna-sequence)) (alphabets (list (find-alphabet :rna) (find-alphabet :rna)))) (mapc (lambda (seq class-name alphabet) (ensure (subtypep (class-name (class-of seq)) class-name)) (ensure-same alphabet (alphabet-of seq))) seqs class-names alphabets)) ;; We now allow empty sequences ;; (ensure-error ;; (make-dna "")) (ensure-error (make-rna "t")) (ensure-error (make-rna '(#\u #\a #\g #\c)))) (addtest (bio-sequence-tests) make-rna/2 (ensure (= 1 (num-strands-of (make-rna "uagc" :num-strands 1)))) (ensure (= 2 (num-strands-of (make-rna "uagc"))))) (addtest (bio-sequence-tests) make-rna/3 (ensure (string= "nnnn" (coerce-sequence (make-rna nil :length 4) 'string)))) (addtest (bio-sequence-tests) make-rna/4 (ensure-error (make-rna "acgu" :encode nil))) ; non-encoded rna not implemented (addtest (bio-sequence-tests) make-aa/1 (let ((seqs (list (make-aa "MAD") ; unambiguous (make-aa "MAB"))) ; ambiguous (class-names (list 'aa-sequence 'aa-sequence)) (alphabets (list (find-alphabet :aa) (find-alphabet :aa)))) (mapc (lambda (seq class-name alphabet) (ensure (subtypep (class-name (class-of seq)) class-name)) (ensure-same alphabet (alphabet-of seq))) seqs class-names alphabets)) (ensure-error (make-aa "?"))) (addtest (bio-sequence-tests) make-aa/2 (ensure-error (make-aa "MAD" :num-strands 1))) (addtest (bio-sequence-tests) make-aa/3 (ensure (string= "XXX" (coerce-sequence (make-aa nil :length 3) 'string)))) (addtest (bio-sequence-tests) make-aa/4 (ensure-error (make-aa "MAD" :encode nil))) ; non-encoded aa not implemented (addtest (bio-sequence-tests) phred-quality/1 (let ((pvals '(0.1 0.01 0.001 0.0001 0.00001)) (quals '(10 20 30 40 50))) (loop for pval in pvals for qual in quals do (ensure-same qual (phred-quality pval))))) (addtest (bio-sequence-tests) make-dna-quality/1 (let ((seqs (list (make-dna-quality ; unambiguous "agaatattctgaccccagttactttcaaga" "<<<<<<<<<<<<<<<<<<<<<735513;3<" :metric :sanger) (make-dna-quality ; ambiguous "ntgccaaaaaatagaaaagtcancgatatt" "<<<<<<<<<<<<<<<<<8<<<<<<5<3.5:" :metric :sanger))) (class-names (list 'dna-quality-sequence 'dna-quality-sequence))) (mapcar (lambda (seq class-name) (ensure (subtypep (class-name (class-of seq)) class-name))) seqs class-names)) (ensure-error (make-dna-quality "agaatattctgaccccagttactttcaaga" "<<<<<<<" :metric :sanger)) (ensure-error (make-dna-quality "agaatattctgaccccagttactttcaaga" "<<<<<<<<<<<<<<<<<8<<<<<<5<3.5:" :metric :invalid-metric))) ;;; Utility methods (addtest (bio-sequence-tests) bio-sequence-p/1 (ensure (every #'bio-sequence-p (list (make-dna "acgt") (make-rna "acgu") (make-aa "MAD"))))) (addtest (bio-sequence-tests) na-sequence-p/1 (ensure (na-sequence-p (make-dna "acgt"))) (ensure (na-sequence-p (make-rna "acgu"))) (ensure (not (na-sequence-p (make-aa "MAD"))))) (addtest (bio-sequence-tests) dna-sequence-p/1 (ensure (dna-sequence-p (make-dna "acgt"))) (ensure (not (dna-sequence-p (make-rna "acgu")))) (ensure (not (dna-sequence-p (make-aa "MAD"))))) (addtest (bio-sequence-tests) rna-sequence-p/1 (ensure (not (rna-sequence-p (make-dna "acgt")))) (ensure (rna-sequence-p (make-rna "acgu"))) (ensure (not (rna-sequence-p (make-aa "MAD"))))) (addtest (bio-sequence-tests) aa-sequence-p/1 (ensure (not (aa-sequence-p (make-dna "acgt")))) (ensure (not (aa-sequence-p (make-rna "acgu")))) (ensure (aa-sequence-p (make-aa "MAD")))) (addtest (bio-sequence-tests) same-biotype-p/1 (ensure (apply #'same-biotype-p (mapcar #'make-dna '("acgt" "acgt" "acgt"))))) (addtest (bio-sequence-tests) same-biotype-p/2 (ensure (apply #'same-biotype-p (mapcar #'make-rna '("acgu" "acgu" "acgu"))))) (addtest (bio-sequence-tests) same-biotype-p/3 (ensure (apply #'same-biotype-p (mapcar #'make-aa '("MAD" "MAD" "MAD"))))) (addtest (bio-sequence-tests) same-biotype-p/4 (ensure (not (same-biotype-p (make-dna "acgt") (make-dna "acgt") (make-rna "acgu"))))) (addtest (bio-sequence-tests) same-strand-num-p/1 (ensure (same-strand-num-p (make-dna "acgt" :num-strands 1) (make-dna "acgt" :num-strands 1))) (ensure (same-strand-num-p (make-rna "acgu" :num-strands 1) (make-rna "acgu" :num-strands 1))) (ensure (same-strand-num-p (make-dna "acgt" :num-strands 2) (make-dna "acgt" :num-strands 2))) (ensure (same-strand-num-p (make-rna "acgu" :num-strands 2) (make-rna "acgu" :num-strands 2))) (ensure-error (same-strand-num-p (make-aa "MAD") (make-aa "MAD"))) (ensure (same-strand-num-p (make-dna "acgt" :num-strands 1) (make-rna "acgu" :num-strands 1))) (ensure (same-strand-num-p (make-dna "acgt" :num-strands 2) (make-rna "acgu" :num-strands 2)))) (addtest (bio-sequence-tests) coerce-sequence/1 (let ((dna (make-dna "acgt")) (rna (make-rna "acgu"))) (ensure (rna-sequence-p (coerce-sequence dna 'rna-sequence))) (ensure (dna-sequence-p (coerce-sequence rna 'dna-sequence))) (ensure (string= "acgu" (coerce-sequence (coerce-sequence dna 'rna-sequence) 'string))) (ensure (string= "acgt" (coerce-sequence (coerce-sequence rna 'dna-sequence) 'string))))) (addtest (bio-sequence-tests) coerce-sequence/2 (let ((dna (make-dna nil :length 4)) (rna (make-rna nil :length 4))) (ensure (rna-sequence-p (coerce-sequence dna 'rna-sequence))) (ensure (dna-sequence-p (coerce-sequence rna 'dna-sequence))) (ensure (string= "nnnn" (coerce-sequence (coerce-sequence dna 'rna-sequence) 'string))) (ensure (string= "nnnn" (coerce-sequence (coerce-sequence rna 'dna-sequence) 'string))))) (addtest (bio-sequence-tests) same-strand-num-p/2 (ensure (not (same-strand-num-p (make-dna "acgt" :num-strands 1) (make-dna "acgt" :num-strands 2)))) (ensure (not (same-strand-num-p (make-rna "acgu" :num-strands 1) (make-rna "acgu" :num-strands 2)))) (ensure-error (not (same-strand-num-p (make-dna "acgt" :num-strands 2) (make-aa "MAD"))))) (addtest (bio-sequence-tests) strand-designator-p/1 (ensure (not (strand-designator-p nil))) (ensure (every #'strand-designator-p (list "+" "-" "?" 1 -1 1 #\+ #\- #\? :forward :reverse :unknown)))) (addtest (bio-sequence-tests) forward-strand-p/1 (ensure (equalp '(t nil nil) (mapcar #'forward-strand-p (list *forward-strand* *reverse-strand* *unknown-strand*))))) (addtest (bio-sequence-tests) reverse-strand-p/1 (ensure (equalp '(nil t nil) (mapcar #'reverse-strand-p (list *forward-strand* *reverse-strand* *unknown-strand*))))) (addtest (bio-sequence-tests) unknown-strand-p/1 (ensure (equalp '(nil nil t) (mapcar #'unknown-strand-p (list *forward-strand* *reverse-strand* *unknown-strand*))))) (addtest (bio-sequence-tests) strand=/1 (ensure (strand= *forward-strand* *forward-strand*)) (ensure (strand= *reverse-strand* *reverse-strand*)) (ensure (not (strand= *unknown-strand* *forward-strand*))) (ensure (not (strand= *unknown-strand* *reverse-strand*))) (ensure (not (strand= *unknown-strand* *unknown-strand*))) (ensure (not (strand= *forward-strand* *reverse-strand*)))) (addtest (bio-sequence-tests) strand-equal/1 (ensure (strand-equal *forward-strand* *forward-strand*)) (ensure (strand-equal *reverse-strand* *reverse-strand*)) (ensure (strand-equal *unknown-strand* *forward-strand*)) (ensure (strand-equal *unknown-strand* *reverse-strand*)) (ensure (strand-equal *unknown-strand* *unknown-strand*)) (ensure (not (strand-equal *forward-strand* *reverse-strand*)))) (addtest (bio-sequence-tests) complement-strand/1 (ensure (eql *forward-strand* (complement-strand *reverse-strand*))) (ensure (eql *reverse-strand* (complement-strand *forward-strand*))) (ensure (eql *unknown-strand* (complement-strand *unknown-strand*)))) (addtest (bio-sequence-tests) complementp/1 (ensure (complementp *forward-strand* *reverse-strand*)) (ensure (not (complementp *forward-strand* *forward-strand*))) (ensure (not (complementp *reverse-strand* *reverse-strand*))) (ensure (not (complementp *forward-strand* *unknown-strand*)))) (addtest (bio-sequence-tests) ambiguousp/1 (ensure (ambiguousp (make-dna "acgn"))) (ensure (not (ambiguousp (make-dna "acgt"))))) (addtest (bio-sequence-tests) ambiguousp/2 (ensure (ambiguousp (make-rna "acgn"))) (ensure (not (ambiguousp (make-rna "acgu"))))) (addtest (bio-sequence-tests) ambiguousp/3 (ensure (ambiguousp (make-aa "MAB"))) (ensure (not (ambiguousp (make-aa "MAD"))))) (addtest (bio-sequence-tests) ambiguousp/4 (ensure (ambiguousp (make-dna nil))) (ensure (ambiguousp (make-rna nil))) (ensure (ambiguousp (make-aa nil)))) (addtest (bio-sequence-tests) simplep/1 (ensure (simplep (make-dna "acgt"))) (ensure (not (simplep (make-dna "acgn"))))) (addtest (bio-sequence-tests) simplep/2 (ensure (simplep (make-rna "acgu"))) (ensure (not (simplep (make-rna "acgn"))))) (addtest (bio-sequence-tests) simplep/3 (ensure (simplep (make-aa "MAD"))) (ensure (not (simplep (make-aa "MAB"))))) (addtest (bio-sequence-tests) simplep/4 (ensure (not (simplep (make-dna nil)))) (ensure (not (simplep (make-rna nil)))) (ensure (not (simplep (make-aa nil))))) (addtest (bio-sequence-tests) anonymousp/1 (ensure (anonymousp (make-dna "tagc"))) (ensure (not (anonymousp (make-dna "tagc" :identity "test"))))) (addtest (bio-sequence-tests) single-stranded-p/1 (let ((seq (make-dna "aaaaaaaaaa" :num-strands 1))) (ensure (single-stranded-p seq)))) (addtest (bio-sequence-tests) double-stranded-p/2 (let ((seq (make-dna "aaaaaaaaaa" :num-strands 2))) (ensure (double-stranded-p seq)))) ;;; Sequence accessors (addtest (bio-sequence-tests) bio-sequence/1 (let ((len 10)) (ensure (= len (length-of (make-dna "aaaaaaaaaa")))) (ensure (= len (length-of (make-rna "aaaaaaaaaa")))) (ensure (= len (length-of (make-dna nil :length len)))) (ensure (= len (length-of (make-rna nil :length len)))))) (addtest (bio-sequence-tests) bio-sequence/2 (let* ((residues "aaggccttaaggcctt") (seq (make-dna residues))) (ensure (string= (subseq residues 0 5) ; aaggc (coerce-sequence (subsequence seq 0 5) 'string))) (ensure (string= residues (coerce-sequence (subsequence seq 0) 'string))))) (addtest (bio-sequence-tests) bio-sequence/3 (let ((seq (make-dna "aacccgggt"))) (mapc (lambda (token freq) (ensure (eq (cdr (assoc token (residue-frequencies seq) :test #'char= )) freq))) '(#\a #\c #\g #\t) '(2 3 3 1)))) ;;; Previously we did not allow mutation of the identity (addtest (bio-sequence-tests) bio-sequence/4 (let ((seq (make-dna "aacccgggt"))) (ensure (anonymousp seq)) (setf (identity-of seq) "test") (ensure (string= "test" (identity-of seq))))) (addtest (bio-sequence-tests) na-sequence/1 (let ((ss-seq (make-dna "aaaaaaaaaa" :num-strands 1)) (ds-seq (make-dna "aaaaaaaaaa" :num-strands 2))) (ensure (= 1 (num-strands-of ss-seq))) (ensure (= 2 (num-strands-of ds-seq))))) (addtest (bio-sequence-tests) dna-sequence/1 (let ((residues "tttt") (seq (make-dna "aaaa"))) (dotimes (n (length residues)) (setf (residue-of seq n) (aref residues n)) (ensure (char= (residue-of seq n) (aref residues n)))))) (addtest (bio-sequence-tests) dna-sequence/2 (let* ((residues "acgt") (seq (make-dna residues))) ;; no args (ensure (string= residues (coerce-sequence seq 'string))) ;; optional arg start (dotimes (n (length residues)) (ensure (string= (subseq residues n) (coerce-sequence seq 'string :start n)))) ;; optional arg start end (dotimes (n (length residues)) (ensure (string= (subseq residues 0 n) (coerce-sequence seq 'string :start 0 :end n)))))) (addtest (bio-sequence-tests) dna-sequence/3 (let* ((residues "aaccggtt") (seq (make-dna residues))) (ensure (string= (coerce-sequence (reverse-sequence seq) 'string) (reverse residues))))) (addtest (bio-sequence-tests) dna-sequence/4 (let* ((residues "aaccggtt") (seq (make-dna residues))) (ensure (string= (coerce-sequence (nreverse-sequence seq) 'string) (reverse residues))))) (addtest (bio-sequence-tests) dna-sequence/5 (let ((seq (make-dna *dna-residues*))) (ensure (string= "atcgyrmkswvhdbn-" (coerce-sequence (complement-sequence seq) 'string))))) (addtest (bio-sequence-tests) dna-sequence/6 (let ((seq (make-dna *dna-residues*))) (ensure (string= "atcgyrmkswvhdbn-" (coerce-sequence (ncomplement-sequence seq) 'string))))) (addtest (bio-sequence-tests) dna-sequence/7 (let ((seq (make-dna *dna-residues*))) (ensure (string= "-nbdhvwskmrygcta" (coerce-sequence (reverse-complement seq) 'string))))) (addtest (bio-sequence-tests) dna-sequence/8 (let ((seq (make-dna *dna-residues*))) (ensure (string= "-nbdhvwskmrygcta" (coerce-sequence (nreverse-complement seq) 'string))))) (addtest (bio-sequence-tests) rna-sequence/1 (let ((residues "uuuu") (rna-seq (make-rna "aaaa"))) (dotimes (n (length residues)) (setf (residue-of rna-seq n) (aref residues n)) (ensure (char= (residue-of rna-seq n) (aref residues n)))))) (addtest (bio-sequence-tests) rna-sequence/2 (let* ((residues "acgu") (seq (make-rna residues))) ;; no args (ensure (string= residues (coerce-sequence seq 'string))) ;; optional arg start (dotimes (n 4) (ensure (string= (subseq residues n) (coerce-sequence seq 'string :start n)))) (dotimes (n 4) (ensure (string= (subseq residues 0 n) (coerce-sequence seq 'string :start 0 :end n)))))) (addtest (bio-sequence-tests) rna-sequence/3 (let* ((residues "aaccgguu") (seq (make-rna residues))) (ensure (string= (coerce-sequence (reverse-sequence seq) 'string) (reverse residues))))) (addtest (bio-sequence-tests) rna-sequence/4 (let* ((residues "aaccgguu") (seq (make-rna residues))) (ensure (string= (coerce-sequence (nreverse-sequence seq) 'string) (reverse residues))))) (addtest (bio-sequence-tests) rna-sequence/5 (let ((seq (make-rna *rna-residues*))) (ensure (string= "aucgyrmkswvhdbn-" (coerce-sequence (complement-sequence seq) 'string))))) (addtest (bio-sequence-tests) rna-sequence/6 (let ((seq (make-rna *rna-residues*))) (ensure (string= "aucgyrmkswvhdbn-" (coerce-sequence (ncomplement-sequence seq) 'string))))) (addtest (bio-sequence-tests) rna-sequence/7 (let ((seq (make-rna *rna-residues*))) (ensure (string= "-nbdhvwskmrygcua" (coerce-sequence (reverse-complement seq) 'string))))) (addtest (bio-sequence-tests) rna-sequence/8 (let ((seq (make-rna *rna-residues*))) (ensure (string= "-nbdhvwskmrygcua" (coerce-sequence (nreverse-complement seq) 'string))))) (addtest (bio-sequence-tests) virtual-dna-sequence/1 (let* ((len 10) (seq (make-dna nil :length 10))) (dotimes (n (1- len)) (ensure (char= #\n (residue-of seq n)))) (ensure-error 'invalid-argument-error (residue-of seq -1)) (ensure-error 'invalid-argument-error (residue-of seq 10)))) ;;; Mutation of sequence quality was allowed, so it make sense to ;;; allow mutation of the quality metric, otherwise the former is not ;;; very useful (addtest (bio-sequence-tests) dna-quality-sequence/1 (let* ((residues "agaatattctgaccccagttactttcaaga") (quality "<<<<<<<<<<<<<<<<<<<<<735513;3<") (seq (make-dna-quality residues quality :metric :sanger))) (ensure (eql :sanger (metric-of seq))) (setf (quality-of seq) (encode-quality (decode-quality quality #'decode-phred-quality) #'encode-illumina-quality) (metric-of seq) :illumina) (ensure (eql :illumina (metric-of seq))))) (addtest (bio-sequence-tests) dna-quality-sequence/2 (let* ((residues "agaatattctgaccccagttactttcaaga") (quality "<<<<<<<<<<<<<<<<<<<<<735513;3<") (seq (make-dna-quality residues quality :metric :sanger))) (ensure (eql :sanger (metric-of seq))) (ensure-error (setf (metric-of seq) :invalid-metric)))) (addtest (bio-sequence-tests) dna-quality-sequence/3 (let* ((residues "agaatattctgaccccagttactttcaaga") (quality "<<<<<<<<<<<<<<<<<<<<<735513;3<") (seq (make-dna-quality residues quality :metric :sanger)) (rseq (reverse-sequence seq))) (ensure (string= (coerce-sequence rseq 'string) (reverse residues))) (ensure (string= (reverse quality) (map-into (make-string (length residues)) #'encode-phred-quality (quality-of rseq)))))) (addtest (bio-sequence-tests) dna-quality-sequence/4 (let* ((residues "agaatattctgaccccagttactttcaaga") (quality "<<<<<<<<<<<<<<<<<<<<<735513;3<") (rresidues (reverse residues)) (rquality (reverse quality)) (seq (make-dna-quality residues quality :metric :sanger)) (rseq (nreverse-sequence seq))) (ensure (string= rresidues (coerce-sequence rseq 'string))) (ensure (equalp rquality (map-into (make-string (length residues)) #'encode-phred-quality (quality-of rseq)))))) (addtest (bio-sequence-tests) dna-quality-sequence/5 (let* ((residues "agaatattctgaccccagttactttcaaga") (quality "<<<<<<<<<<<<<<<<<<<<<735513;3<") (seq (make-dna-quality residues quality :metric :sanger))) (ensure (string= "tcttataagactggggtcaatgaaagttct" (coerce-sequence (complement-sequence seq) 'string))) (ensure (string= quality (map-into (make-string (length residues)) #'encode-phred-quality (quality-of seq)))))) (addtest (bio-sequence-tests) dna-quality-sequence/6 (let* ((residues "agaatattctgaccccagttactttcaaga") (quality "<<<<<<<<<<<<<<<<<<<<<735513;3<") (rquality (reverse quality)) (seq (make-dna-quality residues quality :metric :sanger))) (ensure (string= "tcttgaaagtaactggggtcagaatattct" (coerce-sequence (reverse-complement seq) 'string))) (let ((rcquality (quality-of (reverse-complement seq)))) (ensure (string= rquality (map-into (make-string (length residues)) #'encode-phred-quality rcquality)))))) (addtest (bio-sequence-tests) dna-quality-sequence/7 (let* ((residues "agaatattctgaccccagttactttcaaga") (quality "<<<<<<<<<<<<<<<<<<<<<735513;3<") (rquality (reverse quality)) (seq (make-dna-quality residues quality :metric :sanger)) (rseq (nreverse-complement seq))) (ensure (string= "tcttgaaagtaactggggtcagaatattct" (coerce-sequence rseq 'string))) (let ((rcquality (quality-of rseq))) (ensure (string= rquality (map-into (make-string (length residues)) #'encode-phred-quality rcquality)))))) (addtest (bio-sequence-tests) dna-quality-sequence/8 (let* ((residues "agaatattctgaccccagttactttcaaga") (quality "<<<<<<<<<<<<<<<<<<<<<735513;3<") (seq (make-dna-quality residues quality :metric :sanger))) (ensure (string= (subseq residues 0 5) (coerce-sequence (subsequence seq 0 5) 'string))) (loop for q across (quality-of (subsequence seq 0 5)) do (ensure (= 27 q))))) (addtest (bio-sequence-tests) virtual-token-sequence/3 (let ((seq (make-dna nil :length 10))) (ensure (eql (class-of seq) (class-of (reverse-sequence seq)))) (ensure (= 10 (length-of (reverse-sequence seq)))))) (addtest (bio-sequence-tests) virtual-token-sequence/4 (let ((seq (make-dna nil :length 10))) (ensure (eql (class-of seq) (class-of (nreverse-sequence seq)))) (ensure (= 10 (length-of (nreverse-sequence seq)))))) (addtest (bio-sequence-tests) virtual-token-sequence/5 (let ((seq (make-dna nil :length 10))) (ensure (eql (class-of seq) (class-of (complement-sequence seq)))) (ensure (= 10 (length-of (complement-sequence seq)))))) (addtest (bio-sequence-tests) virtual-token-sequence/6 (let ((seq (make-dna nil :length 10))) (ensure (eql (class-of seq) (class-of (ncomplement-sequence seq)))) (ensure (= 10 (length-of (ncomplement-sequence seq)))))) (addtest (bio-sequence-tests) virtual-token-sequence/7 (let ((seq (make-dna nil :length 10))) (ensure (eql (class-of seq) (class-of (reverse-complement seq)))) (ensure (= 10 (length-of (reverse-complement seq)))))) (addtest (bio-sequence-tests) virtual-token-sequence/8 (let ((seq (make-dna nil :length 10))) (ensure (eql (class-of seq) (class-of (nreverse-complement seq)))) (ensure (= 10 (length-of (nreverse-complement seq)))))) (addtest (bio-sequence-tests) virtual-token-sequence/9 (let ((seq (make-dna nil :length 10))) (ensure (= 5 (length-of (subsequence seq 0 5)))) (ensure (= 10 (length-of (subsequence seq 0)))))) (addtest (bio-sequence-tests) search-sequence/1 (let ((seq (make-dna "tacgagtcgttttagcgcgattatataa")) (sub (make-dna "gtttt"))) (ensure (= 8 (search-sequence sub seq))) (ensure (= 9 (search-sequence sub seq :start1 1))) (ensure (= 8 (search-sequence sub seq :start2 1))) (ensure (= 3 (search-sequence sub seq :end1 1))) (ensure-null (search-sequence sub seq :end2 1)))) (addtest (bio-sequence-tests) with-sequence-residues/1 (let* ((residues "tacgagtcgttttagcgcgattatataa") (seq (make-dna residues)) (i 0)) (with-sequence-residues (residue seq) (ensure (char= (char residues i) residue)) (incf i)))) (addtest (bio-sequence-tests) with-sequence-residues/2 (let* ((residues "tacgagtcgttttagcgcgattatataa") (seq (make-dna residues)) (i 1)) (with-sequence-residues (residue seq :start i :end (1- (length residues))) (ensure (char= (char residues i) residue)) (incf i))))
27,274
Common Lisp
.lisp
572
39.16958
79
0.603706
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e8dbb8c66213851b5c903afabf42e565da3a77f218bdfab9ab3681b5f608d33f
9,645
[ -1 ]
9,646
hamming-test.lisp
keithj_cl-genomic/test/hamming-test.lisp
;;; ;;; Copyright (c) 2010-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :cl-genomic-test) (deftestsuite hamming-tests (cl-genomic-tests) ()) (defun hamming-search-test (seq1 seq2 position distance &rest args) (multiple-value-bind (pos dist) (apply #'hamming-search seq1 seq2 args) (ensure (eql position pos)) (ensure (eql distance dist)))) (addtest (hamming-tests) hamming-distance/1 (ensure (= 0 (hamming-distance (make-dna "a") (make-dna "a")))) (ensure (= 1 (hamming-distance (make-dna "a") (make-dna "t")))) (ensure (= 0 (hamming-distance (make-dna "acgt") (make-dna "acgt")))) ;; Hamming distance does not use base ambiguities (ensure (= 1 (hamming-distance (make-dna "acgt") (make-dna "ncgt")))) (ensure (= 2 (hamming-distance (make-dna "acgt") (make-dna "nngt")))) (ensure (= 3 (hamming-distance (make-dna "acgt") (make-dna "nnnt")))) (ensure (= 4 (hamming-distance (make-dna "acgt") (make-dna "nnnn")))) (ensure (= 0 (hamming-distance (make-dna "acgt") (make-dna "acgtt")))) (ensure (= 0 (hamming-distance (make-dna "acgtt") (make-dna "acgt")))) (ensure (= 3 (hamming-distance (make-dna "aacgt") (make-dna "acgt")))) (ensure (= 3 (hamming-distance (make-dna "acgt") (make-dna "aacgt"))))) (addtest (hamming-tests) hamming-distance/2 (ensure (= 0 (hamming-distance (make-dna "aacgt") (make-dna "acgt") :start1 1))) (ensure (= 0 (hamming-distance (make-dna "acgt") (make-dna "nacgt") :start2 1))) (ensure (= 0 (hamming-distance (make-dna "acgtn") (make-dna "acgtt") :end1 3))) (ensure (= 0 (hamming-distance (make-dna "acgtt") (make-dna "acgtn") :end2 3))) (ensure (= 0 (hamming-distance (make-dna "aattgg") (make-dna "ggttcc") :start1 2 :end1 4 :start2 2 :end2 4)))) (addtest (hamming-tests) hamming-distance/3 (ensure-error (hamming-distance (make-dna "") (make-dna "")))) (addtest (hamming-tests) hamming-search/1 (hamming-search-test (make-dna "acgt") (make-dna "acgt") 0 0) (hamming-search-test (make-dna "acgt") (make-dna "acgtnnnn") 0 0) (hamming-search-test (make-dna "acgt") (make-dna "nacgtnnn") 1 0) (hamming-search-test (make-dna "acgt") (make-dna "nnacgtnn") 2 0) (hamming-search-test (make-dna "acgt") (make-dna "nnnacgtn") 3 0) (hamming-search-test (make-dna "acgt") (make-dna "nnnnacgt") 4 0)) (addtest (hamming-tests) hamming-search/2 ;; max-distance defaults to 1 (hamming-search-test (make-dna "ayyt") (make-dna "acgtnnnn") nil nil) (hamming-search-test (make-dna "ayyt") (make-dna "nacgtnnn") nil nil) (hamming-search-test (make-dna "ayyt") (make-dna "nnacgtnn") nil nil) (hamming-search-test (make-dna "ayyt") (make-dna "nnnacgtn") nil nil) (hamming-search-test (make-dna "ayyt") (make-dna "nnnnacgt") nil nil)) (addtest (hamming-tests) hamming-search/3 (hamming-search-test (make-dna "ayyt") (make-dna "acgtnnnn") 0 2 :max-distance 2) (hamming-search-test (make-dna "ayyt") (make-dna "nacgtnnn") 1 2 :max-distance 2) (hamming-search-test (make-dna "ayyt") (make-dna "nnacgtnn") 2 2 :max-distance 2) (hamming-search-test (make-dna "ayyt") (make-dna "nnnacgtn") 3 2 :max-distance 2) (hamming-search-test (make-dna "ayyt") (make-dna "nnnnacgt") 4 2 :max-distance 2)) (addtest (hamming-tests) hamming-search/4 (hamming-search-test (make-dna "acgtnnnn") (make-dna "acgt") nil nil) (hamming-search-test (make-dna "acgtnnnn") (make-dna "acgt") 0 0 :end1 4) (hamming-search-test (make-dna "nnnnacgtnnnn") (make-dna "acgt") 0 0 :start1 4 :end1 8) (hamming-search-test (make-dna "nnnnacgtnnnn") (make-dna "yyyyacgt") 4 0 :start1 4 :end1 8 :start2 4) (hamming-search-test (make-dna "nnnnacgtnnnn") (make-dna "yyyyacgt") nil nil :start1 4 :end1 8 :start2 5) (hamming-search-test (make-dna "nnnnacgtnnnn") (make-dna "yyyyacgtr") 5 4 :start1 4 :end1 8 :start2 5 :max-distance 4))
4,927
Common Lisp
.lisp
90
48.044444
78
0.631633
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
b8e085c18a824d0a1d4b846e5fb227fd2a3a556613a7d289dc007ab39fc8b673
9,646
[ -1 ]
9,647
bio-sequence-encoding-test.lisp
keithj_cl-genomic/test/bio-sequence-encoding-test.lisp
;;; ;;; Copyright (c) 2008-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :cl-genomic-test) (deftestsuite bio-sequence-encoding-tests (cl-genomic-tests) ((dna-complement"atcgyrmkswvhdbn-") (rna-complement"aucgyrmkswvhdbn-") (dna-unambiguous "tagc") (dna-ambiguous "rykmswbdhvn") (dna-enum (pairlis '(#\t #\a #\g #\c #\r #\y #\k #\m #\s #\w #\b #\d #\h #\v #\n) '((#\t) (#\a) (#\g) (#\c) (#\a #\g) (#\c #\t) (#\g #\t) (#\a #\c) (#\c #\g) (#\a #\t) (#\c #\g #\t) (#\a #\g #\t) (#\a #\c #\t) (#\a #\c #\g) (#\a #\c #\g #\t)))))) ;;; Complementing nucleic acids (addtest (bio-sequence-encoding-tests) complement-dna/1 (loop for res across *dna-residues* for cmp across dna-complement do (ensure (char= (bs::complement-dna res) cmp)))) (addtest (bio-sequence-encoding-tests) complement-dna/2 (loop for res across *dna-residues* for cmp across dna-complement do (ensure (char= (bs::complement-dna (char-upcase res)) cmp)))) (addtest (bio-sequence-encoding-tests) complement-rna/1 (loop for res across *rna-residues* for cmp across rna-complement do (ensure (char= (bs::complement-rna res) cmp)))) (addtest (bio-sequence-encoding-tests) complement-rna/2 (loop for res across *rna-residues* for cmp across rna-complement do (ensure (char= (bs::complement-rna (char-upcase res)) cmp)))) (addtest (bio-sequence-encoding-tests) complement-dna-4bit/1 (loop for res across *dna-residues* for cmp across dna-complement do (progn (ensure (char= (decode-dna-4bit (bs::complement-dna-4bit (encode-dna-4bit res))) cmp))))) ;;; Encoding/decoding sequences (addtest (bio-sequence-encoding-tests) encode/decode-dna-4bit/1 (loop for res across *dna-residues* do (ensure (char= res (decode-dna-4bit (encode-dna-4bit res)))))) (addtest (bio-sequence-encoding-tests) encode/decode-rna-4bit/1 (loop for res across *rna-residues* do (ensure (char= res (decode-rna-4bit (encode-rna-4bit res)))))) (addtest (bio-sequence-encoding-tests) enum-ambiguity/1 (loop for res across *dna-residues* do (ensure (equal (assocdr res dna-enum :test #'char=) (enum-ambiguity res (find-alphabet :dna))))))
3,195
Common Lisp
.lisp
76
35.486842
74
0.620778
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
8c3c5aefb80151f9aa9cb76a162e756fc385b3ac555633a58ead52343457ff0c
9,647
[ -1 ]
9,648
bio-sequence-translation-test.lisp
keithj_cl-genomic/test/bio-sequence-translation-test.lisp
;;; ;;; Copyright (c) 2008-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :cl-genomic-test) (deftestsuite bio-sequence-translation-tests (cl-genomic-tests) ()) (defparameter *test-codons* '((#\a #\a #\a) (#\a #\a #\c) (#\a #\a #\g) (#\a #\a #\t) (#\a #\a #\r) (#\a #\a #\y) (#\a #\c #\a) (#\a #\c #\c) (#\a #\c #\g) (#\a #\c #\t) (#\a #\c #\r) (#\a #\c #\y) (#\a #\c #\k) (#\a #\c #\m) (#\a #\c #\s) (#\a #\c #\w) (#\a #\c #\b) (#\a #\c #\d) (#\a #\c #\h) (#\a #\c #\v) (#\a #\c #\n) (#\a #\g #\a) (#\a #\g #\c) (#\a #\g #\g) (#\a #\g #\t) (#\a #\g #\r) (#\a #\g #\y) (#\a #\t #\a) (#\a #\t #\c) (#\a #\t #\g) (#\a #\t #\t) (#\a #\t #\y) (#\a #\t #\m) (#\a #\t #\w) (#\a #\t #\h) (#\c #\a #\a) (#\c #\a #\c) (#\c #\a #\g) (#\c #\a #\t) (#\c #\a #\r) (#\c #\a #\y) (#\c #\c #\a) (#\c #\c #\c) (#\c #\c #\g) (#\c #\c #\t) (#\c #\c #\r) (#\c #\c #\y) (#\c #\c #\k) (#\c #\c #\m) (#\c #\c #\s) (#\c #\c #\w) (#\c #\c #\b) (#\c #\c #\d) (#\c #\c #\h) (#\c #\c #\v) (#\c #\c #\n) (#\c #\g #\a) (#\c #\g #\c) (#\c #\g #\g) (#\c #\g #\t) (#\c #\g #\r) (#\c #\g #\y) (#\c #\g #\k) (#\c #\g #\m) (#\c #\g #\s) (#\c #\g #\w) (#\c #\g #\b) (#\c #\g #\d) (#\c #\g #\h) (#\c #\g #\v) (#\c #\g #\n) (#\c #\t #\a) (#\c #\t #\c) (#\c #\t #\g) (#\c #\t #\t) (#\c #\t #\r) (#\c #\t #\y) (#\c #\t #\k) (#\c #\t #\m) (#\c #\t #\s) (#\c #\t #\w) (#\c #\t #\b) (#\c #\t #\d) (#\c #\t #\h) (#\c #\t #\v) (#\c #\t #\n) (#\g #\a #\a) (#\g #\a #\c) (#\g #\a #\g) (#\g #\a #\t) (#\g #\a #\r) (#\g #\a #\y) (#\g #\c #\a) (#\g #\c #\c) (#\g #\c #\g) (#\g #\c #\t) (#\g #\c #\r) (#\g #\c #\y) (#\g #\c #\k) (#\g #\c #\m) (#\g #\c #\s) (#\g #\c #\w) (#\g #\c #\b) (#\g #\c #\d) (#\g #\c #\h) (#\g #\c #\v) (#\g #\c #\n) (#\g #\g #\a) (#\g #\g #\c) (#\g #\g #\g) (#\g #\g #\t) (#\g #\g #\r) (#\g #\g #\y) (#\g #\g #\k) (#\g #\g #\m) (#\g #\g #\s) (#\g #\g #\w) (#\g #\g #\b) (#\g #\g #\d) (#\g #\g #\h) (#\g #\g #\v) (#\g #\g #\n) (#\g #\t #\a) (#\g #\t #\c) (#\g #\t #\g) (#\g #\t #\t) (#\g #\t #\r) (#\g #\t #\y) (#\g #\t #\k) (#\g #\t #\m) (#\g #\t #\s) (#\g #\t #\w) (#\g #\t #\b) (#\g #\t #\d) (#\g #\t #\h) (#\g #\t #\v) (#\g #\t #\n) (#\t #\a #\a) (#\t #\a #\c) (#\t #\a #\g) (#\t #\a #\t) (#\t #\a #\r) (#\t #\a #\y) (#\t #\c #\a) (#\t #\c #\c) (#\t #\c #\g) (#\t #\c #\t) (#\t #\c #\r) (#\t #\c #\y) (#\t #\c #\k) (#\t #\c #\m) (#\t #\c #\s) (#\t #\c #\w) (#\t #\c #\b) (#\t #\c #\d) (#\t #\c #\h) (#\t #\c #\v) (#\t #\c #\n) (#\t #\g #\a) (#\t #\g #\c) (#\t #\g #\g) (#\t #\g #\t) (#\t #\g #\y) (#\t #\t #\a) (#\t #\t #\c) (#\t #\t #\g) (#\t #\t #\t) (#\t #\t #\r) (#\t #\t #\y) (#\t #\r #\a) (#\r #\a #\c) (#\r #\a #\t) (#\r #\a #\y) (#\y #\t #\a) (#\y #\t #\g) (#\y #\t #\r) (#\m #\g #\a) (#\m #\g #\g) (#\m #\g #\r) (#\s #\a #\a) (#\s #\a #\g) (#\s #\a #\r)) "Codons that do not encode for X.") (defparameter *test-amino-acids* "KNKNKNTTTTTTTTTTTTTTTRSRSRSIIMIIIIIQHQHQHPPPPPPPPPPPPPPPRRRRRRRRRRRRRRRLLLLLLLLLLLLLLLEDEDEDAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGVVVVVVVVVVVVVVV*Y*Y*YSSSSSSSSSSSSSSS*CWCCLFLFLF*ZZZLLLRRRBBB" "Corresponding translations of codons that do not encode for X.") (addtest (bio-sequence-translation-tests) registered-genetic-codes/1 (let ((codes (registered-genetic-codes))) (ensure (listp codes)) (mapc (lambda (code) (ensure (subtypep (class-name (class-of code)) 'genetic-code))) codes))) (addtest (bio-sequence-translation-tests) find-genetic-code/1 (mapc (lambda (name) (ensure (find-genetic-code name))) (mapcar #'name-of (registered-genetic-codes)))) (addtest (bio-sequence-translation-tests) find-genetic-code/2 (ensure-condition invalid-argument-error (find-genetic-code :no-such-genetic-code)) (ensure-condition invalid-argument-error (find-genetic-code nil)) (ensure-condition invalid-argument-error (find-genetic-code "standard"))) (addtest (bio-sequence-translation-tests) translate-codon-standard/1 (ensure (every #'char= *test-amino-acids* (loop with code = (find-genetic-code :standard) for codon in *test-codons* collect (decode-aa-7bit (translate-codon (mapcar #'encode-dna-4bit codon) code :initiator nil))))) (ensure (every (lambda (char) (or (char= #\X char) (find char *test-amino-acids* :test #'char=))) (loop with code = (find-genetic-code :standard) for codon in (bs::permutations-of-n '(#\a #\c #\g #\t #\r #\y #\k #\m #\s #\w #\b #\d #\h #\v #\n) 3) collect (decode-aa-7bit (translate-codon (mapcar #'encode-dna-4bit codon) code :initiator nil))))))
5,783
Common Lisp
.lisp
101
49.326733
186
0.427212
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
f310ee1545e046f3ac587e3002617e35968f005d5ffd95bbf132bcbb0ebf48db
9,648
[ -1 ]
9,649
cl-genomic-test.lisp
keithj_cl-genomic/test/cl-genomic-test.lisp
;;; ;;; Copyright (c) 2008-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :cl-genomic-test) ;; The base test suite of all cl-genomic tests (deftestsuite cl-genomic-tests () ()) (defparameter *dna-residues* "tagcrykmswbdhvn-") (defparameter *rna-residues* "uagcrykmswbdhvn-")
991
Common Lisp
.lisp
24
40.083333
73
0.741701
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
8485ee7716fa9bff27da4196ba7bae3b458a9726f3108fc4aa55fdd4caf28761
9,649
[ -1 ]
9,650
cl-genomic-ontology-test.lisp
keithj_cl-genomic/test/ontology/cl-genomic-ontology-test.lisp
;;; ;;; Copyright (c) 2010-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :cl-genomic-ontology-test) ;; The base test of all cl-genomic-ontology tests (deftestsuite cl-genomic-ontology-tests () () (:setup (unless (modulep :sequence-ontology) (load-ontology (merge-pathnames "ontology/so_2_4_3.plm")) (load-ontology (merge-pathnames "ontology/so_addenda.plm"))))) (in-syntax *powerloom-readtable*) (addtest (cl-genomic-ontology-tests) modulep/1 (ensure (modulep "SEQUENCE-ONTOLOGY")) (ensure (modulep :sequence-ontology)) (ensure (not (modulep :foo)))) (addtest (cl-genomic-ontology-tests) get-module/1 (ensure (get-module "SEQUENCE-ONTOLOGY")) (ensure (get-module :sequence-ontology))) (addtest (cl-genomic-ontology-tests) with-module/1 (ensure (equal pli:null *current-module*)) (with-module (:sequence-ontology) (ensure (equal *current-module* (get-module :sequence-ontology)))) (ensure (equal pli:null *current-module*))) (addtest (cl-genomic-ontology-tests) ampersand-reader/1 (with-module (:sequence-ontology) (ensure (is-logic-object @SO:0000110)))) (addtest (cl-genomic-ontology-tests) term-name/1 (with-module (:sequence-ontology) (ensure (equal "sequence_feature" (object-to-string (term-name @SO:0000110)))))) (addtest (cl-genomic-ontology-tests) term-doc/1 (with-module (:sequence-ontology) (ensure (is-string (term-doc @SO:0000110))))) (addtest (cl-genomic-ontology-tests) find-term/1 (with-module (:sequence-ontology) (ensure (equal @SO:0000110 (find-term "sequence_feature"))))) (addtest (cl-genomic-ontology-tests) find-doc/1 (with-module (:sequence-ontology) (ensure (is-string (find-doc "sequence_feature"))) (ensure (equal (term-doc @SO:0000110) (find-doc "sequence_feature"))))) (addtest (cl-genomic-ontology-tests) term-parents/1 (with-module (:sequence-ontology) ;; gene (SO:0000704) has parents gene_group (via part_of) and ;; biological_region, region and sequence_feature (via is_a) (ensure (dxu:linear-set-equal (list @SO:0005855 @SO:0001411 @SO:0000001 @SO:0000110) (term-parents @SO:0000704) :test #'equal :key #'get-name)))) (addtest (cl-genomic-ontology-tests) term-parent-p/1 (with-module (:sequence-ontology) ;; gene (SO:0000704) has parents gene_group (via part_of) and ;; biological_region, region and sequence_feature (via is_a) (dolist (term (list @SO:0005855 @SO:0001411 @SO:0000001 @SO:0000110)) (ensure (term-parent-p term @SO:0000704)))))
3,257
Common Lisp
.lisp
67
45.104478
84
0.711992
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
fc2667ae1b744b26358b11196d13a075ddc6e9df1d232a63b4d219fddbfa352e
9,650
[ -1 ]
9,651
package.lisp
keithj_cl-genomic/test/ontology/package.lisp
;;; ;;; Copyright (c) 2010-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :cl-user) (defpackage :cl-genomic-ontology-test (:use #:common-lisp #:bio-sequence #:bio-ontology #:lift) (:export #:cl-genomic-ontology-tests) (:documentation "cl-genomic-ontology tests."))
984
Common Lisp
.lisp
23
41.434783
73
0.734098
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
58019971c415b6e4bb347959a5c3cc72204d3f5d1f9d9d427fbd47c81050189e
9,651
[ -1 ]
9,652
bio-alphabets.lisp
keithj_cl-genomic/src/bio-alphabets.lisp
;;; ;;; Copyright (c) 2008-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :bio-sequence) ;;; FIXME -- use this struct to wrap characters in alphabets so that ;;; metadata can be attached ;;; (defstruct token ;;; (name "" :type string) ;;; (description "" :type string) ;;; (token #\n :type base-char)) (defconstant +gap-char+ #\- "The gap character.") (defconstant +encoded-gap-char+ #b0000 "The encoded gap character in all encoded alphabets.") (defconstant +codon-size+ 3 "The number of bases in a codon.") (defvar *alphabets* (make-hash-table) "The standard biological alphabets.") (defclass alphabet () ((name :initarg :name :reader name-of :documentation "The alphabet name.") (tokens :initform "" :initarg :tokens :reader tokens-of :documentation "The set of member tokens of the alphabet.") (index :initarg :index :reader index-of :documentation "An index of the tokens in the alphabet. The keys are the encoded tokens, the values are their position in the alphabet's token list.")) (:documentation "Alphabets are sets of tokens.")) (defun make-alphabet (name tokens encoder) "Returns a new simple alphabet where the tokens are atomic. Use this function for creating alphabets such as DNA and RNA. Use {defun make-nth-order-alphabet} to create alphabets of compound tokens, such as the codon alphabet. Arguments: - name (symbol): The alphabet symbolic name. - tokens (list atoms): The alphabet tokens. - encoder (function): A function that accepts a single alphabet token and returns its encoded value. Returns: - An {defclass alphabet} ." (make-instance 'alphabet :name name :tokens tokens :index (loop with index = (make-hash-table) for i from 0 below (length tokens) do (setf (gethash (funcall encoder (elt tokens i)) index) i) finally (return index)))) (defun permutations-of-n (elements &optional (n 1)) "Returns a list of permutations of N ELEMENTS." (let ((m (1- n))) (if (zerop m) (mapcar #'list elements) (let ((perms ())) (dolist (e elements) (dolist (p (permutations-of-n elements m)) (push (cons e p) perms))) (nreverse perms))))) (defun make-nth-order-alphabet (name alphabet n encoder) "Returns a new alphabet where the tokens are lists of tokens from a simple alphabet. Use this function for creating alphabets of compound tokens, such as the codon alphabet. Arguments: - name (symbol): The alphabet symbolic name. - alphabet ( {defclass alphabet} ): The alphabet whose tokens will be grouped to form the tokens of the new alphabet. - n (integer): The number of tokens of the simple alphabet that combine to form a token of the new alphabet. - encoder (function): A function that accepts a single simple alphabet token and returns its encoded value. Returns: - An {defclass alphabet} ." (let ((tokens (permutations-of-n (tokens-of alphabet) n))) (make-instance 'alphabet :name name :tokens tokens :index (loop with index = (make-hash-table :test #'equal) for i from 0 below (length tokens) do (setf (gethash (mapcar encoder (elt tokens i)) index) i) finally (return index))))) (defun register-alphabet (alphabet) "Registers a global standard ALPHABET." (setf (gethash (name-of alphabet) *alphabets*) alphabet)) (defun find-alphabet (name) "Returns a standard ALPHABET designated by a symbol NAME, such as :dna :rna or :aa." (multiple-value-bind (alphabet presentp) (gethash name *alphabets*) (check-arguments presentp (name) "no such alphabet. Expected one of ~a" (mapcar #'name-of (registered-alphabets))) alphabet)) (defun registered-alphabets () "Returns a list of all registered alphabets." (loop for alphabet being the hash-values of *alphabets* collect alphabet into alphabets finally (return (sort alphabets #'string<= :key (lambda (alpha) (symbol-name (name-of alpha))))))) (defvar *simple-dna* (let ((tokens '(#\a #\c #\g #\t))) (make-alphabet :simple-dna tokens #'encode-dna-4bit)) "The simple DNA alphabet.") (defvar *simple-rna* (let ((tokens '(#\a #\c #\g #\u))) (make-alphabet :simple-rna tokens #'encode-rna-4bit)) "The simple RNA alphabet.") (defvar *dna* (let ((tokens `(#\a #\c #\g #\t #\r #\y #\k #\m #\s #\w #\b #\d #\h #\v #\n ,+gap-char+))) (make-alphabet :dna tokens #'encode-dna-4bit)) "The IUPAC DNA alphabet.") (defvar *rna* (let ((tokens `(#\a #\c #\g #\u #\r #\y #\k #\m #\s #\w #\b #\d #\h #\v #\n ,+gap-char+))) (make-alphabet :rna tokens #'encode-rna-4bit)) "The IUPAC RNA alphabet.") (defvar *aa* (let ((tokens `(#\A #\B #\C #\D #\E #\F #\G #\H #\I #\J #\K #\L #\M #\N #\O #\P #\Q #\R #\S #\T #\U #\V #\W #\X #\Y #\Z #\* ,+gap-char+))) (make-alphabet :aa tokens #'encode-aa-7bit)) "The amino acid alphabet.") (defvar *dna-codons* (make-nth-order-alphabet :dna-codons *simple-dna* 3 #'encode-dna-4bit) "The alphabet of 64 standard codons.") (defvar *rna-codons* (make-nth-order-alphabet :rna-codons *simple-rna* 3 #'encode-rna-4bit) "The alphabet of 64 standard codons.") (defmethod size-of ((alphabet alphabet)) (length (slot-value alphabet 'tokens))) (defmethod token-index (encoded-token (alphabet alphabet)) (gethash encoded-token (slot-value alphabet 'index))) (defmethod random-token-of ((alphabet alphabet)) ;; TODO -- inefficient (with-slots (tokens) alphabet (elt tokens (random (length tokens))))) (defmethod memberp ((token character) (alphabet alphabet)) (find token (slot-value alphabet 'tokens))) (defmethod memberp ((codon list) (alphabet alphabet)) (find codon (slot-value alphabet 'tokens) :test #'equalp)) (defmethod subsumesp ((token1 character) (token2 character) (alphabet alphabet)) (subsetp (enum-ambiguity token1 alphabet) (enum-ambiguity token2 alphabet))) (defmethod subsumesp ((codon1 list) (codon2 list) (alphabet alphabet)) (subsetp (enum-ambiguity codon1 alphabet) (enum-ambiguity codon2 alphabet) :test #'equalp)) (defmethod enum-ambiguity (token (alphabet alphabet)) (error 'invalid-argument-error :params '(token alphabet) :args (list token alphabet) :text "the token is invalid for this alphabet")) (defmethod enum-ambiguity ((token character) (alphabet (eql *simple-dna*))) (list token)) (defmethod enum-ambiguity ((token character) (alphabet (eql *simple-rna*))) (list token)) (defmethod enum-ambiguity ((token character) (alphabet (eql *dna*))) (enum-dna-base token)) (defmethod enum-ambiguity ((token character) (alphabet (eql *rna*))) (enum-rna-base token)) (defmethod enum-ambiguity ((token character) (alphabet (eql *aa*))) (enum-aa token)) (defmethod enum-ambiguity ((codon list) (alphabet (eql *dna-codons*))) (enum-dna-codon codon)) (defmethod enum-ambiguity ((codon list) (alphabet (eql *rna-codons*))) (enum-rna-codon codon)) (register-alphabet *simple-dna*) (register-alphabet *simple-rna*) (register-alphabet *dna*) (register-alphabet *rna*) (register-alphabet *aa*) (register-alphabet *dna-codons*) (register-alphabet *rna-codons*)
8,424
Common Lisp
.lisp
197
36.822335
80
0.651802
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
ca9cfd1d0bd0c6a4e6de79aa68829a9cc8d316251f85ebad3f39150746c385c4
9,652
[ -1 ]
9,653
bio-sequence-collection.lisp
keithj_cl-genomic/src/bio-sequence-collection.lisp
;;; ;;; Copyright (c) 2009-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :bio-sequence) ;; Need to group sequences that are related in some way: ;; From same organism ;; From same sequencing experiment (may be multiple organisms) ;; From same bioinformatic experiment ;; Other ;; Use cases: ;; ;; A GFF3 file ;; A genome sequence ;; A lane of short-read sequencing data ;; Just throwing around some ideas here; this code is not for use ;; get sequence by key (id?) ;; get sequence by predicate (similar to Lisp find fn) - in fact, a ;; find-type fn covers finding by key and other attributes. ;; Also implement ;; (size-of coll) ;; (memberp seq coll :test #'test) ;; (defgeneric find-sequence (seq collection &key key)) (defgeneric add-sequence (seq collection &key key)) (defgeneric remove-sequence (seq collection &key key)) (defclass bio-sequence-collection () ((sequences :initform nil :initarg :sequences :reader sequences-of) (alphabet :initarg :alphabet :reader alphabet-of))) (defclass bio-sequence-vector (bio-sequence-collection) ((sequences :initform (make-array 1024 :adjustable t :fill-pointer 0)))) (defclass bio-sequence-table (bio-sequence-collection) ((sequences :initform (make-hash-table :test #'equal)))) (defmethod find-sequence (seq (collection bio-sequence-vector) &key key) (with-slots (sequences test) collection (find seq sequences :key key :test #'equal))) (defmethod find-sequence (seq (collection bio-sequence-table) &key key) (with-slots (sequences) collection (gethash (funcall-if-fn key seq) collection))) (defun index-sequence-file (filespec format alphabet) (let ((index (merge-pathnames (make-pathname :type "index") filespec)) (data (merge-pathnames (make-pathname :type "data") filespec))) (with-open-file (data-stream data :direction :output :if-exists :supersede :element-type 'base-char :external-format :ascii) (with-open-file (index-stream index :direction :output :if-exists :supersede :element-type 'base-char :external-format :ascii) (let ((parser (make-instance 'indexing-sequence-parser :stream data-stream))) (with-seq-input (seqi input-stream format :alphabet alphabet :parser parser) (loop for seq = (next seqi) while (has-more-p seqi) finally (prin1 (index-of parser) index-stream)))))))) (defun index-sequence-file2 (filespec format alphabet) (let ((index (make-instance 'tc:tc-hdb)) (index-file (merge-pathnames (make-pathname :type "index") filespec)) (data (merge-pathnames (make-pathname :type "data") filespec))) (tc:dbm-open index (namestring index-file) :write :create) (tc:dbm-optimize index :leaf 512 :non-leaf 256 :bucket-size 100000000 :rec-align 4 :free-pool 10 :opts '(:large)) (tc::dbm-xmsize index 536870912) (unwind-protect (with-open-file (data-stream data :direction :output :if-exists :supersede :element-type 'base-char :external-format :ascii) (let ((parser (make-instance 'indexing-sequence-parser :stream data-stream))) (with-seq-input (seqi input-stream format :alphabet alphabet :parser parser) (loop for seq = (next seqi) for i = 0 then (1+ i) with time = (get-universal-time) with total-time = 0 while (has-more-p seqi) do (progn (tc:dbm-put index (identity-of seq) (princ-to-string i)) (when (zerop (rem i 100000)) (let* ((now (get-universal-time)) (interval (- now time))) (setf time now) (incf total-time interval) (format t "~d records in ~d seconds, total ~d seconds~%" i interval total-time))))))))) (tc:dbm-close index))) (defun index-sequence-file3 (filespec format alphabet) (let ((index (merge-pathnames (make-pathname :type "index") filespec)) (data (merge-pathnames (make-pathname :type "data") filespec))) (with-open-file (data-stream data :direction :output :if-exists :supersede :element-type 'base-char :external-format :ascii) (with-open-file (index-stream index :direction :output :if-exists :supersede :element-type 'base-char :external-format :ascii) (let ((parser (make-instance 'indexing-sequence-parser :stream data-stream))) (with-seq-input (seqi input-stream format :alphabet alphabet :parser parser) (loop for rlen = (- (offset-of parser) (parsed-length-of parser)) for seq = (next seqi) while (has-more-p seqi) do (prog1 (princ (identity-of seq) index-stream) (write-char #\Tab index-stream) (princ rlen index-stream) (terpri index-stream))))))))) (defun lookup-sequence (identity filespec) (let ((index (with-open-file (s (merge-pathnames (make-pathname :type "index") filespec)) (read s))) (data (merge-pathnames (make-pathname :type "data") filespec))) (let ((entry (binary-search index identity :test #'string< :key #'first))) (dxn:with-mapped-vector (vector 'dxn:mapped-vector-char :filespec data :length (reduce #'+ index :key #'third)) (loop for i from (second entry) below (+ (second entry) (third entry)) collect (code-char (dxn:mref vector i)) into bases finally (return (values identity bases)))))))
7,416
Common Lisp
.lisp
150
35.86
83
0.559299
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
58aa1a842ad4c769dce5b4643546189fdd6ce6eea2850e1e74ab9aca520d5e95
9,653
[ -1 ]
9,654
package.lisp
keithj_cl-genomic/src/package.lisp
;;; ;;; Copyright (c) 2007-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :cl-user) (defpackage :bio-sequence (:use #:common-lisp #:deoxybyte-utilities #:deoxybyte-io) (:nicknames #:bs) (:export ;; Types #:quality-score ;; Specials #:*sequence-print-limit* #:*forward-strand* #:*reverse-strand* #:*unknown-strand* #:*default-knowledgebase* ;; Conditions #:bio-sequence-error #:bio-sequence-warning #:bio-sequence-op-error #:initiator-codon-error ;; Macros #:with-seq-input #:with-seq-output #:with-mapped-dna #:with-sequence-residues ;; Functions #:make-dna #:make-rna #:make-dna-quality #:make-aa #:bio-sequence-p #:na-sequence-p #:dna-sequence-p #:rna-sequence-p #:aa-sequence-p #:same-biotype-p #:same-strand-num-p #:concat-sequence #:complement-dna #:complement-rna #:find-alphabet #:register-alphabet #:registered-alphabets #:find-genetic-code #:registered-genetic-codes #:phred-quality #:illumina-quality #:illumina-to-phred-quality #:symbolize-dna-base #:symbolize-rna-base #:symbolize-aa #:encode-dna-symbol #:encode-rna-symbol #:encode-aa-symbol #:encode-dna-4bit #:decode-dna-4bit #:encode-rna-4bit #:decode-rna-4bit #:encode-aa-7bit #:decode-aa-7bit #:encode-quality #:decode-quality #:encode-phred-quality #:decode-phred-quality #:encode-illumina-quality #:decode-illumina-quality #:skip-malformed-sequence #:simple-dna-subst #:iupac-dna-subst #:blosum-50-subst #:write-n-fastq #:split-fastq-file #:convert-obo-powerloom ;; Classes #:alphabet #:genetic-code #:sequence-strand #:bio-sequence #:na-sequence #:dna-sequence #:rna-sequence #:aa-sequence #:dna-quality-sequence #:mapped-dna-sequence #:interval #:bio-sequence-interval #:na-sequence-interval #:na-alignment-interval #:alignment #:bio-sequence-parser #:raw-sequence-parser #:simple-sequence-parser #:quality-sequence-parser #:virtual-sequence-parser ;; Generic functions #:anonymousp #:identity-of #:description-of #:name-of #:symbol-of #:token-of #:random-token-of #:number-of #:ambiguousp #:simplep #:virtualp #:strand-designator-p #:forward-strand-p #:reverse-strand-p #:unknown-strand-p #:decode-strand #:strand= #:strand-equal #:complement-strand #:complementp #:num-strands-of #:single-stranded-p #:double-stranded-p #:num-gaps-of #:size-of #:memberp #:subsumesp #:tokens-of #:enum-ambiguity #:translate-codon #:start-codon-p #:term-codon-p #:encoded-index-of #:decoded-index-of #:alphabet-of #:element-of #:residue-of #:residues-of #:length-of #:metric-of #:quality-of #:upper-of #:lower-of #:strand-of #:reference-of #:subsequence #:reverse-sequence #:nreverse-sequence #:complement-sequence #:ncomplement-sequence #:reverse-complement #:nreverse-complement #:search-sequence #:residue-frequencies #:translate #:make-interval #:beforep #:afterp #:meetsp #:met-by-p #:overlapsp #:startsp #:started-by-p #:duringp #:containsp #:finishesp #:finished-by-p #:interval-equal #:inclusive-beforep #:inclusive-afterp #:inclusive-containsp #:inclusive-duringp #:inclusive-overlapsp #:compare-intervals #:coerce-sequence #:residue-position #:quality-position #:seguid #:md5 #:aligned-of #:intervals-of #:aligned-length-of #:align-local #:align-local-ksh #:hamming-distance #:hamming-search #:make-seq-input #:make-seq-output #:begin-object #:object-alphabet #:object-relation #:object-identity #:object-description #:object-residues #:object-quality #:end-object #:read-raw-sequence #:write-raw-sequence #:read-pure-sequence #:write-pure-sequence #:read-fasta-sequence #:write-fasta-sequence #:read-fastq-sequence #:write-fastq-sequence #:split-sequence-file #:convert-sequence-file #:parsed-alphabet #:parsed-identity #:parsed-description #:parsed-residues #:parsed-metric #:parsed-quality #:parsed-length #:parsed-raw) (:documentation "The BIO-SEQUENCE package provides basic support for representing biological sequences. Concepts such as alphabets of sequence residues (nucleic acid bases and amino acids), sequences of residues (nucleic acids and polypeptides) and sequence strands are represented as CLOS classes. An event-based parsing interface enables reading of some common, simple biological sequence file formats into primitive Lisp data structures or CLOS instances.")) (defpackage :bio-sequence-user (:use #:common-lisp #:bio-sequence #:deoxybyte-utilities #:deoxybyte-io) (:nicknames #:bsu))
5,642
Common Lisp
.lisp
237
20.037975
73
0.69507
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
762a13de5d22fcf9f91684f3fa3c49a0affe13e79552a5bc15010b441f57970c
9,654
[ -1 ]
9,655
genetic-codes.lisp
keithj_cl-genomic/src/genetic-codes.lisp
;;; ;;; Copyright (c) 2008-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :bio-sequence) (eval-when (:compile-toplevel :load-toplevel :execute) (defvar *codons* '((#\t #\t #\t) (#\t #\t #\c) (#\t #\t #\a) (#\t #\t #\g) (#\t #\c #\t) (#\t #\c #\c) (#\t #\c #\a) (#\t #\c #\g) (#\t #\a #\t) (#\t #\a #\c) (#\t #\a #\a) (#\t #\a #\g) (#\t #\g #\t) (#\t #\g #\c) (#\t #\g #\a) (#\t #\g #\g) (#\c #\t #\t) (#\c #\t #\c) (#\c #\t #\a) (#\c #\t #\g) (#\c #\c #\t) (#\c #\c #\c) (#\c #\c #\a) (#\c #\c #\g) (#\c #\a #\t) (#\c #\a #\c) (#\c #\a #\a) (#\c #\a #\g) (#\c #\g #\t) (#\c #\g #\c) (#\c #\g #\a) (#\c #\g #\g) (#\a #\t #\t) (#\a #\t #\c) (#\a #\t #\a) (#\a #\t #\g) (#\a #\c #\t) (#\a #\c #\c) (#\a #\c #\a) (#\a #\c #\g) (#\a #\a #\t) (#\a #\a #\c) (#\a #\a #\a) (#\a #\a #\g) (#\a #\g #\t) (#\a #\g #\c) (#\a #\g #\a) (#\a #\g #\g) (#\g #\t #\t) (#\g #\t #\c) (#\g #\t #\a) (#\g #\t #\g) (#\g #\c #\t) (#\g #\c #\c) (#\g #\c #\a) (#\g #\c #\g) (#\g #\a #\t) (#\g #\a #\c) (#\g #\a #\a) (#\g #\a #\g) (#\g #\g #\t) (#\g #\g #\c) (#\g #\g #\a) (#\g #\g #\g)) "The codons, ordered for making genetic codes.")) (defvar *genetic-codes* (make-hash-table) "The standard genetic codes.") (defmacro define-genetic-code (symbol &key name full-name id amino-acids starts (aa-encoder #'encode-aa-7bit) (na-encoder #'encode-dna-4bit)) "Defines a new genetic code and registers it. Arguments: - symbol (symbol): A symbol used to name a dynamic variable to which the new genetic code object is bound. Key: - name (symbol): The genetic code name, e.g. :standard - full-name (string): The genetic code full name e.g. \"Standard\" - id (integer): The genetic code number. - amino-acids (string): A 64 element string of amino acid tokens. - starts (string): A 64 element string of amino acid tokens indicating potential start codons. - aa-encoder (function): A function used to encode the amino acid tokens. - na-encoder (function): A function used to encode the codon tokens." (let ((t1 (make-hash-table :test #'equal)) (t2 (make-hash-table :test #'equal)) (t3 (make-hash-table :test #'equal)) (asp-asn (mapcar #'encode-aa-7bit '(#\D #\N))) ; D and N -> B (glu-gln (mapcar #'encode-aa-7bit '(#\E #\Q)))) ; E and Q -> Z (mapc (lambda (codon aa start) (let ((encoded-codon (mapcar na-encoder codon)) (encoded-aa (funcall aa-encoder aa))) (setf (gethash encoded-codon t1) encoded-aa) (when (char= #\M start) (setf (gethash encoded-codon t2) t)) (when (char= #\* aa) (setf (gethash encoded-codon t3) t)))) *codons* (coerce amino-acids 'list) (coerce starts 'list)) (with-gensyms (trans-table start-table term-table) `(progn (defvar ,symbol (make-instance 'genetic-code :name ,name :full-name ,full-name :identity ,id)) (register-genetic-code ,symbol) (let ((,trans-table ,t1) (,start-table ,t2) (,term-table ,t3)) (defmethod translate-codon (codon (code (eql ,symbol)) &key initiator) (flet ((trn (c) (gethash c ,trans-table))) (let ((encoded-aa (delete-duplicates (mapcar #'trn (enum-encoded-codon codon))))) (cond ((= 1 (list-length encoded-aa)) (cond ((and initiator (gethash codon ,start-table)) (encode-aa-7bit #\M)) (initiator (error 'initiator-codon-error :codon (mapcar #'decode-rna-4bit codon) :genetic-code code)) (t (first encoded-aa)))) ((= 2 (list-length encoded-aa)) (cond ((null (set-difference ',glu-gln encoded-aa)) (encode-aa-7bit #\B)) ; D and N -> B ((null (set-difference ',asp-asn encoded-aa)) (encode-aa-7bit #\Z)) ; E and Q -> Z (t (encode-aa-7bit #\X)))) (t (encode-aa-7bit #\X)))))) (defmethod start-codon-p (codon (code (eql ,symbol))) (gethash codon ,start-table)) (defmethod term-codon-p (codon (code (eql ,symbol))) (gethash codon ,term-table))))))) (defun register-genetic-code (genetic-code) "Registers a global standard GENETIC-CODE." (setf (gethash (name-of genetic-code) *genetic-codes*) genetic-code)) (defun find-genetic-code (name) "Returns a standard GENETIC-CODE designated by its name symbol NAME, such as :standard, :vert-mito or :bacterial." (multiple-value-bind (genetic-code presentp) (gethash name *genetic-codes*) (check-arguments presentp (name) "no such genetic code") genetic-code)) (defun registered-genetic-codes () "Returns a list of all registered genetic codes." (loop for code being the hash-values of *genetic-codes* collect code into codes finally (return (sort codes #'< :key #'identity-of)))) (defclass genetic-code (identity-mixin) ((name :initform nil :initarg :name :reader name-of :documentation "The genetic code symbolic name.") (full-name :initform nil :initarg :full-name :reader full-name-of :documentation "The genetic code full name.")) (:documentation "A genetic code translating codons to amino acids.")) (defmethod print-object ((code genetic-code) stream) (print-unreadable-object (code stream :type t :identity t) (with-slots (identity name) code (format stream "~a ~a" identity name)))) (define-genetic-code *standard* :name :standard :id 1 :full-name "Standard" :amino-acids "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG" :starts "---M---------------M---------------M----------------------------") (define-genetic-code *vert-mito* :name :vert-mito :id 2 :full-name "Vertebrate Mitochondrial" :amino-acids "FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNKKSS**VVVVAAAADDEEGGGG" :starts "--------------------------------MMMM---------------M------------") (define-genetic-code *yeast-mito* :name :yeast-mito :id 3 :full-name "Yeast Mitochondrial" :amino-acids "FFLLSSSSYY**CCWWTTTTPPPPHHQQRRRRIIMMTTTTNNKKSSRRVVVVAAAADDEEGGGG" :starts "----------------------------------MM----------------------------") (define-genetic-code *mold-mito* :name :mold-mito :id 4 :full-name "Mold Mitochondrial; Protozoan Mitochondrial; Coelenterate Mitochondrial; Mycoplasma; Spiroplasma" :amino-acids "FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG" :starts "--MM---------------M------------MMMM---------------M------------") (define-genetic-code *invert-mito* :name :invert-mito :id 5 :full-name "Invertebrate Mitochondrial" :amino-acids "FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNKKSSSSVVVVAAAADDEEGGGG" :starts "---M----------------------------MMMM---------------M------------") (define-genetic-code *ciliate-nuclear* :name :ciliate-nuclear :id 6 :full-name "Ciliate Nuclear; Dasycladacean Nuclear; Hexamita Nuclear" :amino-acids "FFLLSSSSYYQQCC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG" :starts "-----------------------------------M----------------------------") ;;; No genetic codes 7 and 8 (define-genetic-code *echino-mito* :name :echino-mito :id 9 :full-name "Echinoderm Mitochondrial; Flatworm Mitochondrial" :amino-acids "FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIIMTTTTNNNKSSSSVVVVAAAADDEEGGGG" :starts "-----------------------------------M---------------M------------") (define-genetic-code *euplotid-nuc* :name :euplotid-nuc :id 10 :full-name "Euplotid Nuclear" :amino-acids "FFLLSSSSYY**CCCWLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG" :starts "-----------------------------------M----------------------------") (define-genetic-code *bacterial* :name :bacterial :id 11 :full-name "Bacterial and Plant Plastid" :amino-acids "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG" :starts "---M---------------M------------MMMM---------------M------------") (define-genetic-code *alt-yeast-nuc* :name :alt-yeast-nuc :id 12 :full-name "Alternative Yeast Nuclear" :amino-acids "FFLLSSSSYY**CC*WLLLSPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG" :starts "-------------------M---------------M----------------------------") (define-genetic-code *ascidian-nuc* :name :alt-ascidian-nuc :id 13 :full-name "Ascidian Mitochondrial" :amino-acids "FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNKKSSGGVVVVAAAADDEEGGGG" :starts "---M------------------------------MM---------------M------------") (define-genetic-code *alt-flatworm-nuc* :name :alt-flatworm-nuc :id 14 :full-name "Alternative Flatworm Mitochondrial" :amino-acids "FFLLSSSSYYY*CCWWLLLLPPPPHHQQRRRRIIIMTTTTNNNKSSSSVVVVAAAADDEEGGGG" :starts "-----------------------------------M----------------------------") (define-genetic-code *blepharisma-macronuc* :name :blepharisma-macronuc :id 15 :full-name "Blepharisma Macronuclear" :amino-acids "FFLLSSSSYY*QCC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG" :starts "-----------------------------------M----------------------------") (define-genetic-code *chlorophycean-mito* :name :chlorophycean-mito :id 16 :full-name "Chlorophycean Mitochondrial" :amino-acids "FFLLSSSSYY*LCC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG" :starts "-----------------------------------M----------------------------") ;;; No genetic codes 17, 18, 19 and 20 (define-genetic-code *trematode-mito* :name :trematode-mito :id 21 :full-name "Trematode Mitochondrial" :amino-acids "FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNNKSSSSVVVVAAAADDEEGGGG" :starts "-----------------------------------M---------------M------------") (define-genetic-code *scenedesmus-mito* :name :scenedesmus-mito :id 22 :full-name "Scenedesmus obliquus Mitochondrial" :amino-acids "FFLLSS*SYY*LCC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG" :starts "-----------------------------------M----------------------------") (define-genetic-code *thraustochytrium-mito* :name :thraustochytrium-mito :id 23 :full-name "Thraustochytrium Mitochondrial" :amino-acids "FF*LSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG" :starts "--------------------------------M--M---------------M------------")
11,897
Common Lisp
.lisp
259
38.235521
113
0.551697
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
a4dae889ec32fff33b21cd81aff9f618acff4316aca6f18b476595539e4eef52
9,655
[ -1 ]
9,656
bio-sequence-interval.lisp
keithj_cl-genomic/src/bio-sequence-interval.lisp
;;; ;;; Copyright (c) 2008-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :bio-sequence) ;;; For practicality we allow the reference to be null so that we can ;;; have unattached intervals. An alternative is to use proxies, which ;;; may not be practical when there are millions of intervals and ;;; millions of references. (defclass interval () ((reference :initform nil :initarg :reference :accessor reference-of :documentation "A reference sequence within which the interval lies.") (lower :type fixnum :initform 0 :initarg :lower :reader lower-of :documentation "The lower bound of the interval. If a reference is defined, this must be within the bounds of the reference sequence.") (upper :type fixnum :initform 0 :initarg :upper :reader upper-of :documentation "The upper bound of the interval.")) (:documentation "An interval within a reference sequence. If a reference is defined, this must be within the bounds of the reference sequence. The basic interval has no notion of sequence strandedness; the bounds always refer to the forward strand. Spatial relationships between intervals are described using Allen interval algebra. Allen interval algebra (x is the upper interval) x before y, y after x ------ ----- x meets y, y met-by x (neither x or y are zero-width) ------ ----- x overlaps y, y overlaps x ------ ----- x starts y, y started-by x (neither x or y are zero-width) ---- ------- x during y, y contains x --- ----- x finishes y, y finished-by x (neither x or y are zero-width) --- ----- x equals y ----- ----- This set of functions is extended with others that are less strict. inclusive-before which is the union of before and meets inclusive-after which is the union of after and met-by inclusive-contains which is the union of contains, started-by, finished-by and equals inclusive-overlaps which is the union of overlaps and inclusive-contains")) (defclass na-sequence-interval (na-sequence interval stranded-mixin) () (:documentation "A nucleic acid sequence that is an interval within a reference sequence. In addition to the upper and lower bounds, a strand is defined. The strand indicates the strand of the reference sequence on which the interval lies.")) (defclass aa-sequence-interval (aa-sequence interval) () (:documentation "An amino acid sequence that is an interval within a reference sequence.")) (defgeneric beforep (x y) (:documentation "Returns T if X is before Y according to Allen's Interval Algebra, or NIL otherwise. This definition of 'before' is stricter than is often used in bioinformatics. See also {defun inclusive-beforep} .")) (defgeneric afterp (x y) (:documentation "Returns T if X is after Y according to Allen's Interval Algebra, or NIL otherwise. This definition of 'after' is stricter than is often used in bioinformatics. See also {defun inclusive-afterp} .")) (defgeneric meetsp (x y) (:documentation "Returns T if X meets Y according to Allen's Interval Algebra, or NIL otherwise.")) (defgeneric met-by-p (x y) (:documentation "Returns T if X is met by Y according to Allen's Interval Algebra, or NIL otherwise.")) (defgeneric overlapsp (x y) (:documentation "Returns T if X overlaps Y according to Allen's Interval Algebra, or NIL otherwise. This definition of 'overlaps' is stricter than is often used in bioinformatics. See also {defun inclusive-overlapsp} .")) (defgeneric startsp (x y) (:documentation "Returns T if X starts Y according to Allen's Interval Algebra, or NIL otherwise.")) (defgeneric started-by-p (x y) (:documentation "Returns T if X is started by Y according to Allen's Interval Algebra, or NIL otherwise.")) (defgeneric duringp (x y) (:documentation "Returns T if X occurs during Y according to Allen's Interval Algebra, or NIL otherwise.")) (defgeneric containsp (x y) (:documentation "Returns T if X contains Y according to Allen's Interval Algebra, or NIL otherwise. This definition of 'contains' is stricter than is often used in bioinformatics. See also {defun inclusive-containsp} .")) (defgeneric finishesp (x y) (:documentation "Returns T if X finishes Y according to Allen's Interval Algebra, or NIL otherwise.")) (defgeneric finished-by-p (x y) (:documentation "Returns T if X is finished by Y according to Allen's Interval Algebra, or NIL otherwise.")) (defgeneric interval-equal (x y) (:documentation "Returns T if X is interval equal Y according to Allen's Interval Algebra, or NIL otherwise.")) (defgeneric inclusive-beforep (x y) (:documentation "The union of beforep and meetsp. This predicate is often named 'before' in bioinformatics use cases. See also {defun beforep} .")) (defgeneric inclusive-afterp (x y) (:documentation "The union of afterp and meet-by-p. This predicate is often named 'after' in bioinformatics use cases. See also {defun beforep} .")) (defgeneric inclusive-containsp (x y) (:documentation "The union of containsp, started-by-p, finished-by-p and interval-equal. This predicate is often named 'contains' in bioinformatics use cases. See also {defun containsp} .")) (defgeneric inclusive-duringp (x y) (:documentation "The union of duringp, startsp, finishesp and interval-equal. See also {defun duringp} .")) (defgeneric inclusive-overlapsp (x y) (:documentation "The union of overlapsp, inclusive-duringp and inclusive-containsp. This predicate is often named 'overlaps' in bioinformatics use cases. See also {defun overlapsp} .")) ;;; Initialization methods (defmethod initialize-instance :after ((interval na-sequence-interval) &key) (with-slots (lower upper reference strand num-strands) interval (%check-interval-range lower upper reference) (%check-interval-strands strand num-strands reference))) (defmethod initialize-instance :after ((interval aa-sequence-interval) &key) (with-slots (lower upper reference) interval (%check-interval-range lower upper reference))) ;;; Printing methods (defmethod print-object ((interval interval) stream) (print-unreadable-object (interval stream :type t :identity t) (with-slots (lower upper) interval (format stream "~a ~a" lower upper)))) (defmethod print-object ((interval na-sequence-interval) stream) (print-unreadable-object (interval stream :type t :identity t) (with-slots (lower upper) interval (format stream "~a ~a ~a" lower upper (strand-of interval))))) (defmethod print-object ((interval aa-sequence-interval) stream) (print-unreadable-object (interval stream :type t :identity t) (with-slots (lower upper) interval (format stream "~a ~a" lower upper)))) (defmethod make-interval ((reference na-sequence) &rest initargs) (apply #'make-instance 'na-sequence-interval :reference reference initargs)) (defmethod make-interval ((reference aa-sequence) &rest initargs) (apply #'make-instance 'aa-sequence-interval :reference reference initargs)) ;; (let* ((ref (make-dna (make-string 10000000 :initial-element #\a))) ;; (dna (find-alphabet :simple-dna)) ;; (intervals (make-array 100000 :initial-element nil))) ;; (with-sequence-residues (residue ref) ;; (setf residue (random-token-of dna))) ;; (dotimes (i (length intervals)) ;; (let* ((len (* 10 (random 2000))) ;; (lower (random (- 10000000 len)))) ;; (setf (svref intervals i) ;; (make-interval ref :lower lower :upper (+ lower len))))) ;; (sort intervals #'< :key #'lower-of) ;; (time (let ((x (svref intervals 0))) ;; (cons x ;; (loop ;; for i across intervals ;; when (overlaps x i) ;; collect i))))) ;;; Implementation methods (defmethod (setf reference-of) :before (value (interval interval)) (with-slots (lower upper) interval (%check-interval-range lower upper value))) (defmethod (setf reference-of) :before (value (interval na-sequence-interval)) (with-accessors ((strand strand-of) (num-strands num-strands-of)) interval (%check-interval-strands strand num-strands value))) (defmethod (setf num-strands-of) :before (value (interval na-sequence-interval)) (%check-interval-strands (strand-of interval) value (slot-value interval 'reference))) (defmethod simplep ((interval na-sequence-interval)) (with-slots (reference) interval (and reference (simplep reference)))) (defmethod simplep ((interval aa-sequence-interval)) (with-slots (reference) interval (and reference (simplep reference)))) (defmethod ambiguousp ((interval na-sequence-interval)) (with-slots (reference) interval (or (null reference) (ambiguousp reference)))) (defmethod ambiguousp ((interval aa-sequence-interval)) (with-slots (reference) interval (or (null reference) (ambiguousp reference)))) (defmethod virtualp ((interval na-sequence-interval)) (with-slots (reference) interval (or (null reference) (virtualp reference)))) (defmethod virtualp ((interval aa-sequence-interval)) (with-slots (reference) interval (or (null reference) (virtualp reference)))) (defmethod length-of ((interval interval)) (with-slots (lower upper) interval (- upper lower))) (defmethod coerce-sequence :around ((interval interval) (type (eql 'string)) &key start end) (declare (ignore start end)) (with-slots (lower upper reference) interval (if reference (call-next-method) (make-string (- upper lower) :element-type 'base-char :initial-element +gap-char+)))) (defmethod coerce-sequence ((interval interval) (type (eql 'string)) &key (start 0) (end (length-of interval))) (coerce-sequence (slot-value interval 'reference) 'string :start start :end end)) (defmethod coerce-sequence ((interval na-sequence-interval) (type (eql 'string)) &key (start 0) (end (length-of interval))) (with-slots (lower upper reference strand) interval (cond ((or (eql *unknown-strand* strand) (eql *forward-strand* strand)) (coerce-sequence reference 'string :start (+ lower start) :end (+ lower end))) ((and (eql *reverse-strand* strand) (= 2 (num-strands-of reference))) (coerce-sequence (nreverse-complement (subsequence reference (+ lower start) (+ lower end))) 'string)) (t (error 'bio-sequence-op-error :text (txt "a reverse-strand interval may not be created" "on a single-stranded sequence.")))))) (defmethod subsequence ((interval na-sequence-interval) (start fixnum) &optional end) (let ((end (or end (length-of interval)))) (with-slots (lower upper reference strand num-strands) interval (cond ((or (eql *unknown-strand* strand) (eql *forward-strand* strand)) (subsequence reference (+ lower start) (+ lower end))) ((and (eql *reverse-strand* strand) (= 2 (num-strands-of reference))) (nreverse-complement (subsequence reference (+ lower start) (+ lower end)))) (t (error 'bio-sequence-op-error :text (txt "a reverse-strand interval may not be applied" "to a single-stranded sequence."))))))) (defmethod subsequence ((interval aa-sequence-interval) (start fixnum) &optional end) (let ((end (or end (length-of interval)))) (with-slots (lower upper reference) interval (subsequence reference (+ lower start) (+ lower end))))) (defmethod reverse-complement ((interval na-sequence-interval)) (with-slots (lower upper reference) interval (let ((ref-length (length-of reference)) (int-length (- upper lower))) (make-instance 'na-sequence-interval :lower (- ref-length upper) :upper (+ (- ref-length upper) int-length) :strand (complement-strand (strand-of interval)) :reference reference)))) (defmethod nreverse-complement ((interval na-sequence-interval)) (with-slots (lower upper reference strand) ; direct slot access to ; allow inversion in ; place interval (%check-interval-strands (complement-strand strand) (num-strands-of interval) reference) (let ((ref-length (length-of reference)) (int-length (- upper lower))) (setf lower (- ref-length upper) upper (+ lower int-length) strand (complement-strand strand)))) interval) (defmacro with-interval-slots (((lower-x upper-x interval-x) (lower-y upper-y interval-y)) &body body) "Utility macro for lower and upper bound comparisions between a pair of intervals." `(with-slots ((,lower-x lower) (,upper-x upper)) ,interval-x (with-slots ((,lower-y lower) (,upper-y upper)) ,interval-y ,@body))) (defmethod beforep ((x interval) (y interval)) (< (slot-value x 'upper) (slot-value y 'lower))) (defmethod afterp ((x interval) (y interval)) (> (slot-value x 'lower) (slot-value y 'upper))) (defmethod meetsp ((x interval) (y interval)) (with-interval-slots ((lowx upx x) (lowy upy y)) (and (< lowx upx) (= upx lowy)))) ; to meet y, x may not be zero-width (defmethod met-by-p ((x interval) (y interval)) (with-interval-slots ((lowx upx x) (lowy upy y)) (and (< lowy upy) (= lowx upy)))) ; to meet x, y may not be zero-width (defmethod overlapsp ((x interval) (y interval)) (with-interval-slots ((lowx upx x) (lowy upy y)) (or (< lowx lowy upx upy) (< lowy lowx upy upx)))) (defmethod startsp ((x interval) (y interval)) (with-interval-slots ((lowx upx x) (lowy upy y)) (and (< lowx upx) (< lowy upy) ; neither x or y are zero-width (= lowx lowy) (< upx upy)))) (defmethod started-by-p ((x interval) (y interval)) (with-interval-slots ((lowx upx x) (lowy upy y)) (and (< lowx upx) (< lowy upy) ; neither x or y are zero-width (= lowx lowy) (> upx upy)))) (defmethod duringp ((x interval) (y interval)) (with-interval-slots ((lowx upx x) (lowy upy y)) (and (> lowx lowy) (< upx upy)))) (defmethod containsp ((x interval) (y interval)) (with-interval-slots ((lowx upx x) (lowy upy y)) (and (< lowx lowy) (> upx upy)))) (defmethod finishesp ((x interval) (y interval)) (with-interval-slots ((lowx upx x) (lowy upy y)) (and (< lowx upx) (< lowy upy) ; neither x or y are zero-width (> lowx lowy) (= upx upy)))) (defmethod finished-by-p ((x interval) (y interval)) (with-interval-slots ((lowx upx x) (lowy upy y)) (and (< lowx upx) (< lowy upy) ; neither x or y are zero-width (< lowx lowy) (= upx upy)))) (defmethod interval-equal ((x interval) (y interval)) (with-interval-slots ((lowx upx x) (lowy upy y)) (and (= lowx lowy) (= upx upy)))) (defmethod inclusive-beforep ((x interval) (y interval)) (or (beforep x y) (meetsp x y))) (defmethod inclusive-afterp ((x interval) (y interval)) (or (afterp x y) (met-by-p x y))) (defmethod inclusive-containsp ((x interval) (y interval)) (or (interval-equal x y) (containsp x y) (started-by-p x y) (finished-by-p x y))) (defmethod inclusive-duringp ((x interval) (y interval)) (or (interval-equal x y) (duringp x y) (startsp x y) (finishesp x y))) (defmethod inclusive-overlapsp ((x interval) (y interval)) (or (overlapsp x y) (inclusive-duringp x y) (inclusive-containsp x y))) ;; TODO -- separate methods or add an integer parameter to existing ;; overlapsp method? ;; (defmethod min-overlapsp ((x interval) (y interval) (n fixnum)) ;; (with-accessors ((lowx lower-of) (upx upper-of)) ;; x ;; (with-accessors ((lowy lower-of) (upy upper-of)) ;; y ;; (>= (- (min lowx lowy) (max upx upy)) n)))) ;; (defmethod min-beforep ((x interval) (y interval) (n fixnum)) ;; (<= (upper-of x) (+ (lower-of y) n))) ;; FIXME -- circular sequences ;; These may have intervals that travel around the sequence multiple ;; times ;; TODO -- ;; canonicalize negative coordinates to positive (maybe public function?) ;; calculate numbers of rotations for intervals (maybe public function?) ;; overlaps, intersections, unions ;;; Utility functions (declaim (inline %check-interval-range)) (defun %check-interval-range (lower upper reference) "Validates interval bounds LOWER and UPPER against REFERENCE to ensure that the interval lies within the bounds of the reference." (if reference (let ((length (length-of reference))) (check-arguments (<= 0 lower upper length) (lower upper) "must satisfy (<= 0 lower upper ~d)" length)) (check-arguments (<= lower upper) (lower upper) "must satisty (<= lower upper"))) (declaim (inline %check-interval-strands)) (defun %check-interval-strands (strand num-strands reference) "Validates STRAND and NUM-STRANDS against REFERENCE to ensure that a double-stranded interval is not applied to a single-stranded reference and a reverse-strand interval is not applied to a single-stranded reference." (when reference (let ((num-ref-strands (num-strands-of reference))) (check-arguments (not (> num-strands num-ref-strands)) (num-strands reference) (txt "a double-stranded interval may not be" "applied to a single-stranded sequence")) (check-arguments (not (and (= 1 num-ref-strands) (eql *reverse-strand* strand))) (num-strands reference) (txt "a reverse-strand interval may not be" "applied to a single-stranded sequence")))))
19,074
Common Lisp
.lisp
414
40.28744
80
0.666792
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
20d3e99bd70b9699ef35ccebd3af11a51ed130eb7d6be690ebe3fd5fb3a58ac4
9,656
[ -1 ]
9,657
bio-sequence-encoding.lisp
keithj_cl-genomic/src/bio-sequence-encoding.lisp
;;; ;;; Copyright (c) 2007-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 tnhe ;;; 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 :bio-sequence) (defun complement-dna (base) "Returns the complentary DNA base to that represented by the character BASE. Folds to lower-case." (ecase base ((#\t #\T) #\a) ((#\c #\C) #\g) ((#\a #\A) #\t) ((#\g #\G) #\c) ((#\r #\R) #\y) ((#\y #\Y) #\r) ((#\k #\K) #\m) ((#\m #\M) #\k) ((#\s #\S) #\s) ((#\w #\W) #\w) ((#\b #\B) #\v) ((#\d #\D) #\h) ((#\h #\H) #\d) ((#\v #\V) #\b) ((#\n #\N) #\n) (#\- #\-))) (defun complement-rna (base) "Returns the complentary RNA base to that represented by the character BASE. Folds to lower-case." (ecase base ((#\u #\U) #\a) ((#\c #\C) #\g) ((#\a #\A) #\u) ((#\g #\G) #\c) ((#\r #\R) #\y) ((#\y #\Y) #\r) ((#\k #\K) #\m) ((#\m #\M) #\k) ((#\s #\S) #\s) ((#\w #\W) #\w) ((#\b #\B) #\v) ((#\d #\D) #\h) ((#\h #\H) #\d) ((#\v #\V) #\b) ((#\n #\N) #\n) (#\- #\-))) (declaim (inline complement-dna-8bit)) (defun complement-dna-8bit (byte) "Returns the byte representing the complementary DNA base to that of BYTE. Folds to lower case." (ecase byte ((116 84) 97) ((99 67) 103) ((97 65) 116) ((103 71) 99) ((114 82) 121) ((121 89) 114) ((107 75) 109) ((109 77) 107) ((115 83) 115) ((119 87) 119) ((98 66) 118) ((100 68) 104) ((104 72) 100) ((118 86) 98) ((110 78) 110) (45 45))) (declaim (inline complement-dna-4bit)) (defun complement-dna-4bit (encoded-base) "Returns the complentary encoded DNA base to that represented by ENCODED-BASE." (ecase encoded-base (#b0001 #b1000) (#b0010 #b0100) (#b0100 #b0010) (#b1000 #b0001) (#b0101 #b1010) ; purine (#b1010 #b0101) ; pyrimidine (#b1100 #b0011) ; keto (#b0011 #b1100) ; amino (#b0110 #b0110) ; strong (#b1001 #b1001) ; weak (#b1110 #b0111) ; !adenosine (#b1101 #b1011) ; !cytosine (#b1011 #b1101) ; !guanine (#b0111 #b1110) ; !thymine (#b1111 #b1111) ; any (#b0000 #b0000))) ; gap (declaim (inline complement-rna-4bit)) (defun complement-rna-4bit (encoded-base) "Returns the complentary encoded RNA base to that represented by ENCODED-BASE." (ecase encoded-base (#b0001 #b1000) (#b0010 #b0100) (#b0100 #b0010) (#b1000 #b0001) (#b0101 #b1010) ; purine (#b1010 #b0101) ; pyrimidine (#b1100 #b0011) ; keto (#b0011 #b1100) ; amino (#b0110 #b0110) ; strong (#b1001 #b1001) ; weak (#b1110 #b0111) ; !adenosine (#b1101 #b1011) ; !cytosine (#b1011 #b1101) ; !guanine (#b0111 #b1110) ; !thymine (#b1111 #b1111) ; any (#b0000 #b0000))) ; gap (declaim (inline encode-dna-4bit)) (defun encode-dna-4bit (base) "Encodes DNA standard-char BASE as a 4-bit byte, representing A as 0001, C as 0010, G as 0100 and T as 1000. The first base is in the most significant 4-bit byte and the last base is in the least significant 4-bit byte. Ambiguous bases are represented by bitwise AND combinations of these." (ecase base ((#\a #\A) #b0001) ((#\c #\C) #b0010) ((#\g #\G) #b0100) ((#\t #\T) #b1000) ((#\r #\R) #b0101) ; purine ((#\y #\Y) #b1010) ; pyrimidine ((#\k #\K) #b1100) ; keto ((#\m #\M) #b0011) ; amino ((#\s #\S) #b0110) ; strong ((#\w #\W) #b1001) ; weak ((#\b #\B) #b1110) ; !adenosine ((#\d #\D) #b1101) ; !cytosine ((#\h #\H) #b1011) ; !guanine ((#\v #\V) #b0111) ; !thymine ((#\n #\N) #b1111) ; any (#\- #b0000))) ; gap (declaim (inline decode-dna-4bit)) (defun decode-dna-4bit (encoded-base) "Decodes 4-bit byte ENCODED-BASE, returning a lower case character." (ecase encoded-base (#b0001 #\a) (#b0010 #\c) (#b0100 #\g) (#b1000 #\t) (#b0101 #\r) (#b1010 #\y) (#b1100 #\k) (#b0011 #\m) (#b0110 #\s) (#b1001 #\w) (#b1110 #\b) (#b1101 #\d) (#b1011 #\h) (#b0111 #\v) (#b1111 #\n) (#b0000 #\-))) (declaim (inline encode-dna-comp-4bit)) (defun encode-dna-comp-4bit (base) "Encodes the complement of DNA standard-char BASE as a 4-bit byte, representing T as 0001, C as 0010, A as 0100 and G as 1000. The first base is in the most significant 4-bit byte and the last base is in the least significant 4-bit byte. Ambiguous bases are represented by bitwise AND combinations of these." (encode-dna-4bit (complement-dna base))) (declaim (inline decode-dna-comp-4bit)) (defun decode-dna-comp-4bit (encoded-base) "Decodes 4-bit byte ENCODED-BASE, returning its complement as a lower case character." (complement-dna (decode-dna-4bit encoded-base))) (declaim (inline encode-rna-4bit)) (defun encode-rna-4bit (base) "Encodes RNA standard-char BASE as a 4-bit byte, representing U as 0001, C as 0010, A as 0100 and G as 1000. The first base is in the most significant 4-bit byte and the last base is in the least significant 4-bit byte. Ambiguous bases are represented by bitwise AND combinations of these." (ecase base ((#\a #\A) #b0001) ((#\c #\C) #b0010) ((#\g #\G) #b0100) ((#\u #\U) #b1000) ((#\r #\R) #b0101) ; purine ((#\y #\Y) #b1010) ; pyrimidine ((#\k #\K) #b1100) ; keto ((#\m #\M) #b0011) ; amino ((#\s #\S) #b0110) ; strong ((#\w #\W) #b1001) ; weak ((#\b #\B) #b1110) ; !adenosine ((#\d #\D) #b1101) ; !cytosine ((#\h #\H) #b1011) ; !guanine ((#\v #\V) #b0111) ; !thymine ((#\n #\N) #b1111) ; any (#\- #b0000))) ; gap (declaim (inline decode-rna-4bit)) (defun decode-rna-4bit (encoded-base) "Decodes 4-bit byte ENCODED-BASE, returning a lower case character." (ecase encoded-base (#b0001 #\a) (#b0010 #\c) (#b0100 #\g) (#b1000 #\u) (#b0101 #\r) (#b1010 #\y) (#b1100 #\k) (#b0011 #\m) (#b0110 #\s) (#b1001 #\w) (#b1110 #\b) (#b1101 #\d) (#b1011 #\h) (#b0111 #\v) (#b1111 #\n) (#b0000 #\-))) (declaim (inline encode-rna-comp-4bit)) (defun encode-rna-comp-4bit (base) "Encodes the complement of RNA standard-char BASE as a 4-bit byte, representing U as 0001, C as 0010, A as 0100 and G as 1000. The first base is in the most significant 4-bit byte and the last base is in the least significant 4-bit byte. Ambiguous bases are represented by bitwise AND combinations of these." (encode-rna-4bit (complement-rna base))) (declaim (inline decode-rna-comp-4bit)) (defun decode-rna-comp-4bit (encoded-base) "Decodes 4-bit byte ENCODED-BASE, returning its complement as a lower case character." (complement-rna (decode-rna-4bit encoded-base))) (declaim (inline encode-aa-7bit)) (defun encode-aa-7bit (aa) "Encodes AA standard-char as a 7-bit byte." (ccase aa ((#\a #\A) 1) ((#\b #\B) 2) ((#\c #\C) 3) ((#\d #\D) 4) ((#\e #\E) 5) ((#\f #\F) 6) ((#\g #\G) 7) ((#\h #\H) 8) ((#\i #\I) 9) ((#\j #\J) 10) ((#\k #\K) 11) ((#\l #\L) 12) ((#\m #\M) 13) ((#\n #\N) 14) ((#\o #\O) 15) ((#\p #\P) 16) ((#\q #\Q) 17) ((#\r #\R) 18) ((#\s #\S) 19) ((#\t #\T) 20) ((#\u #\U) 21) ((#\v #\V) 22) ((#\w #\W) 23) ((#\x #\X) 24) ((#\y #\Y) 25) ((#\z #\Z) 26) (#\* 27) (#\- 0))) (declaim (inline decode-aa-7bit)) (defun decode-aa-7bit (encoded-aa) "Decodes 7-bit byte ENCODED-AA, returning an upper case character." (ecase encoded-aa (1 #\A) (2 #\B) (3 #\C) (4 #\D) (5 #\E) (6 #\F) (7 #\G) (8 #\H) (9 #\I) (10 #\J) (11 #\K) (12 #\L) (13 #\M) (14 #\N) (15 #\O) (16 #\P) (17 #\Q) (18 #\R) (19 #\S) (20 #\T) (21 #\U) (22 #\V) (23 #\W) (24 #\X) (25 #\Y) (26 #\Z) (27 #\*) (0 #\-))) (defun symbolize-dna-base (base) "Returns a Lisp keyword symbol representing the base character BASE." (let ((encoded-base (encode-dna-4bit base))) (ecase encoded-base (#b0001 :thymine) (#b0010 :cytosine) (#b0100 :adenine) (#b1000 :guanine) (#b0101 :purine) (#b1010 :pyrimidine) (#b1100 :keto) (#b0011 :amino) (#b0110 :strong) (#b1001 :weak) (#b1110 :!adenine) (#b1101 :!cytosine) (#b1011 :!guanine) (#b0111 :!thymine) (#b1111 :any) (#b0000 :gap)))) (defun encode-dna-symbol (dna-symbol) "Encodes the symbol DNA-SYMBOL as a 4-bit byte." (ecase dna-symbol (:thymine #b0001) (:cytosine #b0010) (:adenine #b0100) (:guanine #b1000) (:purine #b0101) (:pyrimidine #b1010) (:keto #b1100) (:amino #b0011) (:strong #b0110) (:weak #b1001) (:!adenine #b1110) (:!cytosine #b1101) (:!guanine #b1011) (:!thymine #b0111) (:any #b1111) (:gap #b0000))) (defun symbolize-rna-base (base) "Returns a Lisp keyword symbol representing the base character BASE." (let ((encoded-base (encode-rna-4bit base))) (ecase encoded-base (#b0001 :uracil) (#b0010 :cytosine) (#b0100 :adenine) (#b1000 :guanine) (#b0101 :purine) (#b1010 :pyrimidine) (#b1100 :keto) (#b0011 :amino) (#b0110 :strong) (#b1001 :weak) (#b1110 :!adenine) (#b1101 :!cytosine) (#b1011 :!guanine) (#b0111 :!thymine) (#b1111 :any) (#b0000 :gap)))) (defun encode-rna-symbol (rna-symbol) "Encodes the symbol RNA-SYMBOL as a 4-bit byte." (ecase rna-symbol (:uracil #b0001) (:cytosine #b0010) (:adenine #b0100) (:guanine #b1000) (:purine #b0101) (:pyrimidine #b1010) (:keto #b1100) (:amino #b0011) (:strong #b0110) (:weak #b1001) (:!adenine #b1110) (:!cytosine #b1101) (:!guanine #b1011) (:!thymine #b0111) (:any #b1111) (:gap #b0000))) (defun symbolize-aa (aa) "Returns a Lisp keyword symbol representing the amino-acid character AA." (let ((encoded-aa (encode-aa-7bit aa))) (ecase encoded-aa (1 :alanine) (2 :aspartatic-acid/asparagine) (3 :cysteine) (4 :aspartic-acid) (5 :glutamic-acid) (6 :phenylalanine) (7 :glycine) (8 :histidine) (9 :isoleucine) (10 :isoleucine/leucine) (11 :lysine) (12 :leucine) (13 :methionine) (14 :asparagine) (15 :pyrrolysine) (16 :proline) (17 :glutamine) (18 :arginine) (19 :serine) (20 :threonine) (21 :selenocysteine) (22 :valine) (23 :tryptophan) (24 :unknown) (25 :tyrosine) (26 :glutamic-acid/glutamine) (27 :terminator) (0 :gap)))) (defun encode-aa-symbol (aa-symbol) "Encodes the symbol AA-SYMBOL as a 7-bit byte." (ecase aa-symbol (:alanine 1) (:aspartatic-acid/asparagine 2) (:cysteine 3) (:aspartic-acid 4) (:glutamic-acid 5) (:phenylalanine 6) (:glycine 7) (:histidine 8) (:isoleucine 9) (:isoleucine/leucine 10) (:lysine 11) (:leucine 12) (:methionine 13) (:asparagine 14) (:pyrrolysine 15) (:proline 16) (:glutamine 17) (:arginine 18) (:serine 19) (:threonine 20) (:selenocysteine 21) (:valine 22) (:tryptophan 23) (:unknown 24) (:tyrosine 25) (:glutamic-acid/glutamine 26) (:terminator 27) (:gap 0))) (defun enum-dna-base (base) "Returns a sorted list of the unambiguous DNA characters represented by DNA character BASE." (sort (mapcar #'decode-dna-4bit (enum-encoded-base (encode-dna-4bit base))) #'char<=)) (defun enum-rna-base (base) "Returns a sorted list of the unambiguous RNA characters represented by RNA character BASE." (sort (mapcar #'decode-rna-4bit (enum-encoded-base (encode-rna-4bit base))) #'char<=)) (defun enum-dna-codon (codon) "Returns a list of the unambiguous DNA character codons represented by list of DNA characters CODON." (mapcar (lambda (ecodon) (mapcar #'decode-dna-4bit ecodon)) (enum-encoded-codon (mapcar #'encode-dna-4bit codon)))) (defun enum-rna-codon (codon) "Returns a list of the unambiguous RNA character codons represented by list of RNA characters CODON." (mapcar (lambda (ecodon) (mapcar #'decode-rna-4bit ecodon)) (enum-encoded-codon (mapcar #'encode-rna-4bit codon)))) (defun enum-aa (aa) "Returns a list of the unambiguous AA characters represented by amino-acid character AA." (sort (mapcar #'decode-aa-7bit (enum-encoded-aa (encode-aa-7bit aa))) #'char<=)) (defun enum-encoded-base (encoded-base) "Returns a list of all the unambiguous encoded bases represented by ENCODED-BASE." (declare (optimize (speed 3))) (declare (type octet encoded-base)) (loop for b from 0 below (integer-length encoded-base) when (logbitp b encoded-base) collect (ash 1 b))) (defun enum-encoded-codon (encoded-codon) "Returns a list of all the unambiguous encoded codons represented by ENCODED-CODON." (if (null (rest encoded-codon)) (mapcar #'list (enum-encoded-base (first encoded-codon))) (loop for x in (enum-encoded-base (first encoded-codon)) nconc (mapcar (lambda (y) (cons x y)) (enum-encoded-codon (rest encoded-codon)))))) (defun enum-encoded-aa (encoded-aa) "Returns a list of all the unambiguous encoded amino-acids represented by ENCODED-AA." (cond ((= 2 encoded-aa) ; aspartatic-acid/asparagine (list 4 14)) ((= 10 encoded-aa) ; isoleucine/leucine (list 9 12)) ((= 26 encoded-aa) ; glutamic-acid/glutamine (list 1 17)) (t (list encoded-aa)))) (defun phred-quality (p) "Returns the Phred score of a base where P is the error probability." (round (* -10 (/ (log p) (log 10))))) (defun phred-probability (q) "Returns the error probability of a base where Q is the Phred score." (expt 10 (/ (- q) 10))) (defun encode-phred-quality (q) "Returns the character encoding of the Phred quality score Q." (code-char (min 126 (+ 33 q)))) (defun decode-phred-quality (c) "Returns the Phred quality score encoded by the character C." (- (char-code c) 33)) (defun solexa-quality (p) "Returns the Solexa score of a base where P is the error probability." (let ((denom (- 1 p))) (if (zerop denom) -20 (round (* -10 (/ (log (/ p denom)) (log 10))))))) (defun encode-solexa-quality (q) "Returns a character encoding of the Solexa quality score Q." (code-char (+ 64 q))) (defun decode-solexa-quality (c) "Returns the Solexa quality score encoded by the character C." (- (char-code c) 64)) (defun solexa-to-phred-quality (q) "Returns the Phred quality score corresponding to the Solexa quality score Q." (* 10 (/ (log (1+ (expt 10 (/ q 10)))) (log 10)))) (defun encode-illumina-quality (q) "Returns a character encoding of the Illumina 1.3+ quality score Q." (code-char (min 126 (+ 64 q)))) (defun decode-illumina-quality (c) "Returns the Illumina 1.3+ quality score encoded by the character C." (- (char-code c) 64))
16,969
Common Lisp
.lisp
547
26.396709
73
0.554755
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
f96e897d04b5a491fc5f87440f4101d8c68b7d8abd030efe939af799eb8ff077
9,657
[ -1 ]
9,658
bio-sequence.lisp
keithj_cl-genomic/src/bio-sequence.lisp
;;; ;;; Copyright (c) 2007-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :bio-sequence) (deftype encoded-residues (n) "Parameterized type for encoded sequence residues." `(simple-array (unsigned-byte ,n) (*))) (defparameter *sequence-print-limit* 160 "Maximum length of sequence to be pretty-printed.") (defmacro define-strand-decoder (type test forward reverse unknown) "Defines a sequence strand decoder method for a particular strand representation that converts an ad hoc strand designator to a canonical strand object. There is no standard nomenclature for sequence strands and they may be represented as strings, characters, integers, mathematical symbols etc. For example +/-/? or fwd/rev/unk or 1/-1/0. Arguments: - type (Lisp type): The Lisp type of the strand designators. - test (function): The test function to be used to compare strand designators. - forward (object): The forward strand designator. - reverse (object): The reverse strand designator. - unknown (object): The unknown strand designator." `(progn (defmethod decode-strand ((strand ,type) &key strict) (cond ((,test ,forward strand) *forward-strand*) ((,test ,reverse strand) *reverse-strand*) ((,test ,unknown strand) *unknown-strand*) (t (when strict (check-arguments nil (strand) "not a valid ~a strand designator" ',type))))))) (defmacro with-sequence-residues ((var seq &key start end) &body body) "Executes BODY in the context of bio-sequence SEQ such that VAR is iteratively bound to each residue of SEQ in turn. Arguments: - var (symbol or symbols): The iteration variable to which the current residue will be bound during iteration. - seq (bio-sequence): The sequence iterated to be iterated over. Key: - start (fixnum): The start index of the iteration. - end (fixnum): The end index of the iteration. Body: Forms to be executed in the context of these bindings." (with-gensyms (lower upper vector) `(let ((,lower (or ,start 0)) (,upper (or ,end (length-of ,seq)))) (etypecase ,seq (encoded-dna-sequence (with-slots ((,vector vector)) ,seq (loop for i of-type vector-index from ,lower below ,upper do (symbol-macrolet ((,var (%aref-dna-4bit ,vector i))) ,@body)))) (t (loop for i of-type vector-index from ,lower below ,upper do (symbol-macrolet ((,var (element-of ,seq i))) ,@body)))) ,seq))) (define-strand-decoder string string= "+" "-" "?") (define-strand-decoder fixnum = 1 -1 0) (define-strand-decoder character char= #\+ #\- #\?) (define-strand-decoder symbol eql :forward :reverse :unknown) (defun make-dna (residues &rest initargs) "Returns a new DNA sequence object. Arguments: - residues (vector or NIL): A vector of characters, encoded residues or NIL. The latter creates a virtual sequence and requires a length argument to be supplied. Rest: - initargs: Any initialization arguments. Returns: - A DNA sequence object." (if (or (null residues) (zerop (length residues))) (apply #'make-instance 'virtual-dna-sequence initargs) (make-encoded-vector-seq 'encoded-dna-sequence residues #'encode-dna-4bit 'nibble initargs))) (defun make-rna (residues &rest initargs) "Returns a new RNA sequence object. Arguments: - residues (vector or NIL): A vector of characters, encoded residues or NIL. The latter creates a virtual sequence and requires a length argument to be supplied. Rest: - initargs: Any initialization arguments. Returns: - A RNA sequence object." (if (or (null residues) (zerop (length residues))) (apply #'make-instance 'virtual-rna-sequence initargs) (make-encoded-vector-seq 'encoded-rna-sequence residues #'encode-rna-4bit 'nibble initargs))) (defun make-dna-quality (residues quality &rest initargs &key (metric :sanger) &allow-other-keys) "Returns a new DNA sequence object with quality. Arguments: - residues (vector): A vector of characters or encoded residues. It is not possible to create virtual sequences with quality information. - quality (vector integer): A vector of integers, the same length as RESIDUES, containing quality data. Rest: - initargs: Any initialization arguments. Key: - metric (symbol): A symbol indicating the quality metric used in QUALITY. Either :sanger , :solexa or :illumina. Returns: - A DNA sequence object." (check-arguments (= (length residues) (length quality)) (residues quality) "the residues and quality vectors were not the same length") (let ((initargs (remove-key-values '(:metric) initargs))) (apply #'make-instance 'dna-quality-sequence :vector (ensure-encoded residues #'encode-dna-4bit 'nibble) :quality (ensure-decoded-quality quality metric) :metric metric initargs))) (defun make-aa (residues &rest initargs) "Returns a new AA sequence object. Arguments: - residues (vector): A vector of characters, encoded residues or NIL. The latter creates a virtual sequence and requires a length argument to be supplied. Rest: - initargs: Any initialization arguments. Returns: - An AA sequence object." (if (null residues) (apply #'make-instance 'virtual-aa-sequence initargs) (make-encoded-vector-seq 'encoded-aa-sequence residues #'encode-aa-7bit '(unsigned-byte 7) initargs))) (defun make-encoded-vector-seq (class residues encoder element-type initargs) (check-arguments (vectorp residues) (residues) "expected a vector") (apply #'make-instance class :vector (ensure-encoded residues encoder element-type) initargs)) (defun bio-sequence-p (obj) "Returns T if OBJ is a subtype of {defclass bio-sequence} , or NIL otherwise." (subtypep (class-of obj) 'bio-sequence)) (defun na-sequence-p (obj) "Returns T if OBJ is a subtype of {defclass na-sequence} , or NIL otherwise." (subtypep (class-of obj) 'na-sequence)) (defun dna-sequence-p (obj) "Returns T if OBJ is a subtype of {defclass dna-sequence} , or NIL otherwise." (subtypep (class-of obj) 'dna-sequence)) (defun rna-sequence-p (obj) "Returns T if OBJ is a subtype of {defclass rna-sequence} , or NIL otherwise." (subtypep (class-of obj) 'rna-sequence)) (defun aa-sequence-p (obj) "Returns T if OBJ is a subtype of {defclass aa-sequence} , or NIL otherwise." (subtypep (class-of obj) 'aa-sequence)) (defun same-biotype-p (&rest seqs) "Returns T if SEQS are {defclass bio-sequence} s that share exactly the same alphabet, or NIL otherwise." (cond ((null seqs) nil) ((not (bio-sequence-p (first seqs))) nil) (t (loop with alphabet = (alphabet-of (first seqs)) for seq in (rest seqs) always (and (bio-sequence-p seq) (eql alphabet (alphabet-of seq))))))) (defun same-strand-num-p (&rest seqs) "Returns T if SEQS are {defclass na-sequence} s that share the same number of strands, or NIL otherwise." (if (null seqs) nil (loop with num-strands = (num-strands-of (first seqs)) for seq in (rest seqs) always (= num-strands (num-strands-of seq))))) (defun concat-sequence (&rest seqs) (check-arguments (apply #'same-biotype-p seqs) (seqs) "expected all sequences to be one of DNA, RNA or AA") (let ((construct (cond ((dna-sequence-p (first seqs)) #'make-dna) ((rna-sequence-p (first seqs)) #'make-rna) ((aa-sequence-p (first seqs)) #'make-aa) (t (check-arguments nil (seqs) (txt "expected all sequences to be" "one of DNA, RNA or AA")))))) ;; We use coerce-sequence to avoid a special case for virtual ;; sequences. We can't simply concatenate the encoded residue ;; vectors because virtual sequences do not have them (funcall construct (apply #'concatenate 'string (mapcar (lambda (s) (coerce-sequence s 'string)) seqs))))) ;;; Initialization methods (defmethod initialize-instance :after ((seq na-sequence) &key) (with-accessors ((num-strands num-strands-of)) seq (check-arguments (< 0 num-strands 3) (num-strands) "nucleic acid sequences may have 1 or 2 strands"))) ;;; Printing methods (defmethod print-object ((alphabet alphabet) stream) (print-unreadable-object (alphabet stream :type t) (princ (slot-value alphabet 'name) stream))) (defmethod print-object ((strand sequence-strand) stream) (print-unreadable-object (strand stream :type t) (with-slots (name token number) strand (format stream "~a/~a/~a" name token number)))) (defmethod print-object ((seq dna-sequence) stream) (%print-seq seq stream)) (defmethod print-object ((seq dna-sequence) stream) (%print-seq seq stream)) (defmethod print-object ((seq rna-sequence) stream) (%print-seq seq stream)) (defmethod print-object ((seq dna-quality-sequence) stream) (%print-quality-seq seq stream)) (defmethod print-object ((seq aa-sequence) stream) (%print-seq seq stream)) (defmethod print-object ((seq mapped-dna-sequence) stream) (if (dxn:in-memory-p seq) (%print-seq seq stream) (print-unreadable-object (seq stream :type t :identity t) (format stream "length ~d UNMAPPED" (length-of seq))))) ;;; Implementation methods (defmethod anonymousp ((seq identity-mixin)) (null (identity-of seq))) (defmethod strand-designator-p (strand) (declare (ignore strand)) nil) (defmethod strand-designator-p ((strand string)) (decode-strand strand)) (defmethod strand-designator-p ((strand fixnum)) (decode-strand strand)) (defmethod strand-designator-p ((strand character)) (decode-strand strand)) (defmethod strand-designator-p ((strand symbol)) (decode-strand strand)) (defmethod forward-strand-p ((strand sequence-strand)) (eql *forward-strand* strand)) (defmethod reverse-strand-p ((strand sequence-strand)) (eql *reverse-strand* strand)) (defmethod unknown-strand-p ((strand sequence-strand)) (eql *unknown-strand* strand)) (defmethod strand= ((strand1 sequence-strand) (strand2 sequence-strand)) (and (not (eql *unknown-strand* strand1)) (not (eql *unknown-strand* strand2)) (eql strand1 strand2))) (defmethod strand-equal ((strand1 sequence-strand) (strand2 sequence-strand)) (or (eql *unknown-strand* strand1) (eql *unknown-strand* strand2) (eql strand1 strand2))) (defmethod complement-strand ((strand sequence-strand)) (cond ((eql *forward-strand* strand) *reverse-strand*) ((eql *reverse-strand* strand) *forward-strand*) (t *unknown-strand*))) (defmethod complementp ((strand1 sequence-strand) (strand2 sequence-strand)) (strand= (complement-strand strand1) strand2)) (defmethod ambiguousp ((seq virtual-token-sequence)) t) ;;; FIXME -- this is only implemented for DNA/RNA/AA. If a user ;;; extends the set of alphabets this must be changed. (defmethod ambiguousp ((seq encoded-vector-sequence)) (with-slots (vector alphabet) seq (let ((fn (cond ((eql *dna* alphabet) #'enum-encoded-base) ((eql *rna* alphabet) #'enum-encoded-base) ((eql *aa* alphabet) #'enum-encoded-aa) (t (error "Unknown alphabet ~a" alphabet))))) (loop for elt across vector thereis (< 1 (length (funcall fn elt))))))) (defmethod ambiguousp ((seq mapped-dna-sequence)) (with-slots ((area dxn:mmap-area) length) seq (loop for i from 0 below length thereis (< 1 (length (enum-dna-base (code-char (cffi:mem-aref (dxn:mmap-area-ptr area) :char i)))))))) (defmethod simplep ((seq virtual-token-sequence)) nil) (defmethod simplep ((seq encoded-vector-sequence)) (not (ambiguousp seq))) (defmethod simplep ((seq mapped-dna-sequence)) (not (ambiguousp seq))) (defmethod virtualp ((seq token-sequence)) (declare (ignore seq)) nil) (defmethod virtualp ((seq virtual-token-sequence)) (declare (ignore seq)) t) (defmethod length-of ((seq encoded-vector-sequence)) (length (slot-value seq 'vector))) (defmethod length-of ((seq mapped-dna-sequence)) (dxn:length-of seq)) (defmethod single-stranded-p ((seq na-sequence)) (with-slots (num-strands) seq (= 1 num-strands))) (defmethod double-stranded-p ((seq na-sequence)) (with-slots (num-strands) seq (= 2 num-strands))) (defmethod (setf metric-of) :before (metric (obj quality-mixin)) (check-arguments (member metric '(:sanger :solexa :illumina)) (metric) "must be one of :sanger :solexa or :illumina")) (defmethod (setf num-strands-of) :before (value (seq na-sequence)) (check-arguments (< 0 value 3) (value) "nucleic acid sequences may have 1 or 2 strands")) (defmethod num-strands-of ((seq aa-sequence)) (error 'bio-sequence-op-error :text "Amino-acid sequences are not stranded.")) (defmethod element-of ((seq encoded-dna-sequence) (index fixnum)) (%aref-dna-4bit (slot-value seq 'vector) index)) (defmethod (setf element-of) (value (seq encoded-dna-sequence) (index fixnum)) (setf (%aref-dna-4bit (slot-value seq 'vector) index) value)) (defmethod element-of ((seq encoded-rna-sequence) (index fixnum)) (%aref-rna-4bit (slot-value seq 'vector) index)) (defmethod (setf element-of) (value (seq encoded-rna-sequence) (index fixnum)) (setf (%aref-rna-4bit (slot-value seq 'vector) index) value)) (defmethod element-of :before ((seq virtual-token-sequence) (index fixnum)) (%check-token-range (1- (length-of seq)) index index)) (defmethod element-of ((seq virtual-dna-sequence) (index fixnum)) (%check-token-range (1- (length-of seq)) index index) #\n) (defmethod element-of ((seq virtual-rna-sequence) (index fixnum)) (%check-token-range (1- (length-of seq)) index index) #\n) (defmethod element-of ((seq virtual-aa-sequence) (index fixnum)) (%check-token-range (1- (length-of seq)) index index) #\X) (defmethod element-of ((seq mapped-dna-sequence) (index fixnum)) (declare (optimize (speed 3) (safety 1))) (with-slots ((area dxn:mmap-area)) seq (code-char (cffi:mem-aref (dxn:mmap-area-ptr area) :char index)))) (defmethod (setf element-of) (value (seq mapped-dna-sequence) (index fixnum)) (declare (optimize (speed 3) (safety 1))) (with-slots ((area dxn:mmap-area)) seq (declare (type fixnum index)) (setf (cffi:mem-aref (dxn:mmap-area-ptr area) :char index) (char-code value)))) (declaim (inline residue-of)) (defun residue-of (seq index) "Returns the residue of SEQ at INDEX. This is a synonym of ELEMENT-OF." (element-of seq index)) (defun (setf residue-of) (value seq index) "Sets the residue of SEQ at INDEX to VALUE. This is a synonym of \(SETF ELEMENT-OF\)." (setf (element-of seq index) value)) (defmethod num-gaps-of ((seq encoded-vector-sequence) &key (start 0) end) (let ((end (or end (length-of seq)))) (loop for i from start below end count (= +encoded-gap-char+ (aref (slot-value seq 'vector) i))))) (defmethod coerce-sequence ((seq dna-sequence) (type (eql 'dna-sequence)) &key (start 0) end) (maybe-subsequence seq start end)) (defmethod coerce-sequence ((seq rna-sequence) (type (eql 'rna-sequence)) &key (start 0) end) (maybe-subsequence seq start end)) (defmethod coerce-sequence ((seq aa-sequence) (type (eql 'aa-sequence)) &key (start 0) end) (maybe-subsequence seq start end)) (defmethod coerce-sequence ((seq virtual-dna-sequence) (type (eql 'string)) &key (start 0) end) (%to-string-virtual seq #\n start end :lower)) (defmethod coerce-sequence ((seq virtual-rna-sequence) (type (eql 'string)) &key (start 0) end) (%to-string-virtual seq #\n start end :lower)) (defmethod coerce-sequence ((seq virtual-aa-sequence) (type (eql 'string)) &key (start 0) end) (%to-string-virtual seq #\X start end :upper)) (defmethod coerce-sequence ((seq encoded-dna-sequence) (type (eql 'string)) &key (start 0) end) (%to-string-encoded seq #'decode-dna-4bit start end :lower)) (defmethod coerce-sequence ((seq encoded-rna-sequence) (type (eql 'string)) &key (start 0) end) (%to-string-encoded seq #'decode-rna-4bit start end :lower)) (defmethod coerce-sequence ((seq encoded-aa-sequence) (type (eql 'string)) &key (start 0) end) (%to-string-encoded seq #'decode-aa-7bit start end :upper)) (defmethod coerce-sequence ((seq virtual-dna-sequence) (type (eql 'rna-sequence)) &key (start 0) end) (with-accessors ((length length-of)) seq (let ((end (or end length))) (%check-token-range length start end) (make-instance 'virtual-rna-sequence :length (- end start))))) (defmethod coerce-sequence ((seq virtual-rna-sequence) (type (eql 'dna-sequence)) &key (start 0) end) (with-accessors ((length length-of)) seq (let ((end (or end length))) (%check-token-range length start end) (make-instance 'virtual-dna-sequence :length (- end start))))) (defmethod coerce-sequence ((seq encoded-dna-sequence) (type (eql 'rna-sequence)) &key (start 0) end) (with-slots (vector) seq (let ((end (or end (length vector)))) (make-instance 'encoded-rna-sequence :vector (token-subsequence vector start end))))) (defmethod coerce-sequence ((seq encoded-rna-sequence) (type (eql 'dna-sequence)) &key (start 0) end) (with-slots (vector) seq (let ((end (or end (length vector)))) (make-instance 'encoded-dna-sequence :vector (token-subsequence vector start end))))) (defmethod coerce-sequence ((seq mapped-dna-sequence) (type (eql 'string)) &key (start 0) end) (with-slots ((length dxn:length) (area dxn:mmap-area)) seq (let* ((end (or end length)) (str (make-array (- end start) :element-type 'base-char :adjustable t :fill-pointer 0)) (ptr (dxn:mmap-area-ptr area))) (if (dxn:mmap-area-live-p area) ; Only access residues if mapped ;; FIXME -- with-output-to-string is 3x slower than simple ;; octet conversion (with-output-to-string (stream str :element-type 'base-char) (loop for i from start below end do (write-char (code-char (cffi:mem-aref ptr :char i)) stream) finally (return str))) (error 'invalid-operation-error :format-control (txt "cannot coerce ~a to a" "string when unmapped from memory") :format-arguments (list seq)))))) (defmethod subsequence ((seq encoded-vector-sequence) (start fixnum) &optional end) (with-slots (vector) seq (let ((end (or end (length vector)))) (make-instance (class-of seq) :vector (token-subsequence vector start end))))) (defmethod subsequence ((seq dna-quality-sequence) (start fixnum) &optional end) (with-slots (vector quality metric) seq (let ((end (or end (length vector)))) (make-instance 'dna-quality-sequence :vector (token-subsequence vector start end) :quality (subseq quality start end) :metric metric)))) (defmethod subsequence ((seq virtual-token-sequence) (start fixnum) &optional end) (with-accessors ((length length-of)) seq (let ((end (or end length))) (%check-token-range length start end) (make-instance (class-of seq) :length (- end start))))) (defmethod subsequence ((seq mapped-dna-sequence) (start fixnum) &optional end) (declare (optimize (speed 3))) (with-slots ((length dxn:length) (area dxn:mmap-area) ) seq (let ((end (or end length))) (declare (fixnum end)) (let ((vector (make-array (- end start) :element-type 'nibble)) (ptr (dxn:mmap-area-ptr area))) (loop for i of-type vector-index from start below end for j of-type vector-index = 0 then (1+ j) do (setf (aref vector j) (encode-dna-4bit (code-char (cffi:mem-aref ptr :char i))))) (make-instance 'encoded-dna-sequence :vector vector))))) (defmethod reverse-sequence ((seq encoded-vector-sequence)) (make-instance (class-of seq) :vector (reverse (slot-value seq 'vector)))) (defmethod reverse-sequence ((seq dna-quality-sequence)) (with-slots (vector quality metric) seq (make-instance 'dna-quality-sequence :vector (reverse vector) :quality (reverse quality) :metric metric))) (defmethod reverse-sequence ((seq virtual-token-sequence)) (make-instance (class-of seq) :length (length-of seq))) (defmethod reverse-sequence ((seq mapped-dna-sequence)) (declare (optimize (speed 3) (safety 1))) (with-slots ((length dxn:length) (area dxn:mmap-area)) seq (let ((rev-seq (make-instance 'mapped-dna-sequence :length length)) (ptr (dxn:mmap-area-ptr area))) (with-slots ((rev-area dxn:mmap-area)) rev-seq (let ((end (1- (the fixnum length))) (rev-ptr (dxn:mmap-area-ptr rev-area))) (loop for i from 0 to end do (let ((j (- end i))) (setf (cffi:mem-aref rev-ptr :char i) (cffi:mem-aref ptr :char j)))))) rev-seq))) (defmethod nreverse-sequence ((seq encoded-vector-sequence)) (with-slots (vector) seq (setf vector (nreverse vector)) seq)) (defmethod nreverse-sequence ((seq dna-quality-sequence)) (with-slots (vector quality) seq (setf vector (nreverse vector) quality (nreverse quality)) seq)) (defmethod nreverse-sequence ((seq virtual-token-sequence)) seq) (defmethod nreverse-sequence ((seq mapped-dna-sequence)) (declare (optimize (speed 3) (safety 1))) (with-slots ((length dxn:length) (area dxn:mmap-area)) seq (let ((rev-seq (make-instance 'mapped-dna-sequence :length length)) (ptr (dxn:mmap-area-ptr area))) (with-slots ((rev-area dxn:mmap-area)) rev-seq (let ((end (1- (the fixnum length))) (rev-ptr (dxn:mmap-area-ptr rev-area))) (loop for i from 0 to end do (let ((j (- end i))) (setf (cffi:mem-aref rev-ptr :char i) (cffi:mem-aref ptr :char j))))) (dxn:free-mapped-vector seq) ; Free the original seq (setf area rev-area)) ; Swap in the reversed seq seq))) (defmethod complement-sequence ((seq encoded-dna-sequence)) (make-instance 'encoded-dna-sequence :vector (complement-tokens (copy-seq (slot-value seq 'vector)) #'complement-dna-4bit))) (defmethod complement-sequence ((seq encoded-rna-sequence)) (make-instance 'encoded-rna-sequence :vector (complement-tokens (copy-seq (slot-value seq 'vector)) #'complement-rna-4bit))) (defmethod complement-sequence ((seq virtual-token-sequence)) (make-instance (class-of seq) :length (length-of seq))) (defmethod complement-sequence ((seq mapped-dna-sequence)) (declare (optimize (speed 3) (safety 1))) (with-slots ((length dxn:length) (area dxn:mmap-area)) seq (let ((cmp-seq (make-instance 'mapped-dna-sequence :length length)) (ptr (dxn:mmap-area-ptr area))) (with-slots ((cmp-area dxn:mmap-area)) cmp-seq (let ((end (1- (the fixnum length))) (cmp-ptr (dxn:mmap-area-ptr cmp-area))) (loop for i from 0 to end do (setf (cffi:mem-aref cmp-ptr :char i) (complement-dna-8bit (cffi:mem-aref ptr :char i)))))) cmp-seq))) (defmethod ncomplement-sequence ((seq encoded-dna-sequence)) (with-slots (vector) seq (loop for i from 0 below (length vector) do (setf (aref vector i) (complement-dna-4bit (aref vector i))))) seq) (defmethod ncomplement-sequence ((seq encoded-rna-sequence)) (with-slots (vector) seq (loop for i from 0 below (length vector) do (setf (aref vector i) (complement-rna-4bit (aref vector i))))) seq) (defmethod ncomplement-sequence ((seq virtual-token-sequence)) seq) (defmethod ncomplement-sequence ((seq mapped-dna-sequence)) (declare (optimize (speed 3) (safety 1))) (with-slots ((length dxn:length) (area dxn:mmap-area)) seq (let ((ptr (dxn:mmap-area-ptr area)) (end (1- (the fixnum length)))) (loop for i from 0 to end do (setf (cffi:mem-aref ptr :char i) (complement-dna-8bit (cffi:mem-aref ptr :char i)))) seq))) (defmethod reverse-complement ((seq encoded-dna-sequence)) (make-instance 'encoded-dna-sequence :vector (nreverse (complement-tokens (slot-value seq 'vector) #'complement-dna-4bit)))) (defmethod reverse-complement ((seq encoded-rna-sequence)) (make-instance 'encoded-rna-sequence :vector (nreverse (complement-tokens (slot-value seq 'vector) #'complement-rna-4bit)))) (defmethod reverse-complement ((seq dna-quality-sequence)) (with-slots (vector quality metric) seq (let ((s (make-instance 'dna-quality-sequence :vector (copy-seq vector) :quality (copy-seq quality) :metric metric))) (nreverse-complement s)))) (defmethod reverse-complement ((seq virtual-token-sequence)) (make-instance (class-of seq) :length (length-of seq))) (defmethod reverse-complement ((seq mapped-dna-sequence)) (ncomplement-sequence (reverse-sequence seq))) (defmethod nreverse-complement ((seq token-sequence)) (nreverse-sequence (ncomplement-sequence seq))) (defmethod nreverse-complement ((seq virtual-token-sequence)) seq) (defmethod search-sequence :around ((seq1 token-sequence) (seq2 token-sequence) &key from-end start1 end1 start2 end2) (declare (ignore from-end start1 start2 end1 end2)) (if (subtypep (class-of (alphabet-of seq1)) (class-of (alphabet-of seq2))) (call-next-method) nil)) (defmethod search-sequence ((seq1 encoded-vector-sequence) (seq2 encoded-vector-sequence) &key from-end (start1 0) end1 (start2 0) end2) (let ((vector1 (slot-value seq1 'vector)) (vector2 (slot-value seq2 'vector))) (search vector1 vector2 :from-end from-end :start1 start1 :start2 start2 :end1 end1 :end2 end2 :test #'eq))) (defmethod residue-frequencies ((seq encoded-vector-sequence)) (with-slots (alphabet vector) seq (let ((frequencies (make-array (size-of alphabet) :element-type 'fixnum :initial-element 0))) (loop for token across vector do (incf (aref frequencies (token-index token alphabet)))) (pairlis (copy-list (tokens-of alphabet)) (coerce frequencies 'list))))) (defmethod residue-frequencies ((seq virtual-dna-sequence)) ;; Returns 'n' x the sequence length (pairlis (list #\n) (list (length-of seq)))) (defmethod residue-frequencies ((seq virtual-rna-sequence)) ;; Returns 'n' x the sequence length (pairlis (list #\n) (list (length-of seq)))) (defmethod residue-frequencies ((seq virtual-aa-sequence)) ;; Returns 'X' x the sequence length (pairlis (list #\X) (list (length-of seq)))) (defmethod residue-frequencies ((seq mapped-dna-sequence)) (with-slots (alphabet (length dxn:length) (area dxn:mmap-area)) seq (let ((frequencies (make-array (size-of alphabet) :element-type 'fixnum :initial-element 0))) (loop for i of-type vector-index from 0 below length do (let ((token (encode-dna-4bit (code-char (cffi:mem-aref (dxn:mmap-area-ptr area) :char i))))) (incf (aref frequencies (token-index token alphabet)))))))) (defmethod residue-position (character (seq encoded-dna-sequence) &key from-end test test-not (start 0) end) (with-slots (vector) seq (%check-token-range (length vector) start end) (position character vector :from-end from-end :test test :test-not test-not :start start :end end :key #'decode-dna-4bit))) (defmethod residue-position (character (seq encoded-rna-sequence) &key from-end test test-not (start 0) end) (with-slots (vector) seq (%check-token-range (length vector) start end) (position character vector :from-end from-end :test test :test-not test-not :start start :end end :key #'decode-rna-4bit))) (defmethod residue-position (character (seq encoded-aa-sequence) &key from-end test test-not (start 0) end) (with-slots (vector) seq (%check-token-range (length vector) start end) (position character vector :from-end from-end :test test :test-not test-not :start start :end end :key #'decode-aa-7bit))) (defmethod quality-position ((quality fixnum) (seq dna-quality-sequence) &key from-end test test-not (start 0) end) (with-slots ((qvector quality)) seq (%check-token-range (length qvector) start end) (position quality qvector :from-end from-end :test test :test-not test-not :start start :end end))) (defmethod translate :before ((seq na-sequence) (code genetic-code) &key (start 0) end initiator-codon partial-codon) (declare (ignore initiator-codon)) (let* ((na-len (length-of seq)) (end (or end na-len))) (%check-token-range na-len start end) (if (and (plusp (rem (- end start) +codon-size+)) (not partial-codon)) (error 'translation-error :sequence seq :start start :end end :genetic-code code :text "the translated region includes a partial codon")))) (defmethod translate ((seq virtual-dna-sequence) (code genetic-code) &key (start 0) end (initiator-codon t) partial-codon) (declare (ignore partial-codon)) (translate-virtual seq code start end initiator-codon)) (defmethod translate ((seq virtual-rna-sequence) (code genetic-code) &key (start 0) end (initiator-codon t) partial-codon) (declare (ignore partial-codon)) (translate-virtual seq code start end initiator-codon)) (defmethod translate ((seq encoded-dna-sequence) (code genetic-code) &key (start 0) end (initiator-codon t) partial-codon) (declare (ignore partial-codon)) (translate-encoded-4bit seq code start end initiator-codon)) (defmethod translate ((seq encoded-rna-sequence) (code genetic-code) &key (start 0) end (initiator-codon t) partial-codon) (declare (ignore partial-codon)) (translate-encoded-4bit seq code start end initiator-codon)) ;;; Utility functions (defun %print-seq (seq stream) "Helper function for printing bio-sequence objects." (print-unreadable-object (seq stream :type t :identity t) (let ((len (length-of seq))) (if (<= len *sequence-print-limit*) (format stream "~s" (coerce-sequence seq 'string)) (format stream "length ~d" len))))) (defun %print-quality-seq (seq stream) "Helper function for printing bio-sequence objects." (print-unreadable-object (seq stream :type t :identity t) (with-accessors ((length length-of)) seq (with-slots (quality metric) seq (if (<= length *sequence-print-limit*) (format stream "~s ~a quality \"~a\"" (coerce-sequence seq 'string) metric (quality-string quality metric)) (format stream "~a quality, length ~d" metric length)))))) (defun quality-string (quality metric) "Wrapper for ENCODE-QUALITY that encodes QUALITY, an array of bytes representing base quality scores, as a string using an encoder appropriate for METRIC, a quality metric ( :SANGER , :SOLEXA or :ILLUMINA )." (let ((encoder (ecase metric (:sanger #'encode-phred-quality) (:solexa #'encode-solexa-quality) (:illumina #'encode-illumina-quality)))) (encode-quality quality encoder))) (defun encode-quality (quality encoder) "Encodes QUALITY, an array of bytes representing base quality scores, as a string using function ENCODER." (declare (optimize (speed 3))) (declare (type simple-octet-vector quality) (type function encoder)) (map-into (make-string (length quality) :element-type 'base-char) encoder quality)) (defun decode-quality (quality decoder) "Decodes the QUALITY, a string, as into a new array using function DECODER." (declare (optimize (speed 3))) (declare (type simple-string quality) (type function decoder)) (map-into (make-array (length quality) :element-type 'octet) decoder quality)) (defun ensure-encoded (vector encoder element-type) "If VECTOR is a string, returns an encoded token vector of element type (unsigned-byte 4) or (unsigned-byte 7) of the same length, otherwise returns VECTOR. ENCODER is the encoding function used to convert characters to small integers." (declare (optimize (speed 3))) (declare (type function encoder)) (typecase vector (simple-string (cond ((subtypep element-type 'nibble) (map-into (make-array (length vector) :element-type 'nibble) encoder vector)) ((subtypep element-type '(unsigned-byte 7)) (map-into (make-array (length vector) :element-type '(unsigned-byte 7)) encoder vector)))) (t vector))) (defun ensure-decoded-quality (quality metric) "If QUALITY is a string, returns a decoded quality vector of integers of the same length, otherwise returns QUALITY. METRIC is either :SANGER, :SOLEXA or :ILLUMINA , denoting the quality metric to be used when decoding." (if (stringp quality) (let ((decoder (ecase metric (:sanger #'decode-phred-quality) (:solexa #'decode-solexa-quality) (:illumina #'decode-illumina-quality)))) (decode-quality quality decoder)) quality)) (defun token-subsequence (tokens start end) "Returns a subsequence of TOKENS between indices START and END." (let* ((length (length tokens)) (end (or end length))) (%check-token-range (length tokens) start end) (replace (make-array (- end start) :element-type (array-element-type tokens)) tokens :start2 start :end2 end))) (defun complement-tokens (tokens comp-fn &optional (start 0) end) "Returns a complemented copy of TOKENS populated with elements from TOKENS that have been transformed by COMP-FN, starting at the first element, or index START, and continuing to the last residue, or index END." (let ((end (or end (length tokens)))) (map-into (make-array (- end start) :element-type (array-element-type tokens)) comp-fn tokens))) (defun %to-string-virtual (seq char start end token-case) (with-accessors ((length length-of)) seq (let ((end (or end length))) (%check-token-range length start end) (make-string (- end start) :element-type 'base-char :initial-element (ecase token-case ((nil) char) (:lower (char-downcase char)) (:upper char)))))) (defun %to-string-encoded (seq decoder start end token-case) (macrolet ((to-string (vec-type vec &key (speed 1)) `(prog () (declare (optimize (speed ,speed))) (declare (type ,vec-type ,vec) (type function decoder)) (let ((end (or end (length ,vec)))) (declare (type vector-index start end)) (let* ((len (- end start)) (str (make-string len :element-type 'base-char))) (when (plusp len) (copy-vector ,vec start end str 0 decoder)) (return (ecase token-case ((nil) str) (:lower str) (:upper (nstring-upcase str))))))))) (with-slots (vector) seq (typecase vector ((encoded-residues 4) (to-string (encoded-residues 4) vector :speed 3)) ((encoded-residues 7) (to-string (encoded-residues 7) vector :speed 3)) (t (to-string vector vector)))))) (declaim (inline %check-token-range)) (defun %check-token-range (length start &optional end) (declare (optimize (speed 3))) (let ((end (or end length))) (declare (type vector-index length start end)) (check-arguments (<= 0 start end length) (start end) "must satisfy (<= 0 start end ~d)" length))) (declaim (inline %aref-dna-4bit)) (defun %aref-dna-4bit (vector i) (declare (optimize (speed 3))) (declare (type (encoded-residues 4) vector)) (decode-dna-4bit (aref vector i))) (defun (setf %aref-dna-4bit) (value vector i) (declare (optimize (speed 3))) (declare (type (encoded-residues 4) vector)) (setf (aref vector i) (encode-dna-4bit value))) (declaim (inline %aref-rna-4bit)) (defun %aref-rna-4bit (vector i) (declare (optimize (speed 3))) (declare (type (encoded-residues 4) vector)) (decode-rna-4bit (aref vector i))) (defun (setf %aref-rna-4bit) (value vector i) (declare (optimize (speed 3))) (declare (type (encoded-residues 4) vector)) (setf (aref vector i) (encode-rna-4bit value))) (defun codon-start-p (base-pos) (declare (optimize (speed 3))) (declare (type vector-index base-pos)) (zerop (mod base-pos +codon-size+))) (defun codon-end-p (base-pos) (declare (optimize (speed 3))) (declare (type vector-index base-pos)) (= 2 (mod base-pos +codon-size+))) (defun translate-virtual (seq code start end initiator-codon) (let* ((na-len (length-of seq)) (end (or end na-len)) (aa-len (floor (- end start) +codon-size+))) (loop for i from start below end for j = 0 then (1+ j) for initiator = (and initiator-codon (< j +codon-size+)) with codon = (mapcar #'encode-dna-4bit '(#\n #\n #\n)) when (codon-end-p j) collect (translate-codon codon code :initiator initiator) into aa finally (return (make-aa (make-array aa-len :element-type '(unsigned-byte 7) :initial-contents aa)))))) (defun translate-encoded-4bit (seq code start end initiator-codon) (declare (optimize (speed 3))) (with-slots (vector) seq (declare (type (encoded-residues 4) vector)) (let* ((na-len (length vector)) (end (or end na-len))) (declare (type vector-index start end)) (let* ((aa-len (floor (- end start) +codon-size+)) (aa (make-array aa-len :element-type '(unsigned-byte 7)))) (loop with k = 0 for i of-type vector-index from start below end for j of-type vector-index = 0 then (1+ j) for initiator = (and initiator-codon (< j +codon-size+)) for codon = () then (if (codon-start-p j) () codon) do (progn (push (aref vector i) codon) (when (codon-end-p j) (setf (aref aa k) (translate-codon (nreverse codon) code :initiator initiator) k (1+ k))))) (make-aa aa))))) (defun maybe-subsequence (seq start &optional end) (with-accessors ((length length-of)) seq (let ((end (or end length))) (if (and (zerop start) (= length end)) seq (subsequence seq start end)))))
42,526
Common Lisp
.lisp
942
36.753715
80
0.627249
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
f1fa90b7676c309c3232f22b9d59842f4fcafda48cf3e842fe36dda72147359b
9,658
[ -1 ]
9,659
checksum.lisp
keithj_cl-genomic/src/checksum.lisp
;;; ;;; Copyright (c) 2009-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :bio-sequence) (defmethod seguid ((seq encoded-dna-sequence) &key (start 0) end) (base64:usb8-array-to-base64-string (digest-encoded-sequence seq #'decode-dna-4bit :sha1 start end))) (defmethod seguid ((seq encoded-rna-sequence) &key (start 0) end) (base64:usb8-array-to-base64-string (digest-encoded-sequence seq #'decode-rna-4bit :sha1 start end))) (defmethod seguid ((seq encoded-aa-sequence) &key (start 0) end) (base64:usb8-array-to-base64-string (digest-encoded-sequence seq #'decode-aa-7bit :sha1 start end))) (defmethod seguid ((seq mapped-dna-sequence) &key (start 0) end) (base64:usb8-array-to-base64-string (digest-mapped-sequence seq :sha1 start end))) (defmethod md5 ((seq encoded-dna-sequence) &key (start 0) end) (ironclad:byte-array-to-hex-string (digest-encoded-sequence seq #'decode-dna-4bit :md5 start end))) (defmethod md5 ((seq encoded-rna-sequence) &key (start 0) end) (ironclad:byte-array-to-hex-string (digest-encoded-sequence seq #'decode-rna-4bit :md5 start end))) (defmethod md5 ((seq encoded-aa-sequence) &key (start 0) end) (ironclad:byte-array-to-hex-string (digest-encoded-sequence seq #'decode-aa-7bit :md5 start end))) (defmethod md5 ((seq mapped-dna-sequence) &key (start 0) end) (ironclad:byte-array-to-hex-string (digest-mapped-sequence seq :md5 start end))) (defun digest-encoded-sequence (seq decoder digest start &optional end) (with-slots (vector) seq (let ((end (or end (length vector))) (stream (ironclad:make-digesting-stream digest))) (loop for i of-type fixnum from start below end do (stream-write-byte stream (char-code (char-upcase (funcall decoder (aref vector i)))))) (ironclad:produce-digest stream)))) (defun digest-mapped-sequence (seq digest start &optional end) (declare (optimize (speed 3))) (with-slots ((length dxn:length) (area dxn:mmap-area)) seq (let ((end (or end length)) (ptr (dxn:mmap-area-ptr area))) (if (dxn:mmap-area-live-p area) ; Only access residues if mapped (let ((stream (ironclad:make-digesting-stream digest))) (loop for i of-type fixnum from start below end do (stream-write-byte stream (char-code (char-upcase (code-char (cffi:mem-aref ptr :char i)))))) (ironclad:produce-digest stream))))))
3,310
Common Lisp
.lisp
69
41.84058
77
0.672344
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
761e1bbf29354af14ff16b6a38dec94f83d1f7c8c1662edce3f5bcfb90ed5fae
9,659
[ -1 ]
9,660
generics.lisp
keithj_cl-genomic/src/generics.lisp
;;; ;;; Copyright (c) 2007-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :bio-sequence) ;;; identity-mixin generics (defgeneric anonymousp (object) (:documentation "Returns T if OBJECT is anonymous, that is, has an identifier of NIL.")) ;;; bio-sequence generics (defgeneric simplep (bio-sequence) (:documentation "Returns T if BIO-SEQUENCE contains no ambiguous residues, or NIL otherwise.")) (defgeneric ambiguousp (bio-sequence) (:documentation "Returns T if BIO-SEQUENCE contains ambiguous residues, or NIL otherwise.")) (defgeneric size-of (alphabet) (:documentation "Returns the number of tokens in ALPHABET as a fixnum.")) (defgeneric memberp (char alphabet) (:documentation "Returns T if CHAR is a member token of ALPHABET, or NIL otherwise.")) (defgeneric subsumesp (token1 token2 alphabet) (:documentation "Returns T if TOKEN1 subsumes TOKEN2 using IUPAC ambiguities, where both tokens belong to ALPHABET.")) (defgeneric token-index (token alphabet) (:documentation "Returns the integer position of TOKEN in ALPHABET.")) (defgeneric random-token-of (alphabet) (:documentation "Returns a random token from ALPHABET, with an equal probability of selecting each token.")) (defgeneric enum-ambiguity (char alphabet) (:documentation "Returns a list of the ambiguity characters represented by CHAR in ALPHABET.")) (defgeneric strand-designator-p (object) (:documentation "Returns T if OBJECT is one of the supported nucleic acid sequence strand designators, or NIL otherwise. The strand designators are: String Character Symbol Integer Forward strand + + :forward 1 Reverse strand - - :reverse -1 Unknown strand ? ? :unknown 0")) (defgeneric decode-strand (strand-designator &key strict) (:documentation "Returns a {defclass sequence-strand} given STRAND-DESIGNATOR, or NIL if the designator is not recognised. If STRICT is set to T an invalid designator will raise an error.")) (defgeneric strand= (sequence-strand1 sequence-strand2) (:documentation "Returns T if SEQUENCE-STRAND1 can be shown to be the same as SEQUENCE-STRAND2, or NIL otherwise. If either strand is unknown, the result will be NIL.")) (defgeneric strand-equal (sequence-strand1 sequence-strand2) (:documentation "Returns T if SEQUENCE-STRAND1 may be the same as SEQUENCE-STRAND2, or NIL otherwise. If either strand is unknown, the result will be T.")) (defgeneric complement-strand (sequence-strand) (:documentation "Returns the complement strand to SEQUENCE-STRAND. The complement of the unknown strand is the unknown strand.")) (defgeneric complementp (sequence-strand1 sequence-strand2) (:documentation "Returns T if SEQUENCE-STRAND1 is the complement of SEQUENCE-STRAND2, or NIL otherwise.")) (defgeneric forward-strand-p (sequence-strand) (:documentation "Returns T if SEQUENCE-STRAND is the forward strand, or NIL otherwise.")) (defgeneric reverse-strand-p (sequence-strand) (:documentation "Returns T if SEQUENCE-STRAND is the reverse strand, or NIL otherwise.")) (defgeneric unknown-strand-p (sequence-strand) (:documentation "Returns T if SEQUENCE-STRAND is the unknown strand, or NIL otherwise.")) (defgeneric element-of (bio-sequence index) (:documentation "Returns the element at INDEX of BIO-SEQUENCE. As these are interbase coordinates, a residue actually occupies a range from INDEX to 1+ INDEX. However, as the end index of the range is always 1+ the start index, it is implied for convenience. The first base of a sequence is therefore index 0 to index 1, with 0 being the argument passed to the INDEX-OF method.")) (defgeneric (setf element-of) (value bio-sequence index) (:documentation "Sets the residue at INDEX of BIO-SEQUENCE to VALUE.")) (defgeneric virtualp (bio-sequence) (:documentation "Returns T if BIO-SEQUENCE has no concrete token sequence representation, merely a length, or NIL otherwise.")) (defgeneric single-stranded-p (nucleic-acid-sequence) (:documentation "Returns T if NUCLEIC-ACID-SEQUENCE is single-stranded, or NIL otherwise.")) (defgeneric double-stranded-p (nucleic-acid-sequence) (:documentation "Returns T if NUCLEIC-ACID-SEQUENCE is double-stranded, or NIL otherwise.")) (defgeneric num-gaps-of (bio-sequence &key start end) (:documentation "")) (defgeneric residue-frequencies (bio-sequence) (:documentation "")) (defgeneric coerce-sequence (bio-sequence result-type &key start end) (:documentation "Coerces all or part of BIO-SEQUENCE to RESULT-TYPE. RESULT-TYPE may be 'string or another bio-sequence class. For example an object of class {defclass dna-sequence} may be coerced to an {defclass rna-sequence} and vice versa. The coerced sequence starts at the first residue, or index START, and continuing to the last residue, or index END.")) (defgeneric reverse-sequence (bio-sequence) (:documentation "Returns a new bio-sequence with a token-seq that is a reversed copy of that of BIO-SEQUENCE.")) (defgeneric nreverse-sequence (bio-sequence) (:documentation "Returns BIO-SEQUENCE, destructively modified such that its token-seq is reversed.")) (defgeneric complement-sequence (nucleic-acid-sequence) (:documentation "Returns a new nucleic-acid-sequence with a token-seq that is a complemented copy of that of BIO-SEQUENCE.")) (defgeneric ncomplement-sequence (nucleic-acid-sequence) (:documentation "Returns NUCLEIC-ACID-SEQUENCE, destructively modified such that its token-seq is complemented.")) (defgeneric reverse-complement (nucleic-acid-sequence) (:documentation "Returns a new nucleic-acid-sequence that is the reverse-complement of NUCLEIC-ACID-SEQUENCE. If the argument is a {defclass na-sequence-interval} this is accomplished by returning a copy at the corresponding position on the complementary strand of the reference sequence.")) (defgeneric nreverse-complement (nucleic-acid-sequence) (:documentation "Returns NUCLEIC-ACID-SEQUENCE, destructively modified such that its token-seq is reverse-complemented. If the argument is a {defclass na-sequence-interval} this is accomplished by moving it to the corresponding position on the complementary strand of the reference sequence.")) (defgeneric subsequence (bio-sequence start &optional end) (:documentation "Subsequence creates a bio-sequence that is a copy of the subsequence of BIO-SEQUENCE bounded by START and END.")) (defgeneric search-sequence (bio-sequence1 bio-sequence2 &key from-end start1 start2 end1 end2) (:documentation "Searches BIO-SEQUENCE2 for a subsequence that matches BIO-SEQUENCE1.")) (defgeneric hamming-distance (bio-sequence1 bio-sequence2 &key start1 start2 end1 end2) (:documentation "Returns the Hamming distance between BIO-SEQUENCE1 and BIO-SEQUENCE2. Sequences or sequence ranges must be the same length.")) (defgeneric hamming-search (bio-sequence1 bio-sequence2 &key start1 start2 end1 end2 max-distance) (:documentation "Searches BIO-SEQUENCE2 for a subsequence that is up to MAX-DISTANCE Hamming distance from BIO-SEQUENCE1.")) (defgeneric cumulative-lengths (ranges) (:documentation "Returns a list of integers which are the cumulative total lengths of RANGES.")) (defgeneric translate (nucleic-acid-sequence genetic-code &key start end initiator-codon partial-codon) (:documentation "Translates a region of NUCLEIC-ACID-SEQUENCE, bounded by START and END, using GENETIC-CODE. If INITIATOR-CODON is T, the region is must begin with a recognised initiator codon, according to GENETIC-CODE. If PARTIAL-CODON is T, the last codon in the region may be partial and is padded with fully ambiguous bases at its end.")) (defgeneric translate-codon (codon genetic-code &key initiator) (:documentation "Returns an amino acid for CODON using GENETIC-CODE. An implementation should consider ambiguities in CODON, effectively enumerating all possible unambiguous codons from it, translating them and unifying the result into a single, possibly ambiguous amino acid.")) (defgeneric start-codon-p (codon genetic-code) (:documentation "Returns T if CODON may be a start codon in GENETIC-CODE.")) (defgeneric term-codon-p (codon genetic-code) (:documentation "Returns T if CODON may be a terminator in GENETIC-CODE.")) (defgeneric residue-position (character bio-sequence &key from-end test test-not start end) (:documentation "")) (defgeneric quality-position (quality bio-sequence &key from-end test test-not start end) (:documentation "")) (defgeneric seguid (bio-sequence &key start end) (:documentation "Returns the SEquence Globally Unique IDentifier or SEGUID string for BIO-SEQUENCE, between START and END. A SEGUID is essentially a base64-encoded SHA-1 hash of the uppercase sequence string. See PMID:16858731.")) (defgeneric md5 (bio-sequence &key start end) (:documentation "Returns the MD5 checksum of the uppercase sequence string of BIO-SEQUENCE, between START and END.")) ;;; bio-sequence io generics (defgeneric begin-object (parser) (:documentation "Signals to PARSER the beginning of a new object. The parser may use this information to discard accumulated state from the previous object.")) (defgeneric object-relation (parser relation value) (:documentation "Signals to PARSER that RELATION exits between the current object and some VALUE.")) (defgeneric object-identity (parser identity) (:documentation "Signals to PARSER that the current object has IDENTITY.")) (defgeneric object-description (parser description) (:documentation "Signals to PARSER that the current object has DESCRIPTION.")) (defgeneric object-alphabet (parser alphabet) (:documentation "Signals to PARSER that the current object has residues of ALPHABET.")) (defgeneric object-residues (parser residues) (:documentation "Signals to PARSER that the current object has bio-sequence RESIDUES. Multiple calls to this method may be used to accumulate sequence residues.")) (defgeneric object-quality (parser quality) (:documentation "Signals to parser that the current object has bio-sequence residue QUALITY. Multiple calls to this method may be used to accumulate quality information.")) (defgeneric end-object (parser) (:documentation "Signals to PARSER the end of the current object. The method must return T if the accumulated state of the current object is valid, or NIL otherwise. If PARSER is constructing a CLOS object, the object must be returned by this method.")) (defgeneric make-seq-input (source format &key alphabet parser &allow-other-keys) (:documentation "Returns a generator function of arity 1 that uses PARSER to read a single bio-sequence of ALPHABET, in FORMAT, from SOURCE. The standard generator interface functions, CURRENT, NEXT and HAS-MORE-P may be used in operations on the returned generator.")) (defgeneric make-seq-output (dest format &key token-case &allow-other-keys) (:documentation "Returns a consumer function of arity 1 that accepts a bio-sequence and writes a representation in FORMAT to DEST. The TOKEN-CASE keyword is used to override the default character case for printing sequence residues, which is lowercase for DNA or RNA and uppercase for amino acids. The standard consumer interface function CONSUME may be used in operations on the returned consumer.")) (defgeneric make-bio-sequence (parser) (:documentation "Returns a new bio-sequence created from the state accumulated by PARSER.")) (defgeneric make-interval-input (sequence) (:documentation "Returns a generator function that will return elements of SEQUENCE, followed by a sentinel element.")) (defgeneric make-interval (bio-sequence &rest args) (:documentation "Returns a new interval on BIO-SEQUENCE.")) (defgeneric has-sequence-p (stream format &key alphabet) (:documentation "Returns T if a bio-sequence may be read from STREAM.")) ;;; Could all the read-XXXX-sequence and write-XXXX-sequence functions ;;; be replaced sensibly by read-bio-sequence and write-bio-sequence ;;; functions that dispatch on a format object? (defgeneric read-pure-sequence (stream alphabet parser) (:documentation "Reads a single pure format record of ALPHABET from STREAM using PARSER.")) (defgeneric write-pure-sequence (bio-sequence stream &key token-case) (:documentation "Writes BIO-SEQUENCE to STREAM in pure format. The TOKEN-CASE keyword is used to override the default character case for printing sequence residues, which is lowercase for DNA or RNA and uppercase for amino acids.")) (defgeneric read-raw-sequence (stream alphabet parser) (:documentation "Reads a single raw format record of ALPHABET from STREAM using PARSER.")) (defgeneric write-raw-sequence (bio-sequence stream &key token-case) (:documentation "Writes BIO-SEQUENCE to STREAM in raw format. The TOKEN-CASE keyword is used to override the default character case for printing sequence residues, which is lowercase for DNA or RNA and uppercase for amino acids.")) (defgeneric read-fasta-sequence (stream alphabet parser) (:documentation "Reads a single Fasta format record of ALPHABET from STREAM using PARSER.")) (defgeneric write-fasta-sequence (bio-sequence stream &key token-case) (:documentation "Writes BIO-SEQUENCE to STREAM in Fasta format. The TOKEN-CASE keyword is used to override the default character case for printing sequence residues, which is lowercase for DNA or RNA and uppercase for amino acids.")) (defgeneric read-fastq-sequence (stream alphabet parser) (:documentation "Reads a single Fastq format record of ALPHABET from STREAM using PARSER.")) (defgeneric write-fastq-sequence (bio-sequence stream &key token-case metric) (:documentation "Writes BIO-SEQUENCE to STREAM in Fastq format using quality METRIC (e.g. :solexa , :sanger, :illumina ). The TOKEN-CASE keyword is used to override the default character case for printing sequence residues, which is lowercase for DNA or RNA and uppercase for amino acids.")) (defgeneric split-sequence-file (filespec format pathname-gen &key chunk-size) (:documentation "Splits sequence file identified by FILESPEC into automatically named files, each containing up to CHUNK-SIZE records. The new file names are created by the function PATHNAME-GEN. See dxi:pathname-generator and dxi:pathname-extender.")) (defgeneric align-local (seqm seqn subst-fn &key gap-open gap-extend band-centre band-width alignment) (:documentation "Performs Smith Waterman sequence alignment using affine gap penalties. The affine gap scoring is expressed as penalties, that is to say GAP-OPEN and GAP-EXTEND should be negative values. The alignment may be banded to prune the search space. Arguments: - seqm (object): A sequence to be aligned. - seqn (object): A sequence to be aligned. - subst-fn (function): A substitution function that accepts two sequence elements as arguments and returns a single-float substitution score. Key: - gap-open (single-float): The gap opening score, a negative value. - gap-extend (single-float): The gap extension score, a negative value. - band-centre (fixnum): The band centre for banded alignments. This defaults to 0, the main diagonal. The desired band may be calculated by subtracting a j coordinate from its corresponding i coordinate. - band-width (fixnum): The band width for banded alignments. This defaults to most-positive-fixnum so that the search space is not pruned. - alignment (generalized boolean): T if an alignment is to be calculated. Returns: - A single-float alignment score. - An alignment object, or NIL.")) (defgeneric align-local-ksh (seqm seqn subst-fn &key gap-open gap-extend k alignment) (:documentation "Performs Smith Waterman sequence alignment using affine gap penalties with a kmer seeding heuristic. The affine gap scoring is expressed as penalties, that is to say GAP-OPEN and GAP-EXTEND should be negative values. The alignment is seeded with kmers of length K and the alignment is banded to include all such kmers. Arguments: - seqm (object): A sequence to be aligned. - seqn (object): A sequence to be aligned. - subst-fn (function): A substitution function that accepts two sequence elements as arguments and returns a single-float substitution score. Key: - gap-open (single-float): The gap opening penalty. - gap-extend (single-float): The gap extension penalty. - k (fixnum): The seed kmer length. - alignment (generalized boolean): T if an alignment is to be calculated. Returns: - A single-float alignment score. - An alignment object, or NIL.")) (defgeneric begin-term (parser) (:documentation "")) (defgeneric begin-typedef (parser) (:documentation "")) (defgeneric begin-instance (parser) (:documentation "")) (defgeneric end-section (parser) (:documentation "")) (defgeneric tag-value (parser tag value) (:documentation ""))
17,816
Common Lisp
.lisp
346
48.800578
77
0.776448
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
3a5da15854470f5d60b00ac9ca81f483337004ea80ed3bd81441e8d65eded92f
9,660
[ -1 ]
9,661
conditions.lisp
keithj_cl-genomic/src/conditions.lisp
;;; ;;; Copyright (c) 2007-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :bio-sequence) (define-condition bio-sequence-error (error) () (:documentation "The parent type of all bio-sequence error conditions.")) (define-condition bio-sequence-warning (warning) () (:documentation "The parent type of all bio-sequence warning conditions.")) ;; (define-condition bio-sequence-io-error (io-error ;; bio-sequence-error) ;; ((text :initform nil ;; :initarg :text ;; :reader text-of ;; :documentation "Error message text.")) ;; (:report (lambda (condition stream) ;; (format stream "IO error~@[: ~a~]" ;; (text-of condition)))) ;; (:documentation "An error that is raised when performing stream IO ;; on bio-sequences.")) ;; (define-condition bio-sequence-parse-error (general-parse-error ;; bio-sequence-io-error) ;; ((text :initform nil ;; :initarg :text ;; :reader text-of ;; :documentation "Error message text.")) ;; (:report (lambda (condition stream) ;; (format stream "IO error~@[: ~a~]" ;; (text-of condition)))) ;; (:documentation "An error that is raised when performing stream IO ;; on bio-sequences.")) (define-condition bio-sequence-op-error (invalid-operation-error bio-sequence-error simple-text-condition) () (:report (lambda (condition stream) (format stream "Invalid bio-sequence operation~@[: ~a~]" (message-of condition)))) (:documentation "An error that is raised when performing operations on bio-sequences.")) (define-condition initiator-codon-error (bio-sequence-op-error) ((codon :initform nil :initarg :codon :reader codon-of :documentation "The invalid codon.") (genetic-code :initform nil :initarg :genetic-code :reader genetic-code-of :documentation "The genetic code used to translate.")) (:report (lambda (condition stream) (format stream "Codon ~a is not an initiator in ~a" (codon-of condition) (genetic-code-of condition)))) (:documentation "An error that is raised when attempting to translate a non-initiator codon as an initiator.")) (define-condition translation-error (bio-sequence-op-error) ((seq :initform nil :initarg :sequence :reader sequence-of :documentation "The translated sequence.") (start :initform nil :initarg :start :reader start-of :documentation "The translation start position.") (end :initform nil :initarg :end :reader end-of :documentation "The translation end position.") (genetic-code :initform nil :initarg :genetic-code :reader genetic-code-of :documentation "The genetic code used to translate.")) (:report (lambda (condition stream) (format stream "Invalid translation of ~a~@[: ~a~]" (sequence-of condition) (message-of condition)))) (:documentation "An error that is raised when attempting an invalid translation of a sequence."))
4,106
Common Lisp
.lisp
95
37.126316
75
0.625281
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
823d7795058bfc3f8fcaaa6be837d42bca8cd5eaa25a7e359b6e296b4d5c012d
9,661
[ -1 ]
9,662
bio-sequence-classes.lisp
keithj_cl-genomic/src/bio-sequence-classes.lisp
;;; ;;; Copyright (c) 2007-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :bio-sequence) (defclass sequence-strand () ((name :initarg :name :reader name-of :documentation "The strand name.") (symbol-of :initarg :symbol :reader symbol-of :documentation "The Lisp symbol representing the strand.") (token :initarg :token :reader token-of :documentation "The token representing the strand.") (number :initarg :number :reader number-of :documentation "The number representing the strand.")) (:documentation "The strand of a nucleotide sequence.")) (defvar *forward-strand* (make-instance 'sequence-strand :name "forward" :symbol :forward :token #\+ :number 1) "The forward nucleotide strand.") (defvar *reverse-strand* (make-instance 'sequence-strand :name "reverse" :symbol :reverse :token #\- :number -1) "The reverse nucleotide strand.") (defvar *unknown-strand* (make-instance 'sequence-strand :name "unknown" :symbol :unknown :token #\? :number nil) "An unknown nucleotide strand.") (defclass stranded-mixin () ((strand :type sequence-strand :initform *unknown-strand* :initarg :strand :reader strand-of :documentation "The nucleotide strand."))) (defclass identity-mixin () ((identity :initform nil :initarg :identity :accessor identity-of :documentation "A temporary, locally unique identifier.")) (:documentation "A mixin which allows assignment of a temporary local identifier to an object. An identity of NIL signifies an anonymous object.")) (defclass description-mixin () ((description :initform nil :initarg :description :accessor description-of :documentation "A free text description.")) (:documentation "A mixin which allows assignment of a free text description to an object.")) (defclass quality-mixin () ((metric :initform (error "A metric is required.") :initarg :metric :accessor metric-of :documentation "A description of the quality metric measured by the quality values. For example, p-value, Phred score or Illumina score. This should be changed to a controlled vocabulary or enumeration.") (quality :initform (error "Quality values are required.") :initarg :quality :accessor quality-of :documentation "The array of quality values which should be the same length as the array of residues.")) (:documentation "A mixin with support for bio-sequences that have a numeric quality value for each residue.")) (defclass token-sequence () ((alphabet :initarg :alphabet :reader alphabet-of :documentation "The alphabet of the sequence.")) (:documentation "A sequence of tokens belonging to an alphabet.")) (defclass virtual-token-sequence (token-sequence) ((length :initform 0 :initarg :length :accessor length-of :documentation "The length of the sequence.")) (:documentation "A token sequence whose tokens are not explicitly represented.")) (defclass encoded-token-sequence (token-sequence) () (:documentation "A token sequence whose tokens have been transformed to a representation other than characters, typically small integers.")) (defclass encoded-vector-sequence (encoded-token-sequence) ((vector :initform (make-array 0 :element-type 'fixnum) :initarg :vector :accessor vector-of :documentation "The token vector of the sequence.")) (:documentation "An encoded sequence whose tokens are stored in an in-memory vector.")) (defclass bio-sequence () () (:documentation "A biological sequence.")) (defclass na-sequence (bio-sequence) ((num-strands :initform 2 :initarg :num-strands :accessor num-strands-of :documentation "The number of sequence strands.")) (:documentation "A nucleic acid sequence.")) (defclass dna-sequence (na-sequence) ((alphabet :allocation :class :initform *dna*)) (:documentation "A concrete DNA sequence comprising IUPAC ambiguity bases.")) (defclass rna-sequence (na-sequence) ((alphabet :allocation :class :initform *rna*)) (:documentation "A concrete RNA sequence comprising IUPAC ambiguity bases.")) (defclass aa-sequence (bio-sequence) ((alphabet :allocation :class :initform *aa*))) (defclass encoded-dna-sequence (dna-sequence encoded-vector-sequence identity-mixin description-mixin) ()) (defclass encoded-rna-sequence (rna-sequence encoded-vector-sequence identity-mixin description-mixin) ()) (defclass dna-quality-sequence (encoded-dna-sequence quality-mixin identity-mixin description-mixin) ()) (defclass virtual-dna-sequence (dna-sequence virtual-token-sequence identity-mixin description-mixin) ()) (defclass virtual-rna-sequence (rna-sequence virtual-token-sequence identity-mixin description-mixin) ()) (defclass encoded-aa-sequence (aa-sequence encoded-vector-sequence identity-mixin description-mixin) ()) (defclass virtual-aa-sequence (aa-sequence virtual-token-sequence identity-mixin description-mixin) ()) (defclass mapped-dna-sequence (dna-sequence token-sequence dxn:mapped-vector-char identity-mixin description-mixin) ()) ;; Also need to add circularity
6,456
Common Lisp
.lisp
152
35.414474
73
0.676916
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
6ca58e41b0c99954c7c682a654538d3c7cd81fc0c03c567648f7d36639225aa6
9,662
[ -1 ]
9,663
fjoin.lisp
keithj_cl-genomic/src/fjoin.lisp
;;; ;;; Copyright (c) 2009-2011 Keith James. All rights reserved. ;;; ;;; This file is part of cl-genomic. ;;; ;;; 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 :bio-sequence) (defparameter *sentinel* (make-instance 'na-sequence-interval :lower most-positive-fixnum :upper most-positive-fixnum) "The sentinel interval used by the fjoin algorithm.") (defun sentinelp (interval) "Returns T if INTERVAL is the sentinel, or NIL otherwise." (eql *sentinel* interval)) (defmethod make-interval-input ((vector vector)) "Returns a new generator that will return the elements of VECTOR, followed by *SENTINEL*." (let ((length (length vector)) (i 0) (current nil)) (defgenerator (more t) (next (let ((elt (if (< i length) (aref vector i) *sentinel*))) (prog1 elt (incf i) (setf current elt)))) (current current)))) (defmacro with-interval-input ((var obj) &body body) `(let ((,var (make-interval-input ,obj))) ,@body)) (defgeneric compare-intervals (query-intervals reference-intervals exclude test callback) (:documentation "Compares QUERY-INTERVALS with REFERENCE-INTERVALS using he pairwise fjoin alogorithm described in Richardson, J. E. (2006) Journal of Computational Biology 13 (8), 1457-1464. Arguments: - query-intervals (sequence intervals): A sequence of intervals. - reference-intervals (sequence intervals): A sequence of intervals. - exclude (function): A function of two arguments used to test intervals for eviction from the working window. In the fjoin paper this is leftOf. The cl-genomic equivalent is {defun beforep} . - test (function): A function of two arguments used to test intervals to determine whether they are related. This function should return T if the realtionship holds, or NIL otherwise. In the fjoin paper this is overlaps. The cl-genomic equivalent is {defun inclusive-overlapsp} . - callback (function): A function of two arguments that is called whenever a pair of intervals are found to relate by function TEST. CALLBACK is called with the two intervals as arguments. Returns: - T.")) (defmethod compare-intervals ((x vector) (y vector) exclude test callback) (with-interval-input (ix x) (with-interval-input (iy y) (fjoin ix iy exclude test callback)))) (defun fjoin (ix iy exclude test callback) "This function implements the pairwise fjoin alogorithm described in Richardson, J. E. (2006) Journal of Computational Biology 13 (8), 1457-1464. All arguments are functions in order to allow extension beyond simple overlap detection. For example, detecting degree of overlap in terms of percentage length or number of bases, degree of separation or strand relationships. Extension from pairwise relationships to a full n-ary fjoin is planned. This implementation is full of side-effects because it's a very literal translation of the pseudocode in the fjoin paper. This is intentional. Arguments: - ix (function): An iterator function that returns {defclass bio-sequence-interval} s in the order of their position on a reference sequence, until exhausted when it returns the sentinel interval. - iy (function): An iterator function that returns {defclass bio-sequence-interval} s in the order of their position on a reference sequence, until exhausted when it returns the sentinel interval. - exclude (function): A function of two arguments used to test intervals for eviction from the working window. In the fjoin paper this is leftOf. The cl-genomic equivalent is {defun beforep} . - test (function): A function of two arguments used to test intervals to determine whether they are related. This function should return T if the realtionship holds, or NIL otherwise. In the fjoin paper this is overlaps. The cl-genomic equivalent is {defun inclusive-overlapsp} . - callback (function): A function of two arguments that is called whenever a pair of intervals are found to relate by function TEST. CALLBACK is called with the two intervals as arguments. Returns: - T." (let ((wx (make-queue)) (wy (make-queue))) (loop with x = (next ix) with y = (next iy) while (not (and (sentinelp x) (sentinelp y))) do (cond ((<= (lower-of x) (lower-of y)) (scan x wx y wy exclude test callback) (setf x (next ix))) (t (scan y wy x wx exclude test callback) (setf y (next iy))))) t)) (defun scan (f wf g wg exclude test &optional callback) "Window-scanning part of the fjoin algorithm. Arguments: - f (interval): The current interval in the lagging stream. - wf (queue): The window across the lagging stream. - g (interval): The current interval in the leading stream. - wf (queue): The window across the leading stream. - exclude (function): A function of two arguments used to test intervals for eviction from the working window. - test (function): A function of two arguments used to test intervals to determine whether they are related. This function should return T if the realtionship holds, or NIL otherwise. Optional: - callback (function): A function of two arguments that is called whenever a pair of intervals are found to relate by function TEST. CALLBACK is called with the two intervals as arguments." (unless (funcall exclude f g) (queue-enqueue f wf)) (loop for x in (queue-head (queue-dequeue-if (lambda (y) (funcall exclude y f)) wg)) do (when (and callback (funcall test x f)) (funcall callback x f))))
6,445
Common Lisp
.lisp
140
40.857143
74
0.70976
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
0b726511f8cdd51f57ce52d41b98b03f9c532f0568d6ca55b93e1e6d1d57e43c
9,663
[ -1 ]
9,664
nucleic-acid-thermodynamics.lisp
keithj_cl-genomic/src/nucleic-acid-thermodynamics.lisp
;; Allawi and SantaLucia (1997) Biochemistry 36, 10581-10594 ;; ;; 1M NaCl ;; ;; AA/TT, -7.9 ± 0.2, -22.2 ± 0.8 ;; AT/TA, -7.2 ± 0.7, -20.4 ± 2.4 ;; TA/AT, -7.2 ± 0.9, -21.3 ± 2.4 ;; CA/GT, -8.5 ± 0.6, -22.7 ± 2.0 ;; GT/CA, -8.4 ± 0.5, -22.4 ± 2.0 ;; CT/GA, -7.8 ± 0.6, -21.0 ± 2.0 ;; GA/CT, -8.2 ± 0.6, -22.2 ± 1.7 ;; CG/GC, -10.6 ± 0.6, -27.2 ± 2.6 ;; GC/CG, -9.8 ± 0.4, -24.4 ± 2.0 ;; GG/CC, -8.0 ± 0.9, -19.9 ± 1.8 ;; IGC, 0.1 ± 1.1, -2.8 ± 0.2 ;; IAT, 2.3 ± 1.3, 4.1 ± 0.2 ;; (probe-sequence target-sequence enthalpy entropy) ;; probe-sequence: 5'-3' ;; target-sequence: 5'-3' ;; enthalpy: (value error) delta-H in cal mol-1 ;; entropy: (value error) delta-S in cal mol-1 K-1 (defpackage na-therm (:use :common-lisp)) (in-package :na-therm) (defconstant *molar-gas-constant* 1.987 "Molar gas constant in cal mol-1.") (defconstant *absolute-zero-celcius* -273.15 "Zero Kelvin expressed in Celcius.") (defvar *thermodynamic-parameters* '((allawi-santalucia-1997 ("AA" -7900 -22.2) ("AC" -8400 -22.4) ("AG" -7800 -21.0) ("AT" -7200 -20.4) ("CA" -8500 -22.7) ("CC" -8000 -19.9) ("CG" -10600 -27.2) ("CT" -7800 -21.0) ("GA" -8200 -22.2) ("GC" -9800 -24.4) ("GG" -8000 -19.9) ("GT" -8400 -22.4) ("TA" -7200 -21.3) ("TC" -8200 -22.2) ("TG" -8500 -22.7) ("TT" -7900 -22.2) ("G" 100 -2.8) ("C" 100 -2.8) ("A" 2300 4.1) ("T" 2300 4.1)))) (defvar *thermodynamic-parameter-tables* (make-hash-table)) (defun celcius-to-kelvin (celcius) (+ celcius (- *absolute-zero-celcius*))) (defun kelvin-to-celcius (kelvin) (+ kelvin *absolute-zero-celcius*)) (defun get-thermodynamic-parameters (name) (unless (assoc name *thermodynamic-parameters*) (error "No such parameters as ~a~%" name)) (multiple-value-bind (table cached) (gethash name *thermodynamic-parameter-tables*) (unless cached (setf table (setf (gethash name *thermodynamic-parameter-tables*) (make-hash-table :test 'equal))) (dolist (datum (cdr (assoc name *thermodynamic-parameters*))) (setf (gethash (first datum) table) (rest datum)))) table)) (defun order-2-with-termini (str) (let ((len (length str))) (if (zerop len) nil (append (cons (subseq str 0 1) (order-n str 2)) (cons (subseq str (1- len) len) nil))))) (defun order-n (str n) (let ((len (length str))) (if (< len n) nil (loop for i from 0 to (- len n) collect (subseq str i (+ i n)))))) (defun calculate-nn-parameters (str name) (let* ((tm-params (get-thermodynamic-parameters name)) (param-pairs (mapcar #'(lambda (probe) (gethash probe tm-params)) (order-2-with-termini str)))) (values (reduce #'+ param-pairs :key #'first) (reduce #'+ param-pairs :key #'second)))) (defun calculate-melting-temp (sequence seq-conc na-conc &key (name 'allawi-santalucia-1997) (f 4)) (let ((phosphates (1- (length sequence)))) (multiple-value-bind (enthalpy entropy) (calculate-nn-parameters sequence name) (kelvin-to-celcius (/ enthalpy (+ (+ entropy (* 0.368 phosphates (log na-conc))) (* *molar-gas-constant* (log (/ seq-conc f))))))))) (defun read-sequences (filename) (with-open-file (stream filename) (do ((line (read-line stream nil) (read-line stream nil))) ((null line)) (let ((first-tab (position #\tab line)) (second-tab (position #\tab line :from-end t))) (format t "~a ~a ~a ~a~%" (subseq line 0 first-tab) (subseq line (1+ first-tab) second-tab) (subseq line second-tab) (calculate-melting-temp (subseq line (1+ first-tab) second-tab) 0.000000001 0.05))))))
4,055
Common Lisp
.lisp
108
30.175926
82
0.550115
keithj/cl-genomic
17
2
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
71b543c26806057e274161cf5a5780bf32653ec4916924500ad7a71126ab753c
9,664
[ -1 ]