home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / share / audacity / nyquist / xm.lsp < prev   
Encoding:
Text File  |  2010-09-21  |  77.3 KB  |  2,333 lines

  1. ;; X-Music, inspired by Commmon Music
  2.  
  3. #|
  4. PATTERN SEMANTICS
  5.  
  6. Patterns are objects that are generally accessed by calling 
  7. (next pattern). Each call returns the next item in an 
  8. infinite sequence generated by the pattern. Items are 
  9. organized into periods. You can access all (remaining) 
  10. items in the current period using (next pattern t).
  11.  
  12. Patterns mark the end-of-period with +eop+, a distinguished
  13. atom. The +eop+ markers are filtered out by the next function
  14. but returned by the :next method.
  15.  
  16. Pattern items may be patterns. This is called a nested
  17. pattern.  When patterns are nested, you return a period 
  18. from the innermost pattern, i.e. traversal is depth-first. 
  19. This means when you are using something like random, you
  20. have to remember the last thing returned and keep getting
  21. the next element from that thing until you see +eop+; 
  22. then you move on. It's a bit more complicated because 
  23. a pattern advances when its immediate child pattern
  24. finishes a cycle, but +eop+ is only returned from the
  25. "leaf" patterns.
  26.  
  27. With nested patterns, i.e. patterns with items that
  28. are patterns, the implementation requires that
  29. *all* items must be patterns. The application does
  30. *not* have to make every item a pattern, so the
  31. implementation "cleans up" the item list: Any item
  32. that is not a pattern is be replaced with a cycle
  33. pattern whose list contains just the one item.
  34.  
  35. EXPLICIT PATTERN LENGTH
  36.  
  37. Pattern length may be given explicitly by a number or
  38. a pattern that generates numbers. Generally this is 
  39. specified as the optional :for keyword parameter when
  40. the pattern is created. If the explicit pattern
  41. length is a number, this will be the period length,
  42. overriding all implicit lengths. If the pattern length
  43. is itself a pattern, the pattern is evaluated every 
  44. period to determine the length of the next period,
  45. overriding any implicit length. 
  46.  
  47. IMPLEMENTATION
  48.  
  49. There are 3 ways to determine lengths: 
  50. 1) The length is implicit. The length can be
  51. computed (at some point) and turned into an
  52. explicit length.
  53.  
  54. 2) The length is explicit. This overrides the
  55. implicit length. The explicit length is stored as
  56. a counter that tells how many more items to generate
  57. in the current period.
  58.  
  59. 3) The length can be generated by a pattern.
  60. The pattern is evaluated to generate an explicit
  61. length.
  62.  
  63. So ultimately, we just need a mechanism to handle
  64. explicit lengths. This is incorporated into the
  65. pattern-class. The pattern-class sends :start-period
  66. before calling :advance when the first item in a
  67. period is about to be generated. Also, :next returns
  68. +eop+ automatically at the end of a period.
  69.  
  70. Because evaluation is "depth first," i.e. we 
  71. advance to the next top-level item only after a period
  72. is generated from a lower-level pattern, every pattern
  73. has a "current" field that holds the current item. the
  74. "have-current" field is a flag to tell when the "current"
  75. field is valid. It is initialized to nil.
  76.  
  77. To generate an element, you need to follow the nested
  78. patterns all the way to the leaf pattern for every 
  79. generated item. This is perhaps less efficient than
  80. storing the current leaf pattern at the top level, but
  81. patterns can be shared, i.e. a pattern can be a 
  82. sub-pattern of multiple patterns, so current position
  83. in the tree structure of patterns can change at 
  84. any time.
  85.  
  86. The evaluation of nested patterns is depth-first
  87. and the next shallower level advances when its current
  88. child pattern completes a cycle. To facilitate this
  89. step, the :advance method, which advances a pattern
  90. and computes "current", returns +eonp+, which is a
  91. marker that a nested pattern has completed a cycle.
  92.  
  93. The :next method generates the next item or +eop+ from
  94. a pattern. The algorithm in psuedo-code is roughly this:
  95.  
  96. next(p)
  97.     while true:
  98.         if not have-current
  99.             pattern-advance()
  100.             have-current = true
  101.             if is-nested and current = eop:
  102.                 have-current = false
  103.                 return eonp
  104.         if is-nested:
  105.             rslt = next(current)
  106.             if rslt == eonp
  107.                 have-current = false
  108.             elif rslt == eop and not current.is-nested
  109.                 have-current = false
  110.                 return rslt
  111.             else
  112.                 return rslt
  113.         else
  114.             have-current = nil
  115.             return current
  116.  
  117. pattern-advance
  118.     // length-pattern is either a pattern or a constant
  119.     if null(count) and length-pattern:
  120.         count = next(length-pattern)
  121.         start-period() // subclass-specific computation
  122.     if null(count)
  123.         error
  124.     if count == 0
  125.         current = eop
  126.         count = nil
  127.     else
  128.         advance() // subclass-specific computation
  129.         count--
  130.  
  131.  
  132. SUBCLASS RESPONSIBILITIES
  133.  
  134. Note that :advance is the method to override in the 
  135. various subclasses of pattern-class. The :advance()
  136. method computes the next element in the infinite
  137. sequence of items and puts the item in the "current"
  138. field. 
  139.  
  140. The :start-period method is called before calling 
  141. advance to get the first item of a new period.
  142.  
  143. Finally, set the is-nested flag if there are nested patterns,
  144. and make all items of any nested pattern be patterns (no
  145. mix of patterns and non-patterns is allowed; use 
  146.     (MAKE-CYCLE (LIST item))
  147. to convert a non-pattern to a pattern).
  148.  
  149. |#
  150.  
  151. (setf SCORE-EPSILON 0.000001)
  152.  
  153. (setf pattern-class 
  154.   (send class :new '(current have-current is-nested name count
  155.                      length-pattern trace)))
  156.  
  157. (defun patternp (x) 
  158.   (and (objectp x) (send x :isa pattern-class)))
  159.  
  160. (setf +eop+ '+eop+)
  161. (setf +eonp+ '+eonp+) ;; end of nested period, this indicates you
  162.    ;; should advance yourself and call back to get the next element
  163.  
  164. (defun check-for-list (lis name)
  165.   (if (not (listp lis))
  166.       (error (format nil "~A, requires a list of elements" name))))
  167.  
  168. (defun check-for-list-or-pattern (lis name)
  169.   (if (not (or (listp lis) (patternp lis)))
  170.       (error (format nil "~A, requires a list of elements or a pattern" name))))
  171.  
  172. (defun list-has-pattern (lis)
  173.   (dolist (e lis) 
  174.     (if (patternp e) (return t))))
  175.  
  176. (defun is-homogeneous (lis)
  177.   (let (type)
  178.     (dolist (elem lis t)
  179.       (cond ((null type)
  180.              (setf type (if (patternp elem) 'pattern 'atom)))
  181.             ((and (eq type 'pattern)
  182.                   (not (patternp elem)))
  183.              (return nil))
  184.             ((and (eq type 'atom)
  185.                   (patternp elem))
  186.              (return nil))))))
  187.  
  188. (defun make-homogeneous (lis)
  189.   (cond ((is-homogeneous lis) lis)
  190.         (t
  191.          (mapcar #'(lambda (item)
  192.                      (if (patternp item) item 
  193.                          (make-cycle (list item)
  194.                           ;; help debugging by naming the new pattern
  195.                           ;; probably, the name could be item, but
  196.                           ;; here we coerce item to a string to avoid
  197.                           ;; surprises in code that assumes string names.
  198.                           :name (format nil "~A" item))))
  199.                  lis))))
  200.  
  201.  
  202. (send pattern-class :answer :next '()
  203.   '(;(display ":next" name is-nested)
  204.     (loop
  205.      (cond ((not have-current)
  206.             (send self :pattern-advance)
  207.             (setf have-current t)
  208.             (cond (trace
  209.                    (format t "pattern ~A advanced to ~A~%"
  210.                            (if name name "<no-name>")
  211.                            (if (patternp current) 
  212.                                (if (send current :name)
  213.                                    (send current :name)
  214.                                    "<a-pattern>")
  215.                                current))))
  216.             (cond ((and is-nested (eq current +eop+))
  217.                    ;(display ":next returning eonp" name)
  218.                    (setf have-current nil)
  219.                    (return +eonp+)))))
  220.      (cond (is-nested
  221.             (let ((rslt (send current :next)))
  222.               (cond ((eq rslt +eonp+)
  223.                      (setf have-current nil))
  224.                     ;; advance next-to-leaf level at end of leaf's period
  225.                     ((and (eq rslt +eop+) (not (send current :is-nested)))
  226.                      (setf have-current nil)
  227.                      ;; return +eof+ because it's the end of leaf's period
  228.                      (return rslt))
  229.                     (t
  230.                      (return rslt)))))
  231.            (t
  232.             (setf have-current nil)
  233.             (return current))))))
  234.  
  235.  
  236. ;; :PATTERN-ADVANCE -- advance to the next item in a pattern
  237. ;; 
  238. ;; this code is used by every class. class-specific behavior
  239. ;; is implemented by :advance, which this method calls
  240. ;;
  241. (send pattern-class :answer :pattern-advance '()
  242.   '(;(display "enter :pattern-advance" self name count current is-nested)
  243.     (cond ((null count)
  244.            ;(display "in :pattern-advance" name count length-pattern)
  245.            (if length-pattern
  246.                (setf count (next length-pattern)))
  247.            ;; if count is still null, :start-period must set count
  248.            (send self :start-period)))
  249.     (cond ((null count)
  250.            (error
  251.             (format nil
  252.              "~A, pattern-class :pattern-advance has null count" name))))
  253.     (cond ((zerop count)
  254.            (setf current +eop+)
  255.            (setf count nil))
  256.           (t
  257.            (send self :advance)
  258.            (decf count)))
  259.     ;(display "exit :pattern-advance" name count current)
  260.     ))
  261.  
  262.  
  263. (send pattern-class :answer :is-nested '() '(is-nested))
  264.  
  265.  
  266. (send pattern-class :answer :name '() '(name))
  267.  
  268.  
  269. (send pattern-class :answer :set-current '(c)
  270.   '((setf current c)
  271.     (let ((value
  272.            (if (patternp current) 
  273.                (send current :name)
  274.                current)))
  275.       ;(display ":set-current" name value)
  276.       )))
  277.  
  278.  
  279. ;; next -- get the next element in a pattern
  280. ;;
  281. ;; any non-pattern value is simply returned
  282. ;;
  283. (defun next (pattern &optional period-flag) 
  284.   ;(display "next" pattern period-flag (patternp pattern))
  285.   (cond ((and period-flag (patternp pattern))
  286.          (let (rslt elem)
  287.            (while (not (eq (setf elem (send pattern :next)) +eop+))
  288.                ;(display "next t" (send pattern :name) elem)
  289.                (if (not (eq elem +eonp+)) 
  290.                    (push elem rslt)))
  291.            (reverse rslt)))
  292.         (period-flag
  293.          (display "next" pattern)
  294.          (error (format nil "~A, next expected a pattern"
  295.                             (send pattern :name))))
  296.         ((patternp pattern)
  297.          ;(display "next" (send pattern :name) pattern)
  298.          (let (rslt)
  299.            (dotimes (i 10000 (error
  300.                  (format nil
  301.                   "~A, just retrieved 10000 empty periods -- is there a bug?"
  302.                   (send pattern :name))))
  303.              (if (not (member (setf rslt (send pattern :next)) 
  304.                               '(+eop+ +eonp+)))
  305.                  (return rslt)))))
  306.         (t ;; pattern not a pattern, so just return it:
  307.          ;(display "next" pattern)
  308.          pattern)))
  309.  
  310. ;; ---- LENGTH Class ----
  311.  
  312. (setf length-class 
  313.   (send class :new '(pattern length-pattern) '() pattern-class))
  314.  
  315. (send length-class :answer :isnew '(p l nm tr)
  316.   '((setf pattern p length-pattern l name nm trace tr)))
  317.  
  318. ;; note that count is used as a flag as well as a counter.
  319. ;; If count is nil, then the pattern-length has not been
  320. ;; determined. Count is nil intitially and again at the 
  321. ;; end of each period. Otherwise, count is an integer
  322. ;; used to count down the number of items remaining in 
  323. ;; the period.
  324.  
  325. (send length-class :answer :start-period '()
  326.   '((setf count (next length-pattern))))
  327.  
  328. (send length-class :answer :advance '()
  329.   '((send self :set-current (next pattern))))
  330.  
  331. (defun make-length (pattern length-pattern &key (name "length") trace)
  332.   (send length-class :new pattern length-pattern name trace))
  333.  
  334. ;; ---- CYCLE Class ---------
  335.  
  336. (setf cycle-class (send class :new 
  337.                         '(lis cursor lis-pattern)
  338.                         '() pattern-class))
  339.  
  340. (send cycle-class :answer :isnew '(l for nm tr)
  341.   '((cond ((patternp l)
  342.            (setf lis-pattern l))
  343.           ((listp l)
  344.            (send self :set-list l))
  345.           (t
  346.            (error (format nil "~A, expected list" nm) l)))
  347.     (setf length-pattern for name nm trace tr)))
  348.  
  349.  
  350. (send cycle-class :answer :set-list '(l)
  351.   '((setf lis l)
  352.     (check-for-list lis "cycle-class :set-list")
  353.     (setf is-nested (list-has-pattern lis))
  354.     (setf lis (make-homogeneous lis))))
  355.  
  356.  
  357. (send cycle-class :answer :start-period '()
  358.   '(;(display "cycle-class :start-period" lis-pattern lis count length-pattern)
  359.     (cond (lis-pattern
  360.            (send self :set-list (next lis-pattern t))
  361.            (setf cursor lis)))
  362.     (if (null count)
  363.         (setf count (length lis)))))
  364.   
  365.  
  366. (send cycle-class :answer :advance '()
  367.   '((cond ((and (null cursor) lis)
  368.            (setf cursor lis))
  369.           ((null cursor)
  370.            (error (format nil "~A, :advance - no items" name))))
  371.     (send self :set-current (car cursor))
  372.     (pop cursor)))
  373.  
  374.  
  375. (defun make-cycle (lis &key for (name "cycle") trace)
  376.    (check-for-list-or-pattern lis "make-cycle")
  377.    (send cycle-class :new lis for name trace))
  378.  
  379. ;; ---- LINE class ----
  380.  
  381. (setf line-class (send class :new '(lis cursor lis-pattern) 
  382.                        '() pattern-class))
  383.  
  384. (send line-class :answer :isnew '(l for nm tr)
  385.   '((cond ((patternp l)
  386.            (setf lis-pattern l))
  387.           ((listp l)
  388.            (send self :set-list l))
  389.           (t
  390.            (error (format nil "~A, expected list" nm) l)))
  391.     (setf length-pattern for name nm trace tr)))
  392.  
  393. (send line-class :answer :set-list '(l)
  394.   '((setf lis l)
  395.     (check-for-list lis "line-class :set-list")
  396.     (setf is-nested (list-has-pattern lis))
  397.     (setf lis (make-homogeneous l))
  398.     (setf cursor lis)))
  399.  
  400.  
  401. (send line-class :answer :start-period '()
  402.   '((cond (lis-pattern
  403.            (send self :set-list (next lis-pattern t))
  404.            (setf cursor lis)))
  405.     (if (null count)
  406.         (setf count (length lis)))))
  407.  
  408.  
  409. (send line-class :answer :advance '()
  410.   '((cond ((null cursor)
  411.            (error (format nil "~A, :advance - no items" name))))
  412.     (send self :set-current (car cursor))
  413.     (if (cdr cursor) (pop cursor))))
  414.   
  415.  
  416. (defun make-line (lis &key for (name "line") trace)
  417.    (check-for-list-or-pattern lis "make-line")
  418.    (send line-class :new lis for name trace))
  419.  
  420.  
  421. ;; ---- RANDOM class -----
  422.  
  423. (setf random-class (send class :new 
  424.        '(lis lis-pattern len previous repeats mincnt maxcnt) 
  425.        '() pattern-class))
  426.  
  427. ;; the structure is (value weight weight-pattern max min)
  428. (setfn rand-item-value car)
  429. (defun set-rand-item-value (item value) (setf (car item) value))
  430. (setfn rand-item-weight cadr)
  431. (defun set-rand-item-weight (item weight) (setf (car (cdr item)) weight))
  432. (setfn rand-item-weight-pattern caddr)
  433. (setfn rand-item-max cadddr)
  434. (defun rand-item-min (lis) (car (cddddr lis)))
  435.  
  436.  
  437. (defun select-random (len lis previous repeats mincnt maxcnt)
  438.   (let (sum items r)
  439.     (cond ((zerop len)
  440.            (break "random-class has no list to choose from")
  441.            nil)
  442.           (t
  443.            (setf sum 0)
  444.            (dolist (item lis)
  445.              (setf sum (+ sum (rand-item-weight item))))
  446.            (setf items lis)
  447.            (setf r (rrandom))
  448.            (setf sum (* sum r))
  449.            (setf rbd-count-all (incf rbd-count-all))
  450.            (loop
  451.              (setf sum (- sum (rand-item-weight (car items))))
  452.              (if (<= sum 0) (return (car items)))
  453.              (setf rbd-count-two (incf rbd-count-two))
  454.              (setf items (cdr items)))))))
  455.  
  456.  
  457. (defun random-convert-spec (item)
  458.   ;; convert (value :weight wp :min min :max max) to (value nil wp max min)
  459.   (let (value (wp 1) mincnt maxcnt lis)
  460.     (setf value (car item))
  461.     (setf lis (cdr item))
  462.     (while lis
  463.       (cond ((eq (car lis) :weight)
  464.              (setf wp (cadr lis)))
  465.             ((eq (car lis) :min)
  466.              (setf mincnt (cadr lis)))
  467.             ((eq (car lis) :max)
  468.              (setf maxcnt (cadr lis)))
  469.             (t
  470.              (error "(make-random) item syntax error" item)))
  471.       (setf lis (cddr lis)))
  472.     (list value nil wp maxcnt mincnt)))
  473.  
  474.  
  475. (defun random-atom-to-list (a)
  476.   (if (atom a)
  477.       (list a nil 1 nil nil)
  478.       (random-convert-spec a)))
  479.  
  480.  
  481. (send random-class :answer :isnew '(l for nm tr)
  482.   ;; there are two things we have to normalize:
  483.   ;; (1) make all items lists
  484.   ;; (2) if any item is a pattern, make all items patterns
  485.   '((cond ((patternp l)
  486.            (setf lis-pattern l))
  487.           ((listp l)
  488.            (send self :set-list l))
  489.           (t
  490.            (error (format nil "~A, expected list") l)))
  491.     (setf rbd-count-all 0 rbd-count-two 0)
  492.     (setf length-pattern for name nm trace tr)))
  493.  
  494.  
  495. (send random-class :answer :set-list '(l)
  496.   '((check-for-list l "random-class :set-list")
  497.     (setf lis (mapcar #'random-atom-to-list l))
  498.     (dolist (item lis)
  499.       (if (patternp (rand-item-value item))
  500.           (setf is-nested t)))
  501.     (if is-nested
  502.         (mapcar #'(lambda (item)
  503.                     (if (not (patternp (rand-item-value item)))
  504.                         (set-rand-item-value item 
  505.                          (make-cycle (list (rand-item-value item))))))
  506.                 lis))
  507.     ;(display "random is-new" lis)
  508.     (setf repeats 0)
  509.     (setf len (length lis))))
  510.  
  511.     
  512. (send random-class :answer :start-period '()
  513.   '(;(display "random-class :start-period" count len lis lis-pattern)
  514.     (cond (lis-pattern
  515.            (send self :set-list (next lis-pattern t))))
  516.     (if (null count)
  517.         (setf count len))
  518.     (dolist (item lis)
  519.       (set-rand-item-weight item (next (rand-item-weight-pattern item))))))
  520.  
  521.  
  522. (send random-class :answer :advance '()
  523.   '((let (selection (iterations 0))
  524.       ;(display "random-class :advance" mincnt repeats)
  525.       (cond ((and mincnt (< repeats mincnt))
  526.              (setf selection previous)
  527.              (incf repeats))
  528.             (t
  529.              (setf selection
  530.                    (select-random len lis previous repeats mincnt maxcnt))))
  531.       (loop ; make sure selection is ok, otherwise try again
  532.         (cond ((and (eq selection previous)
  533.                     maxcnt 
  534.                     (>= repeats maxcnt)) ; hit maximum limit, try again
  535.                (setf selection
  536.                      (select-random len lis previous repeats mincnt maxcnt))
  537.                (incf iterations)
  538.                (cond ((> iterations 10000)
  539.                       (error
  540.                         (format nil
  541.                          "~A, unable to pick next item after 10000 tries"
  542.                          name)
  543.                        lis))))
  544.               (t (return)))) ; break from loop, we found a selection
  545.  
  546.         ; otherwise, we are ok
  547.         (if (not (eq selection previous))
  548.             (setf repeats 1)
  549.             (incf repeats))
  550.         (setf mincnt (rand-item-min selection))
  551.         (setf maxcnt (rand-item-max selection))
  552.         (setf previous selection)
  553.         ;(display "new selection" repeats mincnt maxcnt selection)
  554.         (send self :set-current (rand-item-value selection)))))
  555.       
  556.  
  557. (defun make-random (lis &key for (name "random") trace)
  558.    (check-for-list-or-pattern lis "make-random")
  559.    (send random-class :new lis for name trace))
  560.  
  561.  
  562. ;; ---- PALINDROME class -----
  563.  
  564. #| Palindrome includes elide, which is either t, nil, :first, or :last.
  565. The pattern length is the "natural" length of the pattern, which goes
  566. forward and backward through the list. Thus, if the list is of length N,
  567. the palindrome length depends on elide as follows:
  568.     elide   length
  569.      nil      2N
  570.      t        2N - 2
  571.    :first     2N - 1
  572.    :last      2N - 1
  573. If elide is a pattern, and if length is not specified, then length should
  574. be computed based on elide. 
  575. |#
  576.  
  577.  
  578. (setf palindrome-class (send class :new 
  579.                          '(lis revlis lis-pattern 
  580.                            direction elide-pattern
  581.                            elide cursor)
  582.                          '() pattern-class))
  583.  
  584. (send palindrome-class :answer :set-list '(l)
  585.   '((setf lis l)
  586.     (check-for-list lis "palindrome-class :start-period")
  587.     (setf is-nested (list-has-pattern lis))
  588.     (setf lis (make-homogeneous l))
  589.     (setf revlis (reverse lis)
  590.           direction t
  591.           cursor lis)))
  592.  
  593.  
  594. (send palindrome-class :answer :isnew '(l e for nm tr)
  595.   '((cond ((patternp l)
  596.            (setf lis-pattern l))
  597.           ((listp l)
  598.            (send self :set-list l))
  599.           (t
  600.            (error (format nil "~A, expected list" nm) l)))
  601.     (setf elide-pattern e length-pattern for name nm trace tr)))
  602.  
  603.  
  604. (send palindrome-class :answer :start-period '()
  605.   '((cond (lis-pattern
  606.            (send self :set-list (next lis-pattern t))
  607.            (setf cursor lis)))
  608.     (setf elide (next elide-pattern))
  609.     (if (and elide (null lis))
  610.         (error (format nil "~A, cannot elide if list is empty" name)))
  611.     (if (null count)
  612.         (setf count (- (* 2 (length lis))
  613.                        (if (member elide '(:first :last)) 
  614.                            1
  615.                            (if elide 2 0)))))))
  616.  
  617.  
  618. (send palindrome-class :answer :next-item '()
  619.   '((send self :set-current (car cursor))
  620.     (pop cursor)
  621.     (cond ((and cursor (not (cdr cursor))
  622.                 (or (and direction (member elide '(:last t)))
  623.                     (and (not direction) (member elide '(:first t)))))
  624.            (pop cursor)))))
  625.  
  626.  
  627. (send palindrome-class :answer :advance '()
  628.   '(
  629.     (cond (cursor
  630.            (send self :next-item))
  631.           (direction ;; we're going forward
  632.            (setf direction nil) ;; now going backward
  633.            (setf cursor revlis)
  634.            (send self :next-item))
  635.           (t ;; direction is reverse
  636.            (setf direction t)
  637.            (setf cursor lis)
  638.            (send self :next-item)))))
  639.  
  640.  
  641. (defun make-palindrome (lis &key elide for (name "palindrome") trace)
  642.   (check-for-list-or-pattern lis "make-palindrome")
  643.   (send palindrome-class :new lis elide for name trace))
  644.  
  645.  
  646. ;; ================= HEAP CLASS ======================
  647.  
  648. ;; to handle the :max keyword, which tells the object to avoid
  649. ;; repeating the last element of the previous period:
  650. ;;
  651. ;; maxcnt = 1 means "avoid the repetition"
  652. ;; check-repeat signals we are at the beginning of the period and must check
  653. ;; prev holds the previous value (initially nil)
  654. ;; after each item is generated, check-repeat is cleared. It is
  655. ;; recalculated when a new period is started.
  656.  
  657. (setf heap-class (send class :new '(lis used maxcnt prev check-repeat
  658.                                     lis-pattern len)
  659.                        '() pattern-class))
  660.  
  661. (send heap-class :answer :isnew '(l for mx nm tr)
  662.   '((cond ((patternp l)
  663.            (setf lis-pattern l))
  664.           ((listp l)
  665.            ; make a copy of l to avoid side effects
  666.            (send self :set-list (append l nil)))
  667.           (t
  668.            (error (format nil "~A, expected list" nm) l)))
  669.     (setf length-pattern for maxcnt mx name nm trace tr)))
  670.  
  671.  
  672. (send heap-class :answer :set-list '(l)
  673.   '((setf lis l)
  674.     (check-for-list lis "heap-class :set-list")
  675.     (setf is-nested (list-has-pattern lis))
  676.     (setf lis (make-homogeneous lis))
  677.     (setf len (length lis))))
  678.  
  679.  
  680. (send heap-class :answer :start-period '()
  681.   '(;(display "heap-class :start-period" lis-pattern count lis)
  682.     (cond (lis-pattern
  683.            (send self :set-list (next lis-pattern t))))
  684.     ; start of period -- may need to avoid repeating previous item
  685.     (if (= maxcnt 1) (setf check-repeat t))
  686.     (if (null count)
  687.         (setf count len))))
  688.  
  689.     
  690. (defun delete-first (elem lis)
  691.   (cond ((null lis) nil)
  692.         ((eq elem (car lis))
  693.          (cdr lis))
  694.         (t
  695.          (cons (car lis) (delete-first elem (cdr lis))))))
  696.  
  697.  
  698. ;; NO-DISTINCT-ELEM -- check if any element of list is not val
  699. ;;
  700. (defun no-distinct-elem (lis val)
  701.   (not 
  702.     (dolist (elem lis)
  703.       (if (not (equal elem val))
  704.           ;; there is a distinct element, return t from dolist
  705.           (return t)))))
  706.     ;; if no distinct element, dolist returns nil, but this is negated
  707.     ;; by the NOT so the function will return t
  708.  
  709.  
  710. (send heap-class :answer :advance '()
  711.   '((cond ((null lis)
  712.            (setf lis used)
  713.            (setf used nil)))
  714.     (let (n elem)
  715.       (cond ((and check-repeat (no-distinct-elem lis prev))
  716.              (error (format nil "~A, cannot avoid repetition, but :max is 1"
  717.                                 name))))
  718.       (loop 
  719.         (setf n (random (length lis)))
  720.         (setf elem (nth n lis))
  721.         (if (or (not check-repeat) (not (equal prev elem))) 
  722.             (return))) ;; loop until suitable element is chosen
  723.       (setf lis (delete-first elem lis))
  724.       (push elem used)
  725.       (setf check-repeat nil)
  726.       (setf prev elem)
  727.       (send self :set-current elem))))
  728.  
  729. (defun make-heap (lis &key for (max 2) (name "heap") trace)
  730.   (send heap-class :new lis for max name trace))
  731.  
  732. ;;================== COPIER CLASS ====================
  733.  
  734. (setf copier-class (send class :new '(sub-pattern repeat repeat-pattern 
  735.                                       merge merge-pattern period cursor) 
  736.                                     '() pattern-class))
  737.  
  738. (send copier-class :answer :isnew '(p r m for nm tr)
  739.   '((setf sub-pattern p repeat-pattern r merge-pattern m)
  740.     (setf length-pattern for name nm trace tr)))
  741.  
  742.  
  743. #| copier-class makes copies of periods from sub-pattern
  744.  
  745. If merge is true, the copies are merged into one big period.
  746. If merge is false, then repeat separate periods are returned.
  747. If repeat is negative, then -repeat periods of sub-pattern
  748. are skipped.
  749.  
  750. merge and repeat are computed from merge-pattern and 
  751. repeat-pattern initially and after making repeat copies
  752.  
  753. To repeat individual items, set the :for keyword parameter of
  754. the sub-pattern to 1.
  755. |#
  756.  
  757. (send copier-class :answer :start-period '()
  758.   '((cond ((null count) 
  759.            (cond ((or (null repeat) (zerop repeat))
  760.                   (send self :really-start-period))
  761.                  (t
  762.                   (setf count (length period))))))))
  763.  
  764.  
  765. (send copier-class :answer :really-start-period '()
  766.   '(;(display "copier-class :really-start-period" count)
  767.     (setf merge (next merge-pattern))
  768.     (setf repeat (next repeat-pattern))
  769.     (while (minusp repeat)
  770.       (dotimes (i (- repeat))
  771.         (setf period (next sub-pattern t)))
  772.       (setf repeat (next repeat-pattern))
  773.       (setf merge (next merge-pattern)))
  774.     (setf period (next sub-pattern t))
  775.     (setf cursor nil)
  776.     (if (null count)
  777.         (setf count (* (if merge repeat 1)
  778.                        (length period))))))
  779.  
  780.  
  781. (send copier-class :answer :advance '()
  782.   '((let ((loop-count 0))
  783.       (loop
  784.         ;(display "copier loop" repeat cursor period)
  785.         (cond (cursor
  786.                (send self :set-current (car cursor))
  787.                (pop cursor)
  788.                (return))
  789.               ((plusp repeat)
  790.                (decf repeat)
  791.                (setf cursor period))
  792.               ((> loop-count 10000)
  793.                (error (format nil
  794.                 "~A, copier-class :advance encountered 10000 empty periods"
  795.                 name)))
  796.               (t
  797.                (send self :really-start-period)))
  798.         (incf loop-count)))))
  799.  
  800.  
  801. (defun make-copier (sub-pattern &key for (repeat 1) merge (name "copier") trace)
  802.   (send copier-class :new sub-pattern repeat merge for name trace))
  803.    
  804. ;; ================= ACCUMULATE-CLASS ===================
  805.  
  806. (setf accumulate-class (send class :new '(sub-pattern period cursor sum mini maxi) 
  807.                                     '() pattern-class))
  808.  
  809.  
  810. (send accumulate-class :answer :isnew '(p for nm tr mn mx)
  811.   '((setf sub-pattern p length-pattern for name nm trace tr sum 0 mini mn maxi mx)
  812.     ; (display "accumulate isnew" self nm)
  813.     ))
  814.  
  815.  
  816. #| 
  817. accumulate-class creates sums of numbers from another pattern
  818. The output periods are the same as the input periods (by default).
  819. |#
  820.  
  821. (send accumulate-class :answer :start-period '()
  822.   '((cond ((null count)
  823.            (send self :really-start-period)))))
  824.  
  825.  
  826. (send accumulate-class :answer :really-start-period '()
  827.   '((setf period (next sub-pattern t))
  828.     (setf cursor period)
  829.     ;(display "accumulate-class :really-start-period" period cursor count)
  830.     (if (null count)
  831.         (setf count (length period)))))
  832.  
  833.  
  834. (send accumulate-class :answer :advance '()
  835.   '((let ((loop-count 0) (minimum (next mini)) (maximum (next maxi)))
  836.       (loop
  837.         (cond (cursor
  838.                (setf sum (+ sum (car cursor)))
  839.                (cond ((and (numberp minimum) (< sum minimum))
  840.                       (setf sum minimum)))
  841.                (cond ((and (numberp maximum) (> sum maximum))
  842.                       (setf sum maximum)))
  843.                (send self :set-current sum)
  844.                (pop cursor)
  845.                (return))
  846.               ((> loop-count 10000)
  847.                (error (format nil
  848.                 "~A, :advance encountered 10000 empty periods" name)))
  849.               (t
  850.                (send self :really-start-period)))
  851.         (incf loop-count)))))
  852.  
  853.  
  854. (defun make-accumulate (sub-pattern &key for min max (name "accumulate") trace)
  855.   (send accumulate-class :new sub-pattern for name trace min max))
  856.    
  857. ;;================== ACCUMULATION CLASS ===================
  858.  
  859. ;; for each item, generate all items up to and including the item, e.g.
  860. ;; (a b c) -> (a a b a b c)
  861.  
  862. (setf accumulation-class (send class :new '(lis lis-pattern outer inner len)
  863.                                '() pattern-class))
  864.  
  865. (send accumulation-class :answer :isnew '(l for nm tr)
  866.   '((cond ((patternp l)
  867.            (setf lis-pattern l))
  868.           ((listp l)
  869.            (send self :set-list l))
  870.           (t
  871.            (error (format nil "~A, expected list" nm) l)))
  872.       (setf length-pattern for name nm trace tr)))
  873.  
  874. (send accumulation-class :answer :set-list '(l)
  875.   '((setf lis l)
  876.     (check-for-list lis "heap-class :set-list")
  877.     (setf lis (make-homogeneous lis))
  878.     (setf inner lis)
  879.     (setf outer lis)
  880.     (setf len (length lis))))
  881.  
  882. (send accumulation-class :answer :start-period '()
  883.   '((cond (lis-pattern
  884.            (send self :set-list (next lis-pattern t))))
  885.     ; start of period, length = (n^2 + n) / 2
  886.     (if (null count) (setf count (/ (+ (* len len) len) 2)))))
  887.  
  888. (send accumulation-class :answer :advance '()
  889.   ;; inner traverses lis from first to outer
  890.   ;; outer traverses lis
  891.   '((let ((elem (car inner)))
  892.       (cond ((eq inner outer)
  893.              (setf outer (rest outer))
  894.              (setf outer (if outer outer lis))
  895.              (setf inner lis))
  896.             (t
  897.              (setf inner (rest inner))))
  898.       (send self :set-current elem))))
  899.  
  900. (defun make-accumulation (lis &key for (name "accumulation") trace)
  901.   (send accumulation-class :new lis for name trace))
  902.  
  903.  
  904. ;;================== SUM CLASS =================
  905.  
  906. (setf sum-class (send class :new '(x y period cursor fn) '() pattern-class))
  907.  
  908. (send sum-class :answer :isnew '(xx yy for nm tr)
  909.   '((setf x xx y yy length-pattern for name nm trace tr fn #'+)))
  910.  
  911. #|
  912. sum-class creates pair-wise sums of numbers from 2 streams.
  913. The output periods are the same as the input periods of the first
  914. pattern argument (by default).
  915. |#
  916.  
  917. (send sum-class :answer :start-period '()
  918.   '((cond ((null count)
  919.            (send self :really-start-period)))))
  920.  
  921. (send sum-class :answer :really-start-period '()
  922.   '((setf period (next x t))
  923.     (setf cursor period)
  924.     (if (null count)
  925.         (setf count (length period)))))
  926.  
  927. (send sum-class :answer :advance '()
  928.   '((let ((loop-count 0) rslt)
  929.       (loop
  930.         (cond (cursor
  931.                (setf rslt (funcall fn (car cursor) (next y)))
  932.                (send self :set-current rslt)
  933.                (pop cursor)
  934.                (return))
  935.               ((> loop-count 10000)
  936.                (error (format nil
  937.                        "~A, :advance encountered 10000 empty periods" name)))
  938.               (t
  939.                (send self :really-start-period)))
  940.         (incf loop-count)))))
  941.  
  942.  
  943. (defun make-sum (x y &key for (name "sum") trace)
  944.   (send sum-class :new x y for name trace))               
  945.  
  946.  
  947. ;;================== PRODUCT CLASS =================
  948.  
  949. (setf product-class (send class :new '() '() sum-class))
  950.  
  951. (send product-class :answer :isnew '(xx yy for nm tr)
  952.   '((setf x xx y yy length-pattern for name nm trace tr fn #'*)))
  953.  
  954. (defun make-product (x y &key for (name "product") trace)
  955.   (send product-class :new x y for name trace))               
  956.  
  957.  
  958. ;;================== EVAL CLASS =================
  959.  
  960. (setf eval-class (send class :new '(expr expr-pattern) 
  961.                        '() pattern-class))
  962.  
  963. (send eval-class :answer :isnew '(e for nm tr)
  964.   '((cond ((patternp e)
  965.            (setf expr-pattern e))
  966.           (t
  967.            (setf expr e)))
  968.     (setf length-pattern for name nm trace tr)))
  969.  
  970.  
  971. (send eval-class :answer :start-period '()
  972.   '(;(display "cycle-class :start-period" lis-pattern lis count length-pattern)
  973.     (cond (expr-pattern
  974.            (setf expr (next expr-pattern))))))
  975.   
  976.  
  977. (send eval-class :answer :advance '()
  978.   '((send self :set-current (eval expr))))
  979.  
  980.  
  981. (defun make-eval (expr &key (for 1) (name "eval") trace)
  982.    (send eval-class :new expr for name trace))
  983.  
  984. ;;================== MARKOV CLASS ====================
  985.  
  986. (setf markov-class (send class :new 
  987.       '(rules order state produces pattern len) 
  988.       '() pattern-class))
  989.  
  990.  
  991. (defun is-produces-homogeneous (produces)
  992.   (let (type elem)
  993.     (setf *rslt* nil)
  994.     (loop
  995.       (cond ((or (null produces) (eq produces :eval) (null (cadr produces)))
  996.              (return t)))
  997.       (setf elem (cadr produces))
  998.       (cond ((null type)
  999.              (setf type (if (patternp elem) 'pattern 'atom))
  1000.            ;(display "is-produces-homogeneous" type)
  1001.              (setf *rslt* (eq type 'pattern))
  1002.              ;(display "is-produces-homogeneous" *rslt*)
  1003.              )
  1004.             ((and (eq type 'pattern) (not (patternp elem)))
  1005.              (return nil))
  1006.             ((and (eq type 'atom)
  1007.                   (patternp elem))
  1008.              (return nil)))
  1009.       (setf produces (cddr produces)))))
  1010.  
  1011.  
  1012. (defun make-produces-homogeneous (produces)
  1013.   (let (result item)
  1014.     (loop
  1015.       (if (null produces) (return nil))
  1016.       (push (car produces) result)
  1017.       (setf produces (cdr produces))
  1018.       (setf item (car produces))
  1019.       (setf produces (cdr produces))
  1020.       (if (not (patternp item)) 
  1021.         (setf item (make-cycle (list item))))
  1022.       (push item result))
  1023.     (reverse result)))
  1024.  
  1025.  
  1026. (send markov-class :answer :isnew '(r o s p for nm tr)
  1027.   ;; input parameters are rules, order, state, produces, for, name, trace
  1028.   '((setf order o state s produces p length-pattern for name nm trace tr)
  1029.     (setf len (length r))
  1030.     ;; input r looks like this:
  1031.     ;; ((prev1 prev2 -> next1 next2 (next3 weight) ... ) ...)
  1032.     ;; transition table will look like a list of these:
  1033.     ;; ((prev1 prev2 ... prevn) (next1 weight weight-pattern) ...)
  1034.     (dolist (rule r)
  1035.       (let ((targets (cdr (nthcdr order rule)))
  1036.             entry pattern)
  1037.         ;; build entry in reverse order
  1038.         (dolist (target targets)
  1039.           (push (if (atom target)
  1040.                     (list target 1 1) 
  1041.                     (list (first target) 
  1042.                           (next (second target)) 
  1043.                           (second target))) 
  1044.                 entry))
  1045.         ; (display "isnew" entry rule targets order (nthcdr order rule))
  1046.         (dotimes (i order)
  1047.           (push (nth i rule) pattern))
  1048.         (push (cons (reverse pattern) entry) rules)))
  1049.     (setf rules (reverse rules)) ;; keep rules in original order
  1050.     (setf *rslt* nil) ;; in case produces is nil
  1051.     (cond ((and produces (not (is-produces-homogeneous produces)))
  1052.            (setf produces (make-produces-homogeneous produces))))
  1053.     ;(display "markov-class :isnew" *rslt*)
  1054.     (setf is-nested *rslt*) ;; returned by is-produces-homogeneous
  1055.     ;(display "markov-class :isnew" is-nested)
  1056.     ))
  1057.  
  1058.  
  1059. (defun markov-match (state pattern)
  1060.   (dolist (p pattern t) ;; return true if no mismatch
  1061.     ;; compare element-by-element
  1062.     (cond ((eq p '*)) ; anything matches '*
  1063.           ((eql p (car state)))
  1064.           (t (return nil))) ; a mismatch: return false
  1065.     (setf state (cdr state))))
  1066.  
  1067. (defun markov-sum-of-weights (rule)
  1068.   ;(display "sum-of-weights" rule)
  1069.   (let ((sum 0.0))
  1070.     (dolist (target (cdr rule))
  1071.       ;(display "markov-sum-of-weights" target)
  1072.       (setf sum (+ sum (second target))))
  1073.     sum))
  1074.  
  1075.  
  1076. (defun markov-pick-target (sum rule)
  1077.   (let ((total 0.0)
  1078.         ;; want to choose a value in the interval [0, sum)
  1079.         ;; but real-random is not open on the right, so fudge
  1080.         ;; the range by a small amount:
  1081.         (r (real-random 0.0 (- sum SCORE-EPSILON))))
  1082.     (dolist (target (cdr rule))
  1083.       (setf total (+ total (second target)))
  1084.       (cond ((> total r) (return (car target)))))))
  1085.  
  1086.  
  1087. (defun markov-update-weights (rule)
  1088.   (dolist (target (cdr rule))
  1089.     (setf (car (cdr target)) (next (caddr target)))))
  1090.  
  1091.  
  1092. (defun markov-map-target (target produces)
  1093.   (while (and produces (not (eq target (car produces))))
  1094.     (setf produces (cddr produces)))
  1095.   (cadr produces))
  1096.  
  1097.  
  1098. (send markov-class :answer :find-rule '()
  1099.   '((let (rslt)
  1100.       ;(display "find-rule" rules)
  1101.       (dolist (rule rules)
  1102.         ;(display "find-rule" state rule)
  1103.         (cond ((markov-match state (car rule))
  1104.                (setf rslt rule)
  1105.                (return rslt))))
  1106.       (cond ((null rslt)
  1107.              (display "Error, no matching rule found" state rules)
  1108.              (error (format nil "~A, (markov-class)" name))))
  1109.       rslt)))
  1110.  
  1111.  
  1112. (send markov-class :answer :start-period '()
  1113.   '((if (null count)
  1114.         (setf count len))))
  1115.  
  1116. (defun markov-general-rule-p (rule)
  1117.   (let ((pre (car rule)))
  1118.     (cond ((< (length pre) 2) nil) ;; 1st-order mm
  1119.           (t
  1120.            ;; return false if any member not *
  1121.            ;; return t if all members are *
  1122.            (dolist (s pre t)
  1123.              (if (eq s '*) t (return nil)))))))
  1124.  
  1125. (defun markov-find-state-leading-to (target rules)
  1126.   (let (candidates)
  1127.     (dolist (rule rules)
  1128.       (let ((targets (cdr rule)))
  1129.         (dolist (targ targets)
  1130.           (cond ((eql (car targ) target)
  1131.                  (push (car rule) candidates))))))
  1132.     (cond (candidates ;; found at least one
  1133.            (nth (random (length candidates)) candidates))
  1134.           (t
  1135.            nil))))
  1136.  
  1137. (send markov-class :answer :advance '()
  1138.   '((let (rule sum target rslt new-state)
  1139.       ;(display "markov" pattern rules)
  1140.       (setf rule (send self :find-rule))
  1141.       ;(display "advance 1" rule)
  1142.       (markov-update-weights rule)
  1143.       ;(display "advance 2" rule)
  1144.       (setf sum (markov-sum-of-weights rule))
  1145.       ;; the target can be a pattern, so apply NEXT to it
  1146.       (setf target (next (markov-pick-target sum rule)))
  1147.       ;; if the matching rule is multiple *'s, then this
  1148.       ;; is a higher-order Markov model, and we may now
  1149.       ;; wander around in parts of the state space that
  1150.       ;; never appeared in the training data. To avoid this
  1151.       ;; we violate the strict interpretation of the rules
  1152.       ;; and pick a random state sequence from the rule set
  1153.       ;; that might have let to the current state. We jam
  1154.       ;; this state sequence into state so that when we
  1155.       ;; append target, we'll have a history that might
  1156.       ;; have a corresponding rule next time.
  1157.       (cond ((markov-general-rule-p rule)
  1158.              (setf new-state (markov-find-state-leading-to target rules))
  1159.              (cond (new-state
  1160.                     ;(display "state replacement" new-state target)
  1161.                     (setf state new-state)))))
  1162.       (setf state (append (cdr state) (list target)))
  1163.       ;(display "markov next" rule sum target state)
  1164.       ;; target is the symbol for the current state. We can
  1165.       ;; return target (default), the value of target, or a
  1166.       ;; mapped value:
  1167.       (cond ((eq produces :eval)
  1168.              (setf target (eval target)))
  1169.             ((and produces (listp produces))
  1170.              ;(display "markov-produce" target produces)
  1171.              (setf target (markov-map-target target produces))))
  1172.       (if (not (eq is-nested (patternp target)))
  1173.           (error (format nil 
  1174.          "~A :is-nested keyword (~A) not consistent with result (~A)"
  1175.                   name is-nested target)))
  1176.       (send self :set-current target))))
  1177.  
  1178.  
  1179. (defun make-markov (rules &key produces past for (name "markov") trace)
  1180.   ;; check to make sure past and rules are consistent
  1181.   (let ((order (length past)))
  1182.     (dolist (rule rules)
  1183.       (dotimes (i order)
  1184.         (if (eq (car rule) '->)
  1185.             (error (format nil "~A, a rule does not match the length of :past"
  1186.                                name)))
  1187.         (pop rule))
  1188.       (if (eq (car rule) '->) nil
  1189.           (error (format nil "~A, a rule does not match the length of :past"
  1190.                              name)))))
  1191.   (cond ((null for)
  1192.          (setf for (length rules))))
  1193.   (send markov-class :new rules (length past) past produces for name trace))
  1194.  
  1195.  
  1196. (defun markov-rule-match (rule state)
  1197.   (cond ((null state) t)
  1198.         ((eql (car rule) (car state))
  1199.          (markov-rule-match (cdr rule) (cdr state)))
  1200.         (t nil)))
  1201.  
  1202.  
  1203. (defun markov-find-rule (rules state)
  1204.   (dolist (rule rules)
  1205.     ;(display "find-rule" rule)
  1206.     (cond ((markov-rule-match rule state)
  1207.            (return rule)))))
  1208.  
  1209. ;; ------- functions below are for MARKOV-CREATE-RULES --------
  1210.  
  1211. ;; MARKOV-FIND-CHOICE -- given a next state, find it in rule
  1212. ;;
  1213. ;; use state to get the order of the Markov model, e.g. how
  1214. ;; many previous states to skip in the rule, (add 1 for '->).
  1215. ;; then use assoc to do a quick search
  1216. ;;
  1217. ;; example:
  1218. ;;  (markov-find-choice '(a b -> (c 1) (d 2)) '(a b) 'd)
  1219. ;; returns (d 2) from the rule
  1220. ;;
  1221. (defun markov-find-choice (rule state next)
  1222.   (assoc next (nthcdr (1+ (length state)) rule)))
  1223.  
  1224. (defun markov-update-rule (rule state next)
  1225.   (let ((choice (markov-find-choice rule state next)))
  1226.     (cond (choice
  1227.            (setf (car (cdr choice)) (1+ (cadr choice))))
  1228.           (t
  1229.            (nconc rule (list (list next 1)))))
  1230.     rule))
  1231.  
  1232.  
  1233. (defun markov-update-rules (rules state next)
  1234.   (let ((rule (markov-find-rule rules state)))
  1235.     (cond (rule
  1236.            (markov-update-rule rule state next))
  1237.           (t
  1238.            (setf rules
  1239.                  (nconc rules 
  1240.                         (list (append state
  1241.                                       (cons '-> (list 
  1242.                                                  (list next 1)))))))))
  1243.     rules))
  1244.  
  1245.  
  1246. ;; MARKOV-UPDATE-HISTOGRAM -- keep a list of symbols and counts
  1247. ;; 
  1248. ;; This histogram will become the right-hand part of a rule, so
  1249. ;; the format is ((symbol count) (symbol count) ...)
  1250. ;;
  1251. (defun markov-update-histogram (histogram next)
  1252.   (let ((pair (assoc next histogram)))
  1253.     (cond (pair
  1254.            (setf (car (cdr pair)) (1+ (cadr pair))))
  1255.           (t
  1256.            (setf histogram (cons (list next 1) histogram))))
  1257.     histogram))
  1258.  
  1259.  
  1260. (defun markov-create-rules (sequence order &optional generalize)
  1261.   (let ((seqlen (length sequence)) state rules next histogram rule)
  1262.     (cond ((<= seqlen order)
  1263.            (error "markov-create-rules: sequence must be longer than order"))
  1264.           ((< order 1)
  1265.            (error "markov-create-rules: order must be 1 or greater")))
  1266.     ; build initial state sequence
  1267.     (dotimes (i order)
  1268.       (setf state (nconc state (list (car sequence))))
  1269.       (setf sequence (cdr sequence)))
  1270.     ; for each symbol, either update a rule or add a rule
  1271.     (while sequence
  1272.       (setf next (car sequence))
  1273.       (setf sequence (cdr sequence))
  1274.       (setf rules (markov-update-rules rules state next))
  1275.       (setf histogram (markov-update-histogram histogram next))
  1276.       ; shift next state onto current state list
  1277.       (setf state (nconc (cdr state) (list next))))
  1278.     ; generalize?
  1279.     (cond (generalize
  1280.            (setf rule (cons '-> histogram))
  1281.            (dotimes (i order)
  1282.              (setf rule (cons '* rule)))
  1283.            (setf rules (nconc rules (list rule)))))
  1284.     rules))
  1285.  
  1286.  
  1287. ;; ----- WINDOW Class ---------
  1288.  
  1289. (setf window-class (send class :new 
  1290.                          '(pattern skip-pattern lis cursor)
  1291.                          '() pattern-class))
  1292.  
  1293. (send window-class :answer :isnew '(p for sk nm tr)
  1294.   '((setf pattern p length-pattern for skip-pattern sk name nm trace tr)))
  1295.  
  1296.  
  1297. (send window-class :answer :start-period '()
  1298.   '((if (null count) (error (format nil "~A, :start-period -- count is null"
  1299.                                         name)))
  1300.     (cond ((null lis) ;; first time
  1301.            (dotimes (i count)
  1302.              (push (next pattern) lis))
  1303.            (setf lis (reverse lis)))
  1304.           (t
  1305.            (let ((skip (next skip-pattern)))
  1306.              (dotimes (i skip)
  1307.                (if lis (pop lis) (next pattern))))
  1308.            (setf lis (reverse lis))
  1309.            (let ((len (length lis)))
  1310.              (while (< len count)
  1311.                (incf len)
  1312.                (push (next pattern) lis))
  1313.              (while (> len count)
  1314.                (decf len)
  1315.                (pop lis))
  1316.              (setf lis (reverse lis)))))
  1317.     (setf cursor lis)))
  1318.  
  1319.  
  1320. (send window-class :answer :advance '()
  1321.   '((send self :set-current (car cursor))
  1322.     (pop cursor)))
  1323.  
  1324. (defun make-window (pattern length-pattern skip-pattern
  1325.                     &key (name "window") trace)
  1326.   (send window-class :new pattern length-pattern skip-pattern name trace))
  1327.  
  1328. ;; SCORE-SORTED -- test if score is sorted
  1329. ;;
  1330. (defun score-sorted (score)
  1331.   (let ((result t))
  1332.     (while (cdr score)
  1333.       (cond ((event-before (cadr score) (car score))
  1334.              (setf result nil)
  1335.              (return nil)))
  1336.       (setf score (cdr score)))
  1337.     result))
  1338.     
  1339.  
  1340. (defmacro score-gen (&rest args)
  1341.   (let (key val tim dur (name ''note) ioi trace save 
  1342.         score-len score-dur others pre post
  1343.         next-expr (score-begin 0) score-end)
  1344.     (while (and args (cdr args))
  1345.       (setf key (car args))
  1346.       (setf val (cadr args))
  1347.       (setf args (cddr args))       
  1348.       (case key
  1349.         (:time (setf tim val))
  1350.         (:dur (setf dur val))
  1351.         (:name (setf name val))
  1352.         (:ioi (setf ioi val))
  1353.         (:trace (setf trace val))
  1354.         (:save (setf save val))
  1355.         (:pre (setf pre val))
  1356.         (:post (setf post val))
  1357.         (:score-len (setf score-len val))
  1358.         (:score-dur (setf score-dur val))
  1359.         (:begin (setf score-begin val))
  1360.         (:end (setf score-end val))
  1361.         (t (setf others (cons key (cons val others))))))
  1362.     ;; make sure at least one of score-len, score-dur is present
  1363.     (cond ((and (null score-len) (null score-dur))
  1364.            (error
  1365.            "score-gen needs either :score-len or :score-dur to limit length")))
  1366.     ;; compute expression for dur
  1367.     (cond ((null dur)
  1368.            (setf dur 'sg:ioi)))
  1369.     ;; compute expression for ioi
  1370.     (cond ((null ioi)
  1371.            (setf ioi 1)))
  1372.     ;; compute expression for next start time
  1373.     (setf next-expr '(+ sg:start sg:ioi))
  1374.     ; (display "score-gen" others)
  1375.     `(let (sg:seq (sg:start ,score-begin) sg:ioi 
  1376.            (sg:score-len ,score-len) (sg:score-dur ,score-dur)
  1377.            (sg:count 0) (sg:save ,save) 
  1378.            (sg:begin ,score-begin) (sg:end ,score-end))
  1379.        ;; make sure at least one of score-len, score-dur is present
  1380.        (loop
  1381.          (cond ((or (and sg:score-len (<= sg:score-len sg:count))
  1382.                     (and sg:score-dur (<= (+ sg:begin sg:score-dur) sg:start)))
  1383.                 (return)))
  1384.          ,pre
  1385.          ,(cond (tim (list 'setf 'sg:start tim)))
  1386.          (setf sg:ioi ,ioi)
  1387.          (setf sg:dur ,dur)
  1388.          (push (list sg:start sg:dur (list ,name ,@others))
  1389.                sg:seq)
  1390.          ,post
  1391.          (cond (,trace
  1392.                 (format t "get-seq trace at ~A stretch ~A: ~A~%" 
  1393.                           sg:start sg:dur (car sg:seq))))
  1394.          (incf sg:count)
  1395.          (setf sg:start ,next-expr))
  1396.        (setf sg:seq (reverse sg:seq))
  1397.        ;; avoid sorting a sorted list -- XLisp's quicksort can overflow the
  1398.        ;; stack if the list is sorted because (apparently) the pivot points
  1399.        ;; are not random.
  1400.        (cond ((not (score-sorted sg:seq))
  1401.               (setf sg:seq (bigsort sg:seq #'event-before))))
  1402.        (cond ((and sg:seq (null sg:end))
  1403.               (setf sg:end (event-end (car (last sg:seq)))))
  1404.              ((null sg:end)
  1405.               (setf sg:end 0)))
  1406.        (push (list 0 0 (list 'SCORE-BEGIN-END ,score-begin sg:end)) sg:seq)
  1407.        (cond (sg:save (set sg:save sg:seq)))
  1408.        sg:seq)))
  1409.  
  1410. ;; ============== score manipulation ===========
  1411.  
  1412. (defun event-before (a b)
  1413.   (< (car a) (car b)))
  1414.  
  1415. ;; EVENT-END -- get the ending time of a score event
  1416. ;;
  1417. (defun event-end (e) (+ (car e) (cadr e)))
  1418.  
  1419. ;; EVENT-TIME -- time of an event
  1420. ;;
  1421. (setfn event-time car)
  1422.  
  1423. ;; EVENT-DUR -- duration of an event
  1424. ;;
  1425. (setfn event-dur cadr)
  1426.  
  1427. ;; EVENT-SET-TIME -- new event with new time
  1428. ;;
  1429. (defun event-set-time (event time)
  1430.   (cons time (cdr event)))
  1431.  
  1432.  
  1433. ;; EVENT-SET-DUR -- new event with new dur
  1434. ;;
  1435. (defun event-set-dur (event dur)
  1436.   (list (event-time event) 
  1437.         dur 
  1438.         (event-expression event)))
  1439.   
  1440.   
  1441. ;; EVENT-SET-EXPRESSION -- new event with new expression
  1442. ;;
  1443. (defun event-set-expression (event expression)
  1444.   (list (event-time event) 
  1445.         (event-dur event)
  1446.         expression))
  1447.   
  1448. ;; EXPR-HAS-ATTR -- test if expression has attribute
  1449. ;;
  1450. (defun expr-has-attr (expression attr)
  1451.   (member attr expression))
  1452.  
  1453.  
  1454. ;; EXPR-GET-ATTR -- get value of attribute from expression
  1455. ;;
  1456. (defun expr-get-attr (expression attr &optional default)
  1457.   (let ((m (member attr expression)))
  1458.     (if m (cadr m) default)))
  1459.  
  1460.  
  1461. ;; EXPR-SET-ATTR -- set value of an attribute in expression
  1462. ;; (returns new expression)
  1463. (defun expr-set-attr (expr attr value)
  1464.   (cons (car expr) (expr-parameters-set-attr (cdr expr) attr value)))
  1465.  
  1466. (defun expr-parameters-set-attr (lis attr value)
  1467.   (cond ((null lis) (list attr value))
  1468.         ((eq (car lis) attr) (cons attr (cons value (cddr lis))))
  1469.         (t (cons (car lis) 
  1470.                  (cons (cadr lis) 
  1471.                        (expr-parameters-set-attr (cddr lis) attr value))))))
  1472.  
  1473.  
  1474. ;; EXPR-REMOVE-ATTR -- expression without attribute value pair
  1475. (defun expr-remove-attr (event attr)
  1476.   (cons (car expr) (expr-parameters-remove-attr (cdr expr) attr)))
  1477.  
  1478. (defun expr-parameters-remove-attr (lis attr)
  1479.    (cond ((null lis) nil)
  1480.          ((eq (car lis) attr) (cddr lis))
  1481.          (t (cons (car lis)
  1482.                   (cons (cadr lis)
  1483.                         (expr-parameters-remove-attr (cddr lis) attr))))))
  1484.  
  1485.  
  1486. ;; EVENT-GET-ATTR -- get value of attribute from event
  1487. ;;
  1488. (defun event-get-attr (note attr &optional default)
  1489.   (expr-get-attr (event-expression note) attr default))
  1490.  
  1491.  
  1492. ;; EVENT-SET-ATTR -- new event with attribute = value
  1493. (defun event-set-attr (event attr value)
  1494.   (event-set-expression 
  1495.     event
  1496.     (expr-set-attr (event-expression event) attr value)))
  1497.  
  1498.  
  1499. ;; EVENT-REMOVE-ATTR -- new event without atttribute value pair
  1500. (defun event-remove-attr (event attr)
  1501.   (event-set-expression
  1502.      event
  1503.      (event-remove-attr (event-expression event) attr)))
  1504.  
  1505.  
  1506. ;; SCORE-GET-BEGIN -- get the begin time of a score
  1507. ;;
  1508. (defun score-get-begin (score)
  1509.   (setf score (score-must-have-begin-end score))
  1510.   (cadr (event-expression (car score))))
  1511.  
  1512.  
  1513. ;; SCORE-SET-BEGIN -- set the begin time of a score
  1514. ;;
  1515. (defun score-set-begin (score time)
  1516.   (setf score (score-must-have-begin-end score))
  1517.   (cons (list 0 0 (list 'score-begin-end time 
  1518.                         (caddr (event-expression (car score)))))
  1519.         (cdr score)))
  1520.  
  1521.  
  1522. ;; SCORE-GET-END -- get the end time of a score
  1523. ;;
  1524. (defun score-get-end (score)
  1525.   (setf score (score-must-have-begin-end score))
  1526.   (caddr (event-expression (car score))))
  1527.  
  1528.  
  1529. ;; SCORE-SET-END -- set the end time of a score
  1530. ;;
  1531. (defun score-set-end (score time)
  1532.   (setf score (score-must-have-begin-end score))
  1533.   (cons (list 0 0 (list 'score-begin-end 
  1534.                         (cadr (event-expression (car score))) time))
  1535.         (cdr score)))
  1536.  
  1537.  
  1538. ;; FIND-FIRST-NOTE -- use keywords to find index of first selected note
  1539. ;;
  1540. (defun find-first-note (score from-index from-time)
  1541.   (let ((s (cdr score)))
  1542.     ;; offset by one because we removed element 0
  1543.     (setf from-index (if from-index (max 0 (- from-index 1)) 0))
  1544.     (setf from-time (if from-time 
  1545.                         (- from-time SCORE-EPSILON)
  1546.                         (- SCORE-EPSILON)))
  1547.     (if s (setf s (nthcdr from-index s)))
  1548.     
  1549.     (while (and s (>= from-time (event-time (car s))))
  1550.       (setf s (cdr s))
  1551.       (incf from-index))
  1552.     (1+ from-index)))
  1553.  
  1554.  
  1555. ;; EVENT-BEFORE -- useful function for sorting scores
  1556. ;;
  1557. (defun event-before (a b)
  1558.   (< (car a) (car b)))
  1559.   
  1560. ;; bigsort -- a sort routine that avoids recursion in order
  1561. ;; to sort large lists without overflowing the evaluation stack
  1562. ;;
  1563. ;; Does not modify input list. Does not minimize cons-ing.
  1564. ;;
  1565. ;; Algorithm: first accumulate sorted sub-sequences into lists
  1566. ;; Then merge pairs iteratively until only one big list remains
  1567. ;; 
  1568. (defun bigsort (lis cmp) ; sort lis using cmp function
  1569.   ;; if (funcall cmp a b) then a and b are in order
  1570.   (prog (rslt sub pairs)
  1571.     ;; first, convert to sorted sublists stored on rslt
  1572.     ;; accumulate sublists in sub
  1573.    get-next-sub
  1574.     (if (null lis) (go done-1))
  1575.     (setf sub (list (car lis)))
  1576.     (setf lis (cdr lis))
  1577.    fill-sub
  1578.     ;; invariant: sub is non-empty, in reverse order
  1579.     (cond ((and lis (funcall cmp (car sub) (car lis)))
  1580.            (setf sub (cons (car lis) sub))
  1581.            (setf lis (cdr lis))
  1582.            (go fill-sub)))
  1583.     (setf sub (reverse sub)) ;; put sub in correct order
  1584.     (setf rslt (cons sub rslt)) ;; build rslt in reverse order
  1585.     (go get-next-sub)
  1586.    done-1
  1587.     ;; invariant: rslt is list of sorted sublists
  1588.     (if (cdr rslt) nil (go done-2))
  1589.     ;; invariant: rslt has at least one list
  1590.     (setf pairs rslt)
  1591.     (setf rslt nil)
  1592.    merge-pairs    ;; merge a pair and save on rslt
  1593.     (if (car pairs) nil (go end-of-pass)) ;; loop until all pairs merged
  1594.     ;; invariant: pairs has at least one list
  1595.     (setf list1 (car pairs)) ;; list1 is non-empty
  1596.     (setf list2 (cadr pairs)) ;; list2 could be empty
  1597.     (setf pairs (cddr pairs))
  1598.     (cond (list2
  1599.            (setf rslt (cons (list-merge list1 list2 cmp) rslt)))
  1600.           (t
  1601.            (setf rslt (cons list1 rslt))))
  1602.     (go merge-pairs)
  1603.    end-of-pass
  1604.     (go done-1)
  1605.    done-2
  1606.     ;; invariant: rslt has one sorted list!
  1607.     (return (car rslt))))
  1608.  
  1609. (defun list-merge (list1 list2 cmp)
  1610.   (prog (rslt)
  1611.    merge-loop
  1612.     (cond ((and list1 list2)
  1613.            (cond ((funcall cmp (car list1) (car list2))
  1614.                   (setf rslt (cons (car list1) rslt))
  1615.                   (setf list1 (cdr list1)))
  1616.                  (t
  1617.                   (setf rslt (cons (car list2) rslt))
  1618.                   (setf list2 (cdr list2)))))
  1619.           (list1
  1620.            (return (nconc (reverse rslt) list1)))
  1621.           (t
  1622.            (return (nconc (reverse rslt) list2))))
  1623.     (go merge-loop)))  
  1624.  
  1625.  
  1626. ;; SCORE-SORT -- sort a score into time order
  1627. ;;
  1628. (defun score-sort (score &optional (copy-flag t)) 
  1629.   (setf score (score-must-have-begin-end score))
  1630.   (let ((begin-end (car score)))
  1631.     (setf score (cdr score))
  1632.     (if copy-flag (setf score (append score nil)))
  1633.     (cons begin-end (bigsort score #'event-before))))
  1634.   
  1635.  
  1636. ;; PUSH-SORT -- insert an event in (reverse) sorted order
  1637. ;;
  1638. ;; Note: Score should NOT have a score-begin-end expression
  1639. ;;
  1640. (defun push-sort (event score)
  1641.   (let (insert-after)
  1642.     (cond ((null score) (list event))
  1643.           ((event-before (car score) event)
  1644.            (cons event score))
  1645.           (t
  1646.            (setf insert-after score)
  1647.            (while (and (cdr insert-after) 
  1648.                        (event-before event (cadr insert-after)))
  1649.              (setf insert-after (cdr insert-after)))
  1650.            (setf (cdr insert-after) (cons event (cdr insert-after)))
  1651.            score))))
  1652.  
  1653.  
  1654. (setf FOREVER 3600000000.0) ; 1 million hours
  1655.  
  1656. ;; FIND-LAST-NOTE -- use keywords to find index beyond last selected note
  1657. ;;
  1658. ;; note that the :to-index keyword is the index of the last note (numbered
  1659. ;; from zero), whereas this function returns the index of the last note
  1660. ;; plus one, i.e. selected notes have an index *less than* this one
  1661. ;;
  1662. (defun find-last-note (score to-index to-time)
  1663.   ;; skip past score-begin-end event
  1664.   (let ((s (cdr score))
  1665.         (n 1))
  1666.     (setf to-index (if to-index (1+ to-index) (length score)))
  1667.     (setf to-time (if to-time (- to-time SCORE-EPSILON)  FOREVER))
  1668.     (while (and s (< n to-index) (< (event-time (car s)) to-time))
  1669.       (setf s (cdr s))
  1670.       (incf n))
  1671.     n))
  1672.  
  1673.  
  1674. ;; SCORE-MUST-HAVE-BEGIN-END -- add score-begin-end event if necessary
  1675. ;;
  1676. (defun score-must-have-begin-end (score)
  1677.   (cond ((null score) 
  1678.          (list (list 0 0 (list 'SCORE-BEGIN-END 0 0))))
  1679.         ((eq (car (event-expression (car score))) 'SCORE-BEGIN-END)
  1680.          score)
  1681.         (t (cons (list 0 0 (list 'SCORE-BEGIN-END (event-time (car score))
  1682.                                  (event-end (car (last score)))))
  1683.                  score))))
  1684.  
  1685.  
  1686. ;; SCORE-SHIFT -- add offset to times of score events
  1687. ;;
  1688. (defun score-shift (score offset &key from-index to-index from-time to-time)
  1689.   (setf score (score-must-have-begin-end score))
  1690.   (let ((i 1) 
  1691.         (start (find-first-note score from-index from-time))
  1692.         (stop (find-last-note score to-index to-time))
  1693.         (end (caddr (event-expression (car score))))
  1694.         result)
  1695.     (dolist (event (cdr score))
  1696.       (cond ((and (<= start i) (< i stop))
  1697.              (setf event (event-set-time 
  1698.                           event (+ (event-time event) offset)))
  1699.              (setf end (max end (event-end event)))))
  1700.       (setf result (push-sort event result))
  1701.       (incf i))
  1702.     (cons (list 0 0 (list 'SCORE-BEGIN-END
  1703.                           (cadr (event-expression (car score)))
  1704.                           end))
  1705.           (reverse result))))
  1706.  
  1707.  
  1708. ;; TIME-STRETCH -- map a timestamp according to stretch factor
  1709. ;;
  1710. (defun time-stretch (time stretch start-time stop-time)
  1711.   (cond ((< time start-time) time)
  1712.         ((< time stop-time) 
  1713.          (+ start-time (* stretch (- time start-time))))
  1714.         (t ; beyond stop-time
  1715.          (+ (- time stop-time) ; how much beyond stop-time
  1716.             start-time
  1717.             (* stretch (- stop-time start-time))))))
  1718.          
  1719.  
  1720. ;; EVENT-STRETCH -- apply time warp to an event
  1721. (defun event-stretch (event stretch dur-flag time-flag start-time stop-time)
  1722.   (let* ((new-time (event-time event))
  1723.          (new-dur (event-dur event))
  1724.          (end-time (+ new-time new-dur)))
  1725.     (cond (time-flag
  1726.            (setf new-time (time-stretch new-time stretch 
  1727.                                         start-time stop-time))))
  1728.     (cond ((and time-flag dur-flag)
  1729.            ;; both time and dur are stretched, so map the end time just
  1730.            ;; like the start time, then subtract to get new duration
  1731.            (setf end-time (time-stretch end-time stretch
  1732.                                         start-time stop-time))
  1733.            (setf new-dur (- end-time new-time)))
  1734.           ((and dur-flag (>= new-time start-time) (< new-time stop-time))
  1735.            ;; stretch only duration, not time. If note starts in range
  1736.            ;; scale to get the new duration.
  1737.            (setf new-dur (* stretch new-dur))))
  1738.     (list new-time new-dur (event-expression event))))
  1739.  
  1740.  
  1741. ;; SCORE-STRETCH -- stretch a region of the score
  1742. ;;
  1743. (defun score-stretch (score factor &key (dur t) (time t)
  1744.                       from-index to-index (from-time 0) (to-time FOREVER))
  1745.   (setf score (score-must-have-begin-end score))
  1746.   (let ((begin-end (event-expression (car score)))
  1747.         (i 1))
  1748.     (if from-index
  1749.         (setf from-time (max from-time 
  1750.                              (event-time (nth from-index score)))))
  1751.     (if to-index
  1752.         (setf to-time (min to-time 
  1753.                            (event-end (nth to-index score)))))
  1754.     ; stretch from start-time to stop-time
  1755.     (cons (list 0 0 (list 'SCORE-BEGIN-END 
  1756.                           (time-stretch (cadr begin-end) factor 
  1757.                                         from-time to-time)
  1758.                           (time-stretch (caddr begin-end) factor
  1759.                                         from-time to-time)))
  1760.           (mapcar #'(lambda (event) 
  1761.                       (event-stretch event factor dur time
  1762.                                      from-time to-time))
  1763.                   (cdr score)))))
  1764.     
  1765.           
  1766. (defun params-transpose (params keyword amount)
  1767.   (cond ((null params) nil)
  1768.         ((and (eq keyword (car params))
  1769.               (numberp (cadr params)))
  1770.          (cons (car params)
  1771.                (cons (+ amount (cadr params))
  1772.                      (cddr params))))
  1773.         (t (cons (car params)
  1774.                  (cons (cadr params)
  1775.                        (params-transpose (cddr params) keyword amount))))))
  1776.  
  1777.  
  1778. (defun score-transpose (score keyword amount &key
  1779.                         from-index to-index from-time to-time)
  1780.   (score-apply score 
  1781.                #'(lambda (time dur expression)
  1782.                    (list time dur 
  1783.                          (cons (car expression)
  1784.                                (params-transpose (cdr expression)
  1785.                                                  keyword amount))))
  1786.                :from-index from-index :to-index to-index
  1787.                :from-time from-time :to-time to-time))
  1788.  
  1789.  
  1790. (defun params-scale (params keyword amount)
  1791.   (cond ((null params) nil)
  1792.         ((and (eq keyword (car params))
  1793.               (numberp (cadr params)))
  1794.          (cons (car params)
  1795.                (cons (* amount (cadr params))
  1796.                      (cddr params))))
  1797.         (t (cons (car params)
  1798.                  (cons (cadr params)
  1799.                        (params-scale (cddr params) keyword amount))))))
  1800.  
  1801.  
  1802. (defun score-scale (score keyword amount &key
  1803.                     from-index to-index from-time to-time)
  1804.   (score-apply score 
  1805.                #'(lambda (time dur expression)
  1806.                    (list time dur
  1807.                          (cons (car expression)
  1808.                                (params-scale (cdr expression)
  1809.                                              keyword amount))))
  1810.                :from-index from-index :to-index to-index
  1811.                :from-time from-time :to-time to-time))
  1812.  
  1813.  
  1814. (defun score-sustain (score factor &key
  1815.                       from-index to-index from-time to-time)
  1816.   (setf score (score-must-have-begin-end score))
  1817.   (let ((i 0)
  1818.         (start (find-first-note score from-index from-time))
  1819.         (stop (find-last-note score to-index to-time))
  1820.         result)
  1821.     (dolist (event score)
  1822.       (cond ((and (<= start i) (< i stop))
  1823.              (setf event (event-set-dur
  1824.                           event (* (event-dur event) factor)))))
  1825.       (push event result)
  1826.       (incf i))
  1827.     (reverse result)))
  1828.  
  1829.  
  1830. (defun map-voice (expression replacement-list)
  1831.   (let ((mapping (assoc (car expression) replacement-list)))
  1832.     (cond (mapping (cons (second mapping)
  1833.                          (cdr expression)))
  1834.           (t expression))))
  1835.  
  1836.  
  1837. (defun score-voice (score replacement-list &key
  1838.                     from-index to-index from-time to-time)
  1839.   (setf score (score-must-have-begin-end score))
  1840.   (let ((i 0) 
  1841.         (start (find-first-note score from-index from-time))
  1842.         (stop (find-last-note score to-index to-time))
  1843.         result)
  1844.     (dolist (event score)
  1845.       (cond ((and (<= start i) (< i stop))
  1846.              (setf event (event-set-expression
  1847.                           event (map-voice (event-expression event)
  1848.                                            replacement-list)))))
  1849.       (push event result)
  1850.       (incf i))
  1851.     (reverse result)))
  1852.  
  1853.  
  1854. (defun score-merge (&rest scores)
  1855.   ;; scores is a list of scores
  1856.   (cond ((null scores) nil)
  1857.         (t
  1858.          (score-merge-1 (car scores) (cdr scores)))))
  1859.  
  1860.  
  1861. ;; SCORE-MERGE-1 -- merge list of scores into score
  1862. ;;
  1863. (defun score-merge-1 (score scores)
  1864.   ;; scores is a list of scores to merge
  1865.   (cond ((null scores) score)
  1866.         (t (score-merge-1 (score-merge-2 score (car scores))
  1867.                           (cdr scores)))))
  1868.  
  1869. ;; SCORE-MERGE-2 -- merge 2 scores
  1870. ;;
  1871. (defun score-merge-2 (score addin)
  1872.   ;(display "score-merge-2 before" score addin)
  1873.   (setf score (score-must-have-begin-end score))
  1874.   (setf addin (score-must-have-begin-end addin))
  1875.   ;(display "score-merge-2" score addin)
  1876.   (let (start1 start2 end1 end2)
  1877.     (setf start1 (score-get-begin score))
  1878.     (setf start2 (score-get-begin addin))
  1879.     (setf end1 (score-get-end score))
  1880.     (setf end2 (score-get-end addin))
  1881.     
  1882.     ;; note: score-sort is destructive, but append copies score
  1883.     ;;       and score-shift copies addin
  1884.     (score-sort
  1885.      (cons (list 0 0 (list 'SCORE-BEGIN-END (min start1 start2)
  1886.                            (max end1 end2)))
  1887.            (append (cdr score) (cdr addin) nil)))))
  1888.  
  1889.  
  1890.  
  1891. ;; SCORE-APPEND -- append scores together in sequence
  1892. ;;
  1893. (defun score-append (&rest scores)
  1894.   ;; scores is a list of scores
  1895.   (cond ((null scores) nil)
  1896.         (t
  1897.          (score-append-1 (car scores) (cdr scores)))))
  1898.  
  1899.  
  1900. ;; SCORE-APPEND-1 -- append list of scores into score
  1901. ;;
  1902. (defun score-append-1 (score scores)
  1903.   ;; scores is a list of scores to append
  1904.   (cond ((null scores) score)
  1905.         (t (score-append-1 (score-append-2 score (car scores))
  1906.                            (cdr scores)))))
  1907.  
  1908.  
  1909. ;; SCORE-APPEND-2 -- append 2 scores
  1910. ;;
  1911. (defun score-append-2 (score addin)
  1912.   ;(display "score-append-2" score addin)
  1913.   (setf score (score-must-have-begin-end score))
  1914.   (setf addin (score-must-have-begin-end addin))
  1915.   (let (end1 start2 begin-end1 begin-end2)
  1916.     (setf start1 (score-get-begin score))
  1917.     (setf end1 (score-get-end score))
  1918.     (setf start2 (score-get-begin addin))
  1919.     (setf end2 (score-get-end addin))
  1920.     (setf begin-end1 (event-expression (car score)))
  1921.     (setf begin-end2 (event-expression (car addin)))
  1922.     (setf addin (score-shift addin (- end1 start2)))
  1923.     ;; note: score-sort is destructive, but append copies score
  1924.     ;;       and score-shift copies addin
  1925.     (score-sort
  1926.      (cons (list 0 0 (list 'SCORE-BEGIN-END start1 (+ end1 (- end2 start2))))
  1927.            (append (cdr score) (cdr addin) nil)))))
  1928.  
  1929.  
  1930. (defun score-select (score predicate &key
  1931.                     from-index to-index from-time to-time reject)
  1932.   (setf score (score-must-have-begin-end score))
  1933.   (let ((begin-end (car score))
  1934.         (i 1) 
  1935.         (start (find-first-note score from-index from-time))
  1936.         (stop (find-last-note score to-index to-time))
  1937.         result)
  1938.     ;; selected if start <= i AND i < stop AND predicate(...)
  1939.     ;; choose if not reject and selected or reject and not selected
  1940.     ;; so in other words choose if reject != selected. Use NULL to
  1941.     ;; coerce into boolean values and then use NOT EQ to compare
  1942.     (dolist (event (cdr score))
  1943.       (cond ((not (eq (null reject)
  1944.                       (null (and (<= start i) (< i stop)
  1945.                                  (or (eq predicate t)
  1946.                                      (funcall predicate 
  1947.                                       (event-time event) 
  1948.                                       (event-dur event) 
  1949.                                       (event-expression event)))))))
  1950.              (push event result)))
  1951.       (incf i))
  1952.     (cons begin-end (reverse result))))
  1953.  
  1954.  
  1955. ;; SCORE-FILTER-LENGTH -- remove notes beyond cutoff time
  1956. ;;
  1957. (defun score-filter-length (score cutoff)
  1958.   (let (result)
  1959.     (dolist (event score)
  1960.       (cond ((<= (event-end event) cutoff)
  1961.              (push event result))))
  1962.     (reverse result)))
  1963.  
  1964.  
  1965. ;; SCORE-REPEAT -- make n copies of score in sequence
  1966. ;;
  1967. (defun score-repeat (score n)
  1968.   (let (result)
  1969.     (dotimes (i n)
  1970.       (setf result (score-append result score)))
  1971.     result))
  1972.  
  1973.  
  1974. ;; SCORE-STRETCH-TO-LENGTH -- stretch score to have given length
  1975. ;;
  1976. (defun score-stretch-to-length (score length)
  1977.   (let ((begin-time (score-get-begin score))
  1978.         (end-time (score-get-end score))
  1979.         duration stretch)
  1980.     (setf duration (- end-time begin-time))
  1981.     (cond ((< 0 duration)
  1982.            (setf stretch (/ length (- end-time begin-time)))
  1983.            (score-stretch score stretch))
  1984.           (t score))))
  1985.  
  1986.  
  1987. (defun score-filter-overlap (score)
  1988.   (setf score (score-must-have-begin-end score))
  1989.   (prog (event end-time filtered-score
  1990.          (begin-end (car score)))
  1991.     (setf score (cdr score))
  1992.     (cond ((null score) (return (list begin-end))))
  1993.   loop
  1994.     ;; get event from score
  1995.     (setf event (car score))
  1996.     ;; add a note to filtered-score
  1997.     (push event filtered-score)
  1998.     ;; save the end-time of this event: start + duration
  1999.     (setf end-time (+ (car event) (cadr event)))
  2000.     ;; now skip everything until end-time in score
  2001.   loop2
  2002.     (pop score) ;; move to next event in score
  2003.     (cond ((null score) 
  2004.            (return (cons begin-end (reverse filtered-score)))))
  2005.     (setf event (car score)) ;; examine next event
  2006.     (setf start-time (car event))
  2007.     ;(display "overlap" start-time (- end-time SCORE-EPSILON))
  2008.     (cond ((< start-time (- end-time SCORE-EPSILON))
  2009.            ;(display "toss" event start-time end-time)
  2010.            (go loop2)))
  2011.     (go loop)))
  2012.  
  2013.  
  2014. (defun score-print (score)
  2015.  (format t "(")
  2016.  (dolist (event score)
  2017.   (format t "~S~%" event))
  2018.  (format t ")~%"))
  2019.  
  2020. (defun score-play (score)
  2021.   (play (timed-seq score)))
  2022.  
  2023.  
  2024. (defun score-adjacent-events (score function &key
  2025.                               from-index to-index from-time to-time)
  2026.   (setf score (score-must-have-begin-end score))
  2027.   (let ((begin-end (car score))
  2028.         (a nil)
  2029.         (b (second score))
  2030.         (c-list (cddr score))
  2031.         r newscore
  2032.         (i 1)
  2033.         (start (find-first-note score from-index from-time))
  2034.         (stop (find-last-note score to-index to-time)))
  2035.     (dolist (event (cdr score))
  2036.       (setf r b)
  2037.       (cond ((and (<= start i) (< i stop))
  2038.              (setf r (funcall function a b (car c-list)))))
  2039.       (cond (r
  2040.              (push r newscore)
  2041.              (setf a r)))
  2042.       (setf b (car c-list))
  2043.       (setf c-list (cdr c-list))
  2044.       (incf i))
  2045.     (score-sort (cons begin-end newscore))))
  2046.  
  2047.  
  2048. (defun score-apply (score fn &key
  2049.                     from-index to-index from-time to-time)
  2050.  
  2051.   (setf score (score-must-have-begin-end score))
  2052.   (let ((begin-end (car score))
  2053.         (i 1) 
  2054.         (start (find-first-note score from-index from-time))
  2055.         (stop (find-last-note score to-index to-time))
  2056.         result)
  2057.     (dolist (event (cdr score))
  2058.       (push 
  2059.        (cond ((and (<= start i) (< i stop))
  2060.               (funcall fn (event-time event)
  2061.                           (event-dur event) (event-expression event)))
  2062.              (t event))
  2063.        result)
  2064.       (incf i))
  2065.     (score-sort (cons begin-end result))))
  2066.  
  2067.  
  2068. (defun score-indexof (score fn &key
  2069.                       from-index to-index from-time to-time)
  2070.   (setf score (score-must-have-begin-end score))
  2071.   (let ((i 1) 
  2072.         (start (find-first-note score from-index from-time))
  2073.         (stop (find-last-note score to-index to-time))
  2074.         result)
  2075.     (dolist (event (cdr score))
  2076.       (cond ((and (<= start i) (< i stop)
  2077.                   (funcall fn (event-time event)
  2078.                               (event-dur event)
  2079.                               (event-expression event)))
  2080.              (setf result i)
  2081.              (return)))
  2082.       (incf i))
  2083.     result))
  2084.  
  2085.  
  2086. (defun score-last-indexof (score fn &key
  2087.                            from-index to-index from-time to-time)
  2088.   (setf score (score-must-have-begin-end score))
  2089.   (let ((i 1) 
  2090.         (start (find-first-note score from-index from-time))
  2091.         (stop (find-last-note score to-index to-time))
  2092.         result)
  2093.     (dolist (event (cdr score))
  2094.       (cond ((and (<= start i) (< i stop)
  2095.                   (funcall fn (event-time event)
  2096.                            (event-dur event)
  2097.                            (event-expression event)))
  2098.              (setf result i)))
  2099.       (incf i))
  2100.     result))
  2101.  
  2102.  
  2103. ;; SCORE-RANDOMIZE-START -- alter start times with offset
  2104. ;; keywords: jitter, offset, feel factor
  2105. ;;
  2106. (defun score-randomize-start (score amt &key
  2107.                               from-index to-index from-time to-time)
  2108.   (score-apply score
  2109.                (lambda (time dur expr)
  2110.                  (setf time (+ (real-random (- amt) amt) time))
  2111.                  (setf time (max 0.0 time))
  2112.                  (list time dur expr))))
  2113.  
  2114.  
  2115. ;; SCORE-READ-SMF -- read a standard MIDI file to a score
  2116. ;;
  2117. (defun score-read-smf (filename)
  2118.   (let ((seq (seq-create))
  2119.         (file (open-binary filename)))
  2120.     (cond (file
  2121.            (seq-read-smf seq file)
  2122.            (close file)
  2123.            (score-from-seq seq))
  2124.           (t nil))))
  2125.  
  2126.  
  2127. ;; SET-PROGRAM-TO -- a helper function to set a list value
  2128. (defun set-program-to (lis index value default)
  2129.   ;; if length or lis <= index, extend the lis with default
  2130.   (while (<= (length lis) index)
  2131.     (setf lis (nconc lis (list default))))
  2132.   ;; set the nth element
  2133.   (setf (nth index lis) value)
  2134.   ;; return the list
  2135.   lis)
  2136.  
  2137.  
  2138. (defun score-from-seq (seq)
  2139.   (prog (event tag score programs)
  2140.     (seq-reset seq)
  2141. loop
  2142.     (setf event (seq-get seq))
  2143.     (setf tag (seq-tag event))
  2144.     (cond ((= tag seq-done-tag)
  2145.            (go exit))
  2146.           ((= tag seq-prgm-tag)
  2147.            (let ((chan (seq-channel event))
  2148.                  (when (seq-time event))
  2149.                  (program (seq-program event)))
  2150.              (setf programs (set-program-to programs chan program 0))
  2151.              (push (list (* when 0.001) 1
  2152.                          (list 'NOTE :pitch nil :program program))
  2153.                    score)))
  2154.           ((= tag seq-note-tag)
  2155.          (let ((chan (seq-channel event))
  2156.                  (pitch (seq-pitch event))
  2157.                  (vel (seq-velocity event))
  2158.                  (when (seq-time event))
  2159.                  (dur (seq-duration event)))
  2160.              (push (list (* when 0.001) (* dur 0.001)
  2161.                        (list 'NOTE :chan (1- chan) :pitch pitch :vel vel))
  2162.                    score))))
  2163.     (seq-next seq)
  2164.     (go loop)
  2165. exit
  2166.     (setf *rslt* programs) ;; extra return value
  2167.     (return (score-sort score))))
  2168.  
  2169.  
  2170. (defun score-write-smf (score filename &optional programs)
  2171.   (let ((file (open-binary filename :direction :output))
  2172.         (seq (seq-create))
  2173.         (chan 1))
  2174.     (cond (file
  2175.            (dolist (program programs)
  2176.              ;; 6 = SEQ_PROGRAM
  2177.              (seq-insert-ctrl seq 0 0 6 chan program)
  2178.              ;(display "insert ctrl" seq 0 0 6 chan program)
  2179.              (incf chan))
  2180.  
  2181.            (dolist (event (cdr (score-must-have-begin-end score)))
  2182.              (let ((time (event-time event))
  2183.                    (dur (event-dur event))
  2184.                    (chan (event-get-attr event :chan 0))
  2185.                    (pitch (event-get-attr event :pitch))
  2186.                    (program (event-get-attr event :program))
  2187.                    (vel (event-get-attr event :vel 100)))
  2188.                (cond (program
  2189.                       ;(display "score-write-smf program" chan program)
  2190.                       (seq-insert-ctrl seq (round (* time 1000))
  2191.                                        0 6 (1+ chan)
  2192.                                        (round program))))
  2193.                (cond ((consp pitch)
  2194.                       (dolist (p pitch)
  2195.                         (seq-insert-note seq (round (* time 1000))
  2196.                                          0 (1+ chan) (round p) 
  2197.                                          (round (* dur 1000)) (round vel))))
  2198.                      (pitch
  2199.                       (seq-insert-note seq (round (* time 1000))
  2200.                                        0 (1+ chan) (round pitch)
  2201.                                        (round (* dur 1000)) (round vel))))))
  2202.            (seq-write-smf seq file)
  2203.            (close file)))))
  2204.  
  2205.  
  2206. ;; make a default note function for scores
  2207. ;;
  2208. (defun note (&key (pitch 60) (vel 100))
  2209.   ;; load the piano if it is not loaded already
  2210.   (if (not (boundp '*piano-srate*)) 
  2211.       (abs-env (load "pianosyn")))
  2212.   (piano-note-2 pitch vel))
  2213.  
  2214. ;;================================================================
  2215.  
  2216. ;; WORKSPACE functions have moved to envelopes.lsp
  2217.  
  2218.  
  2219. ;; DESCRIBE -- add a description to a global variable
  2220. ;;
  2221. (defun describe (symbol &optional description)
  2222.   (add-to-workspace symbol)
  2223.   (cond (description
  2224.          (putprop symbol description 'description))
  2225.         (t
  2226.          (get symbol 'description))))
  2227.  
  2228. ;; INTERPOLATE -- linear interpolation function
  2229. ;;
  2230. ;; compute y given x by interpolating between points (x1, y1) and (x2, y2)
  2231. (defun interpolate (x x1 y1 x2 y2)
  2232.   (cond ((= x1 x2) x1)
  2233.         (t (+ y1 (* (- x x1) (/ (- y2 y1) (- x2 (float x1))))))))
  2234.  
  2235.  
  2236. ;; INTERSECTION -- set intersection
  2237. ;;
  2238. ;; compute the intersection of two lists
  2239. (defun intersection (a b)
  2240.   (let (result)
  2241.     (dolist (elem a)
  2242.       (if (member elem b) (push elem result)))
  2243.     result))
  2244.  
  2245. ;; UNION -- set union
  2246. ;;
  2247. ;; compute the union of two lists
  2248. (defun union (a b)
  2249.   (let (result)
  2250.     (dolist (elem a)
  2251.       (if (not (member elem result)) (push elem result)))
  2252.     (dolist (elem b)
  2253.       (if (not (member elem result)) (push elem result)))
  2254.     result))
  2255.  
  2256. ;; SET-DIFFERENCE -- set difference
  2257. ;;
  2258. ;; compute the set difference between two sets
  2259. (defun set-difference (a b)
  2260.   (remove-if (lambda (elem) (member elem b)) a))
  2261.  
  2262. ;; SUBSETP -- test is list is subset
  2263. ;;
  2264. ;; test if a is subset of b
  2265. (defun subsetp (a b)
  2266.   (let ((result t))
  2267.     (dolist (elem a)
  2268.       (cond ((not (member elem b))
  2269.              (setf result nil)
  2270.              (return nil))))
  2271.     result))
  2272.  
  2273. ;; functions to support score editing in jNyqIDE
  2274.  
  2275. (if (not (boundp '*default-score-file*))
  2276.     (setf *default-score-file* "score.dat"))
  2277.  
  2278. ;; SCORE-EDIT -- save a score for editing by jNyqIDE
  2279. ;;
  2280. ;; file goes to a data file to be read by jNyqIDE
  2281. ;; Note that the parameter is a global variable name, not a score,
  2282. ;; but you do not quote the global variable name, e.g. call
  2283. ;;    (score-edit my-score)
  2284. ;;
  2285. (defmacro score-edit (score-name)
  2286.     `(score-edit-symbol (quote ,score-name)))
  2287.  
  2288. (defun score-edit-symbol (score-name)
  2289.     (prog ((f (open *default-score-file* :direction :output))
  2290.            score expr)
  2291.       (cond ((symbolp score-name)
  2292.              (setf score (eval score-name)))
  2293.             (t
  2294.              (error "score-edit expects a symbol naming the score to edit")))
  2295.       (cond ((null f)
  2296.         (format t "score-edit: error in output file ~A!~%" *default-score-file*)
  2297.         (return nil)))
  2298.  
  2299.       (format t "score-edit: writing ~A ...~%" *default-score-file*)
  2300.       (format f "~A~%" score-name) ; put name on first line
  2301.       (dolist (event score) ;cdr scor
  2302.         (format f "~A " (event-time event))  ; print start time
  2303.         (format f "~A " (event-dur event))   ; print duration
  2304.  
  2305.         (setf expr (event-expression event))
  2306.  
  2307.         ; print the pitch and the rest of the attributes
  2308.         (format f "~A " (expr-get-attr expr :pitch))
  2309.         (format f "~A~%" (expr-parameters-remove-attr expr :pitch)))
  2310.       (close f)
  2311.       (format t "score-edit: wrote ~A events~%" (length score))))
  2312.  
  2313.  
  2314. ;; Read in a data file stored in the score-edit format and save
  2315. ;; it to the global variable it came from
  2316. (defun score-restore ()
  2317.   (prog ((inf (open *default-score-file*))
  2318.          name start dur pitch expr score)
  2319.     (cond ((null inf)
  2320.            (format t "score-restore: could not open ~A~%" *default-score-file*)
  2321.            (return nil)))
  2322.     (setf name (read inf)) ;; score name
  2323.     (loop
  2324.       (setf start (read inf))
  2325.       (cond ((null start) (return)))
  2326.       (setf dur (read inf))
  2327.       (setf pitch (read inf))
  2328.       (setf expr (read inf))
  2329.       (cond (pitch
  2330.              (setf expr (expr-set-attr expr :pitch pitch)))))
  2331.     (close inf)
  2332.     (setf (symbol-value name) score)))
  2333.