id
int64 0
45.1k
| file_name
stringlengths 4
68
| file_path
stringlengths 14
193
| content
stringlengths 32
9.62M
| size
int64 32
9.62M
| language
stringclasses 1
value | extension
stringclasses 6
values | total_lines
int64 1
136k
| avg_line_length
float64 3
903k
| max_line_length
int64 3
4.51M
| alphanum_fraction
float64 0
1
| repo_name
stringclasses 779
values | repo_stars
int64 0
882
| repo_forks
int64 0
108
| repo_open_issues
int64 0
90
| repo_license
stringclasses 8
values | repo_extraction_date
stringclasses 146
values | sha
stringlengths 64
64
| __index_level_0__
int64 0
45.1k
| exdup_ids_cmlisp_stkv2
sequencelengths 1
47
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
33,640 | integer-affine-trans.lsp | rwoldford_Quail/source/window-basics/transforms/integer-affine-trans.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; integer-affine-trans.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;;
;;; This file is an addition to Window-basics for moving pointclouds
;;;
;;;
;;; Authors:
;;; H.A. Chipman 1991
;;; C.B. Hurley 1991 George Washington University
;;;
;;;
;;;
;;;
;;;
;;;----------------------------------------------------------------------------------
;;; A modified version of affinetrans.lisp. It includes more specific subclasses,
;;; such as:
;;;
;;; affine-transform---- 2d-affine----- 2d-shift
;;; \
;;; \_ 3d-affine----- 3d-rotate------ 3d-x-rotate
;;; | |
;;; |----- 3d-scale |- 3d-y-rotate
;;; | |
;;; |_____ 3d-shift |_ 3d-z-rotate
;;; |
;;; |_ 3d-axis-rotate
;;;
;;; The modifications include integer math, apply-transform methods for arrays of data,
;;; and the extended classes described above.
(in-package :wb)
(defclass affine-transform ()
((dimension
:initarg :dimension
:accessor dimension-of
:documentation "The true dimension of the transform, (n * n)")
(affine
:initarg :affine
:accessor matrix-of
:documentation "an (n+1) *(n+1) array of reals, first n rows and colums represent the transformation, the last column represents the location shift")
)
(:documentation
"Affine transformations for viewing 2 and 3 dimensional objects. See Foley and Van Dam for reference. Note the transforms here operate on columns whereas those in F+VD operate on row vectors"
))
(defclass 2d-affine (affine-transform)
((affine
:documentation "a 3 by 3 array of reals, first 2 rows and colums represent the transformation, the last column represents the location shift")
(x-function
:accessor x-function
:documentation "function applied to object to retrieve its x location")
(y-function
:accessor y-function
:documentation "function applied to object to retrieve its y location")
(dimension
:initform 2
:documentation " the true dimension of the transform, 2 by 2")))
(defclass 3d-affine (affine-transform)
((affine
:documentation "a 4 by 4 array of reals, first 3 rows and colums represent the transformation, the last column represents the location shift")
(x-function
:accessor x-function
:documentation "function applied to object to retrieve its x location")
(y-function
:accessor y-function
:documentation "function applied to object to retrieve its y location")
(z-function
:accessor z-function
:documentation "function applied to object to retrieve its z location")
(dimension
:initform 3
:documentation " the true dimension of the transform, 3 by 3")))
(defclass 2d-shift (2d-affine)
((x-shift :initarg :x-shift
:accessor x-shift-of
:documentation "The translation applied to the x-axis")
(y-shift :initarg :y-shift
:accessor y-shift-of
:documentation "The translation applied to the y-axis")))
(defclass 3d-rotate (3d-affine)
((angle :initarg :angle
:accessor angle-of
:documentation "The angle of rotation")))
(defclass 3d-axis-rotate (3d-rotate)
((x-component :initarg :x-component
:accessor x-component-of
:documentation "The x-component of the arbitrary axis (length=1)")
(y-component :initarg :y-component
:accessor y-component-of
:documentation "The y-component of the arbitrary axis (length=1)")
(z-component :initarg :z-component
:accessor z-component-of
:documentation "The z-component of the arbitrary axis (length=1)")))
(defclass 3d-x-rotate (3d-rotate) ())
(defclass 3d-y-rotate (3d-rotate) ())
(defclass 3d-z-rotate (3d-rotate) ())
(defclass 3d-shift (3d-affine)
((x-shift :initarg :x-shift
:accessor x-shift-of
:documentation "The translation applied to the x-axis")
(y-shift :initarg :y-shift
:accessor y-shift-of
:documentation "The translation applied to the y-axis")
(z-shift :initarg :z-shift
:accessor z-shift-of
:documentation "The translation applied to the z-axis")))
(defclass 3d-scale (3d-affine)
((x-scale :initarg :x-scale
:accessor x-scale-of
:documentation "The scaling applied to the x-axis")
(y-scale :initarg :x-scale
:accessor y-scale-of
:documentation "The scaling applied to the y-axis")
(z-scale :initarg :z-scale
:accessor z-scale-of
:documentation "The scaling applied to the z-axis")))
(defmethod apply-transform ((self 2d-shift) (a array))
"apply a shift transform to a data array. Observations correspond to rows~
This routine returns a *new* array. Integer calculations are used, and ~
an INTEGER ARRAY MUST BE GIVEN TO THIS ROUTINE!!!"
(make-array (list (first (array-dimensions a)) 2)
:initial-contents
(loop for i from 0 to (- (first (array-dimensions a)) 1)
collect (list (+ (aref a i 0) (x-shift-of self))
(+ (aref a i 1) (y-shift-of self))))))
;;; Note that apply-transform is not optimized for speed like the other apply-transforms
;;; that rotate three-d data.
(defmethod apply-transform ((self 3d-axis-rotate) (a array))
"rotate an array about an arbitrary axis through a given angle, specified~
by the transformation. Observations in the array correspons to rows~
in the order x,y,z. This routine returns a *new* array. Integer~
calculations are used, and an INTEGER ARRAY MUST BE GIVEN TO THIS ROUTINE!!!"
(make-array (list (first (array-dimensions a)) 3)
:initial-contents
(let* ((c (cos (angle-of self)))
(s (sin (angle-of self)))
(u (- 1 c))
(xc (x-component-of self))
(yc (y-component-of self))
(zc (z-component-of self))
)
(loop for i from 0 to (- (first (array-dimensions a)) 1)
collect (let ((x (aref a i 0))
(y (aref a i 1))
(z (aref a i 2)))
(list (round (+ (* x (+ (* u xc xc) c))
(* y (- (* u xc yc) (* s zc)))
(* z (+ (* u xc zc) (* s yc)))))
(round (+ (* x (+ (* u xc yc) (* s zc)))
(* y (+ (* u yc yc) c))
(* z (- (* u yc zc) (* s xc)))))
(round (+ (* x (- (* u xc zc) (* s yc)))
(* y (+ (* u yc zc) (* s xc)))
(* z (+ (* u zc zc) c))))))))))
(defmethod apply-transform ((self 3d-x-rotate) (a array))
"rotate an array about the x axis through a given angle, specified~
by the transformation. Observations in the array correspons to rows~
in the order x,y,z. This routine returns a *new* array. Integer~
calculations are used, and an INTEGER ARRAY MUST BE GIVEN TO THIS ROUTINE!!!"
(make-array (list (first (array-dimensions a)) 3)
:initial-contents
(let ((c (round (* 1024 (cos (angle-of self)))))
(s (round (* 1024 (sin (angle-of self))))))
(loop for i from 0 to (- (first (array-dimensions a)) 1)
collect (let ((y (aref a i 1))
(z (aref a i 2)))
(list (aref a i 0)
(ash (- (* y c) (* z s)) -10)
(ash (+ (* y s) (* z c)) -10)))))))
(defmethod apply-transform ((self 3d-y-rotate) (a array))
"rotate an array about the y axis through a given angle, specified~
by the transformation. Observations in the array correspons to rows~
in the order x,y,z. This returns a *new* array. Integer~
calculations are used, and an INTEGER ARRAY MUST BE GIVEN TO THIS ROUTINE!!!"
(make-array (list (first (array-dimensions a)) 3)
:initial-contents
(let ((c (round (* 1024 (cos (angle-of self)))))
(s (round (* 1024 (sin (angle-of self))))))
(loop for i from 0 to (- (first (array-dimensions a)) 1)
collect (let ((x (aref a i 0))
(z (aref a i 2)))
(list (ash (+ (* x c) (* z s)) -10)
(aref a i 1)
(ash (- (* z c) (* x s)) -10)))))))
(defmethod apply-transform ((self 3d-z-rotate) (a array))
"rotate an array about the z axis through a given angle, specified~
by the transformation. Observations in the array correspons to rows~
in the order x,y,z. This returns a *new* array. Integer~
calculations are used, and an INTEGER ARRAY MUST BE GIVEN TO THIS ROUTINE!!!"
(make-array (list (first (array-dimensions a)) 3)
:initial-contents
(let ((c (round (* 1024 (cos (angle-of self)))))
(s (round (* 1024 (sin (angle-of self))))))
(loop for i from 0 to (- (first (array-dimensions a)) 1)
collect (let ((x (aref a i 0))
(y (aref a i 1)))
(list (ash (- (* x c) (* y s)) -10)
(ash (+ (* x s) (* y c)) -10)
(aref a i 2)))))))
(defmethod apply-transform ((self 3d-shift) (a array))
"shift an array along all three axes specified~
by the transformation. Observations in the array correspons to rows~
in the order x,y,z. This returns a *new* array. Integer~
calculations are used, and an INTEGER ARRAY MUST BE GIVEN TO THIS ROUTINE!!!"
(make-array (list (first (array-dimensions a)) 3)
:initial-contents
(loop for i from 0 to (- (first (array-dimensions a)) 1)
collect (list (+ (aref a i 0) (x-shift-of self))
(+ (aref a i 1) (y-shift-of self))
(+ (aref a i 2) (z-shift-of self))))))
(defmethod apply-transform ((self 3d-scale) (a array))
"Scale an array along all three axes specified~
by the transformation. Observations in the array correspons to rows~
in the order x,y,z. This returns a *new* array. Integer~
calculations are used, and an INTEGER ARRAY MUST BE GIVEN TO THIS ROUTINE!!!"
(make-array (list (first (array-dimensions a)) 3)
:initial-contents
(loop for i from 0 to (- (first (array-dimensions a)) 1)
collect (list (round (* (aref a i 0) (x-scale-of self)))
(round (* (aref a i 1) (y-scale-of self)))
(round (* (aref a i 2) (z-scale-of self)))))))
;---------------------------------------------------------------------------
;
; the same routines as above, but ones that destructively change the contents
; of the arrays
;
;---------------------------------------------------------------------------
(defmethod apply-transform! ((self 2d-shift) (a array))
"apply a shift transform to a data array. Observations correspond to rows~
This routine destructively modifies the given array. Integer~
calculations are used, and an INTEGER ARRAY MUST BE GIVEN TO THIS ROUTINE!!!"
(loop with xs = (x-shift-of self)
with ys = (y-shift-of self)
for i from 0 to (- (first (array-dimensions a)) 1)
do (progn
(incf (aref a i 0) xs)
(incf (aref a i 1) ys))))
(defmethod apply-transform! ((self 3d-x-rotate) (a array))
"rotate an array about the x axis through a given angle, specified~
by the transformation. Observations in the array correspons to rows~
in the order x,y,z. This routine destructively modifies the given~
array. Integer calculations are used, and an INTEGER ARRAY MUST BE~
GIVEN TO THIS ROUTINE!!!"
(let ((c (round (* 1024 (cos (angle-of self)))))
(s (round (* 1024 (sin (angle-of self))))))
(loop for i from 0 to (- (first (array-dimensions a)) 1)
do (let ((y (aref a i 1))
(z (aref a i 2)))
(setf (aref a i 1) (ash (- (* y c) (* z s)) -10))
(setf (aref a i 2) (ash (+ (* y s) (* z c)) -10))))))
(defmethod apply-transform! ((self 3d-y-rotate) (a array))
"rotate an array about the y axis through a given angle, specified~
by the transformation. Observations in the array correspons to rows~
in the order x,y,z. This routine destructively modifies the given array.~
Integer calculations are used, and an INTEGER ARRAY MUST BE~
GIVEN TO THIS ROUTINE!!!"
(let ((c (round (* 1024 (cos (angle-of self)))))
(s (round (* 1024 (sin (angle-of self))))))
(loop for i from 0 to (- (first (array-dimensions a)) 1)
do (let ((x (aref a i 0))
(z (aref a i 2)))
(setf (aref a i 0) (ash (+ (* x c) (* z s)) -10))
(setf (aref a i 2) (ash (- (* z c) (* x s)) -10))))))
(defmethod apply-transform! ((self 3d-z-rotate) (a array))
"rotate an array about the z axis through a given angle, specified~
by the transformation. Observations in the array correspons to rows~
in the order x,y,z. This routine destructively modifies the given array.~
Integer calculations are used, and an INTEGER ARRAY MUST BE~
GIVEN TO THIS ROUTINE!!!"
(let ((c (round (* 1024 (cos (angle-of self)))))
(s (round (* 1024 (sin (angle-of self))))))
(loop for i from 0 to (- (first (array-dimensions a)) 1)
do (let ((x (aref a i 0))
(y (aref a i 1)))
(setf (aref a i 0) (ash (- (* x c) (* y s)) -10))
(setf (aref a i 1) (ash (+ (* x s) (* y c)) -10))))))
(defmethod apply-transform! ((self 3d-shift) (a array))
"shift an array along all three axes specified~
by the transformation. Observations in the array correspons to rows~
in the order x,y,z. This routine destructively modifies the given array.~
Integer calculations are used, and an INTEGER ARRAY MUST BE~
GIVEN TO THIS ROUTINE!!!"
(loop for i from 0 to (- (first (array-dimensions a)) 1)
do (progn
(incf (aref a i 0) (x-shift-of self))
(incf (aref a i 1) (y-shift-of self))
(incf (aref a i 2) (z-shift-of self)))))
(defmethod apply-transform! ((self 3d-scale) (a array))
"Scale an array along all three axes specified~
by the transformation. Observations in the array correspons to rows~
in the order x,y,z. This routine destructively modifies the given array.~
Integer calculations are used, and an INTEGER ARRAY MUST BE~
GIVEN TO THIS ROUTINE!!!"
(loop for i from 0 to (- (first (array-dimensions a)) 1)
do (progn
(setf (aref a i 0) (round (* (aref a i 0) (x-scale-of self))))
(setf (aref a i 1) (round (* (aref a i 1) (y-scale-of self))))
(setf (aref a i 2) (round (* (aref a i 2) (z-scale-of self)))))))
| 16,320 | Common Lisp | .l | 304 | 42.328947 | 195 | 0.537613 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | ee1a9a653c2e470000d32ecfdec532439d0045feee747a93b1b5512872d7e4b0 | 33,640 | [
-1
] |
33,641 | list-transforms.lsp | rwoldford_Quail/source/window-basics/transforms/list-transforms.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; list-transforms.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;;
;;; This file is an addition to Window-basics for moving pointclouds
;;;
;;;
;;; Authors:
;;; H.A. Chipman 1991
;;; C.B. Hurley 1991 George Washington University
;;;
;;;
;;;
;;;
;;;----------------------------------------------------------------------------------
(in-package :wb)
;;;----------------------------------------------------------------------------------
;;; A modified version of affinetrans.lisp. It includes more specific subclasses,
;;; such as:
;;;
;;; affine-transform---- 2d-affine----- 2d-shift
;;; \
;;; \_ 3d-affine----- 3d-rotate------ 3d-x-rotate
;;; | |
;;; |----- 3d-scale |- 3d-y-rotate
;;; | |
;;; |_____ 3d-shift |_ 3d-z-rotate
;;; |
;;; |_ 3d-axis-rotate
;;;
;;; The modifications include fixnum math, apply-transform methods for lists of lists,
;;; and the extended classes described above.
(in-package :wb)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(mapply-transform mapply-transform!)))
(defclass affine-transform ()
((dimension
:initarg :dimension
:accessor dimension-of
:documentation "The true dimension of the transform, (n * n)")
(affine
:initarg :affine
:accessor matrix-of
:documentation "an (n+1) *(n+1) array of reals, first n rows and colums represent the transformation, the last column represents the location shift")
)
(:documentation
"Affine transformations for viewing 2 and 3 dimensional objects. See Foley and Van Dam for reference. Note the transforms here operate on columns whereas those in F+VD operate on row vectors"
))
(defclass 2d-affine (affine-transform)
((affine
:documentation "a 3 by 3 array of reals, first 2 rows and colums represent the transformation, the last column represents the location shift")
(x-function
:accessor x-function
:documentation "function applied to object to retrieve its x location")
(y-function
:accessor y-function
:documentation "function applied to object to retrieve its y location")
(dimension
:initform 2
:documentation " the true dimension of the transform, 2 by 2")))
(defclass 3d-affine (affine-transform)
((affine
:documentation "a 4 by 4 array of reals, first 3 rows and colums represent the transformation, the last column represents the location shift")
(x-function
:accessor x-function
:documentation "function applied to object to retrieve its x location")
(y-function
:accessor y-function
:documentation "function applied to object to retrieve its y location")
(z-function
:accessor z-function
:documentation "function applied to object to retrieve its z location")
(dimension
:initform 3
:documentation " the true dimension of the transform, 3 by 3")))
(defclass 2d-shift (2d-affine)
((x-shift :initarg :x-shift
:accessor x-shift-of
:documentation "The translation applied to the x-axis")
(y-shift :initarg :y-shift
:accessor y-shift-of
:documentation "The translation applied to the y-axis")))
(defclass 3d-rotate (3d-affine)
((angle :initarg :angle
:accessor angle-of
:documentation "The angle of rotation")))
(defclass 3d-axis-rotate (3d-rotate)
((x-component :initarg :x-component
:accessor x-component-of
:documentation "The x-component of the arbitrary axis (length=1)")
(y-component :initarg :y-component
:accessor y-component-of
:documentation "The y-component of the arbitrary axis (length=1)")
(z-component :initarg :z-component
:accessor z-component-of
:documentation "The z-component of the arbitrary axis (length=1)")))
(defclass 3d-x-rotate (3d-axis-rotate) ())
(defclass 3d-y-rotate (3d-axis-rotate) ())
(defclass 3d-z-rotate (3d-axis-rotate) ())
(defclass 3d-shift (3d-affine)
((x-shift :initarg :x-shift
:accessor x-shift-of
:documentation "The translation applied to the x-axis")
(y-shift :initarg :y-shift
:accessor y-shift-of
:documentation "The translation applied to the y-axis")
(z-shift :initarg :z-shift
:accessor z-shift-of
:documentation "The translation applied to the z-axis")))
(defclass 3d-scale (3d-affine)
((x-scale :initarg :x-scale
:accessor x-scale-of
:documentation "The scaling applied to the x-axis")
(y-scale :initarg :x-scale
:accessor y-scale-of
:documentation "The scaling applied to the y-axis")
(z-scale :initarg :z-scale
:accessor z-scale-of
:documentation "The scaling applied to the z-axis")))
(defmethod mapply-transform ((self 2d-shift) (a list))
"Apply a shift transform to each sublist of the list. ~
A sublist has fixnums in the order x,y,z. ~
This routine returns a *new* list of fixnums. "
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (inline + list))
(loop with xs fixnum = (x-shift-of self)
with ys fixnum = (y-shift-of self)
for (x y) fixnum in a
collect (list (+ x xs) (+ y ys))))
;;; Note that apply-transform is not optimized for speed like the other apply-transforms
;;; that rotate three-d data.
(defmethod mapply-transform ((self 3d-axis-rotate) (a list))
"Rotate each sublist of the list about an arbitrary axis ~
through a given angle, specified by the transformation. ~
A sublist has fixnums in the order x,y,z. ~
This routine returns a *new* list of fixnums. "
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (inline + * - list round))
(let* ((c (cos (angle-of self)))
(s (sin (angle-of self)))
(u (- 1 c))
(xc (x-component-of self))
(yc (y-component-of self))
(zc (z-component-of self))
)
(loop for (x y z) fixnum in a
collect
(list (round (+ (* x (+ (* u xc xc) c))
(* y (- (* u xc yc) (* s zc)))
(* z (+ (* u xc zc) (* s yc)))))
(round (+ (* x (+ (* u xc yc) (* s zc)))
(* y (+ (* u yc yc) c))
(* z (- (* u yc zc) (* s xc)))))
(round (+ (* x (- (* u xc zc) (* s yc)))
(* y (+ (* u yc zc) (* s xc)))
(* z (+ (* u zc zc) c))))))))
#|
(defmethod mapply-transform ((self 3d-x-rotate) (a list))
"Rotate each sublist of the list about the x-axis ~
through a given angle, specified by the transformation. ~
A sublist has fixnums in the order x,y,z. ~
This routine returns a *new*list of fixnums. "
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (inline + - * ash list) (fixnum c s))
(let ((c (round (* 1024 (cos (angle-of self)))))
(s (round (* 1024 (sin (angle-of self))))))
(loop for (x y z) fixnum in a
collect (list x
(ash (- (* y c) (* z s)) -10)
(ash (+ (* y s) (* z c)) -10)))))
|#
(defmethod mapply-transform ((self 3d-x-rotate) (a list))
"Rotate each sublist of the list about the y-axis ~
through a given angle, specified by the transformation. ~
A sublist has fixnums in the order x,y,z. ~
This routine returns a *new* list of fixnums."
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (inline + - * ash list))
(let ((c (round (* 1024 (cos (angle-of self)))))
(s (round (* 1024 (sin (angle-of self))))))
(loop for (x y z) fixnum in a
collect (list (ash (- (* y c) (* z s)) -10)
y
(ash (+ (* y s) (* z c)) -10)))))
(defmethod mapply-transform ((self 3d-y-rotate) (a list))
"Rotate each sublist of the list about the y-axis ~
through a given angle, specified by the transformation. ~
A sublist has fixnums in the order x,y,z. ~
This routine returns a *new* list of fixnums."
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (inline + - * ash list))
(let ((c (round (* 1024 (cos (angle-of self)))))
(s (round (* 1024 (sin (angle-of self))))))
(loop for (x y z) fixnum in a
collect (list (ash (+ (* x c) (* z s)) -10)
y
(ash (- (* z c) (* x s)) -10)))))
(defmethod mapply-transform ((self 3d-z-rotate) (a list))
"Rotate each sublist of the list about the z-axis ~
through a given angle, specified by the transformation. ~
A sublist has fixnums in the order x,y,z. ~
This routine returns a *new* list of fixnums."
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (inline + - * ash list))
(let ((c (round (* 1024 (cos (angle-of self)))))
(s (round (* 1024 (sin (angle-of self))))))
(loop for (x y z) fixnum in a
collect (list (ash (- (* x c) (* y s)) -10)
(ash (+ (* x s) (* y c)) -10)
z))))
(defmethod mapply-transform ((self 3d-shift) (a list))
"Shift each sublist of the list along all three axes. ~
A sublist has fixnums in the order x,y,z. ~
This routine returns a *new* list of fixnums. "
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (inline + list))
(loop with xs fixnum = (x-shift-of self)
with ys fixnum = (y-shift-of self)
with zs fixnum = (z-shift-of self)
for (x y z) fixnum in a
collect (list (+ x xs) (+ y ys) (+ z zs))))
(defmethod mapply-transform ((self 3d-scale) (a list))
"Scale each sublist of the list along all three axes. ~
A sublist has fixnums in the order x,y,z. ~
This routine returns a *new* list of fixnums."
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (inline * list))
(loop with xs fixnum = (x-scale-of self)
with ys fixnum = (y-scale-of self)
with zs fixnum = (z-scale-of self)
for (x y z) fixnum in a
collect (list (* x xs) (* y ys) (* z zs))))
;---------------------------------------------------------------------------
;
; the same routines as above, but ones that destructively change the contents
; of the lists
;
;---------------------------------------------------------------------------
(defmethod mapply-transform! ((self 2d-shift) (a list))
"apply a shift transform to a list of lists. Observations correspond to lists~
fixnum calculations are used, and ~
an fixnum LIST MUST BE GIVEN TO THIS ROUTINE!!!"
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (inline first second))
;inline first second incf)) ;16 November 2019
(loop with xs fixnum = (x-shift-of self)
with ys fixnum = (y-shift-of self)
for ai in a do
(incf (first ai) xs)
(incf (second ai) ys)))
;;; Note that apply-transform is not optimized for speed like the other apply-transforms
;;; that rotate three-d data.
(defmethod mapply-transform! ((self 3d-axis-rotate) (a list))
"apply a shift transform to each sublist of the list ~
A sublist has fixnums in the order x,y,z.
This routine modifies the fixnum list "
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (inline first second third round + * -))
(let* ((c (cos (angle-of self)))
(s (sin (angle-of self)))
(u (- 1 c))
(xc (x-component-of self))
(yc (y-component-of self))
(zc (z-component-of self))
)
(loop for (x y z) fixnum in a
for ai in a do
(setf (first ai)
(round (+ (* x (+ (* u xc xc) c))
(* y (- (* u xc yc) (* s zc)))
(* z (+ (* u xc zc) (* s yc))))))
(setf (second ai)
(round (+ (* x (+ (* u xc yc) (* s zc)))
(* y (+ (* u yc yc) c))
(* z (- (* u yc zc) (* s xc))))))
(setf (third ai)
(round (+ (* x (- (* u xc zc) (* s yc)))
(* y (+ (* u yc zc) (* s xc)))
(* z (+ (* u zc zc) c))))))))
(defmethod mapply-transform! ((self 3d-x-rotate) (a list))
"Rotates each sublist of the list about the x-axis.~
A sublist has fixnums in the order x,y,z.
This routine modifies the fixnum list "
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (inline ash second third + * -))
(let ((c (round (* 1024 (cos (angle-of self)))))
(s (round (* 1024 (sin (angle-of self))))))
(loop for (x y z) fixnum in a
for ai in a do
(setf (second ai) (ash (- (* y c) (* z s)) -10))
(setf (third ai) (ash (+ (* y s) (* z c)) -10)))))
(defmethod mapply-transform! ((self 3d-y-rotate) (a list))
"Rotates each sublist of the list about the y-axis.~
A sublist has fixnums in the order x,y,z.
This routine modifies the fixnum list "
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (inline ash first third + * -))
(let ((c (round (* 1024 (cos (angle-of self)))))
(s (round (* 1024 (sin (angle-of self))))))
(loop for (x y z) fixnum in a
for ai in a do
(setf (first ai) (ash (+ (* x c) (* z s)) -10)
(third ai) (ash (- (* z c) (* x s)) -10)))))
(defmethod mapply-transform! ((self 3d-z-rotate) (a list))
"Rotates each sublist of the list about the z-axis.~
A sublist has fixnums in the order x,y,z.
This routine modifies the fixnum list "
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (inline ash second first + * -))
(let ((c (round (* 1024 (cos (angle-of self)))))
(s (round (* 1024 (sin (angle-of self))))))
(loop for (x y z) fixnum in a
for ai in a do
(setf (first ai) (ash (- (* x c) (* y s)) -10)
(second ai) (ash (+ (* x s) (* y c)) -10)))))
(defmethod mapply-transform! ((self 3d-shift) (a list))
"Shifts each sublist of the list along all axes.~
A sublist has fixnums in the order x,y,z.
This routine modifies the fixnum list "
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (inline first second third))
;(inline incf first second third)) ;16 November 2019
(loop with xs fixnum = (x-shift-of self)
with ys fixnum = (y-shift-of self)
with zs fixnum = (z-shift-of self)
for ai in a do
(incf (first ai) xs)
(incf (second ai) ys)
(incf (third ai) zs)))
(defmethod mapply-transform! ((self 3d-scale) (a list))
"Scales each sublist of the list along all axes.~
A sublist has fixnums in the order x,y,z.
This routine modifies the fixnum list "
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (inline * first second third))
(loop with xs fixnum = (x-scale-of self)
with ys fixnum = (y-scale-of self)
with zs fixnum = (z-scale-of self)
for (x y z) fixnum in a
for ai in a do
(setf (first ai) (* x xs)
(second ai) (* y ys)
(third ai) (* z zs))))
(defclass 3d-x-rotate&2d-shift (3d-x-rotate 2d-shift)
())
(defclass 3d-y-rotate&2d-shift (3d-y-rotate 2d-shift)
())
(defclass 3d-z-rotate&2d-shift (3d-z-rotate 2d-shift)
())
(defmethod mapply-transform-store ((self 3d-x-rotate&2d-shift) (a list) store)
"Rotates each sublist around x-axis, and shifts along x and y~
A sublist has fixnums in the order x,y,z.
This results are placed in store "
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (inline * + - first second third))
(let ((c (round (* 1024 (cos (angle-of self)))))
(s (round (* 1024 (sin (angle-of self))))))
(loop with xs fixnum = (x-shift-of self)
with ys fixnum = (y-shift-of self)
for (x y z) fixnum in a
for ai in store do
(setf (first ai) (+ xs x)
(second ai) (+ ys (ash (- (* y c) (* z s)) -10))
(third ai) (ash (+ (* y s) (* z c)) -10)))))
(defmethod mapply-transform-store ((self 3d-y-rotate&2d-shift) (a list) store)
"Rotates each sublist around y axis, and shifts along x and y~
A sublist has fixnums in the order x,y,z.
This results are placed in store "
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (inline * + - first second third ash))
(let ((c (round (* 1024 (cos (angle-of self)))))
(s (round (* 1024 (sin (angle-of self))))))
(loop with xs fixnum = (x-shift-of self)
with ys fixnum = (y-shift-of self)
for (x y z) fixnum in a
for ai in store do
(setf (first ai) (+ xs (ash (+ (* x c) (* z s)) -10))
(second ai) (+ y ys)
(third ai) (ash (- (* z c) (* x s)) -10)))))
(defmethod mapply-transform-store ((self 3d-z-rotate&2d-shift) (a list) store)
"Rotates each sublist around z-axis, and shifts along x and y~
A sublist has fixnums in the order x,y,z.
This results are placed in store "
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (inline * + - first second third ash))
(let ((c (round (* 1024 (cos (angle-of self)))))
(s (round (* 1024 (sin (angle-of self))))))
(loop with xs fixnum = (x-shift-of self)
with ys fixnum = (y-shift-of self)
for (x y z) fixnum in a
for ai in store do
(setf (first ai) (+ xs (ash (- (* x c) (* y s)) -10))
(second ai) (+ ys (ash (+ (* x s) (* y c)) -10))
(third ai) z))))
| 20,056 | Common Lisp | .l | 427 | 37.224824 | 195 | 0.53214 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 5f53c48646b18eeaafccfa4b97e6be33d0911d429ac0a07d1a45f23da7ef1e8c | 33,641 | [
-1
] |
33,643 | font-mixin-pc.lsp | rwoldford_Quail/source/window-basics/fonts/font-mixin-pc.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; font-mixin-pc.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;; This file is part of the Window-Basics package intended to provide a uniform
;;; window environment for Common Lisp programming.
;;;
;;; For copyright information and history, see window-basics-copyright.lisp
;;; Authors:
;;; R.W. Oldford 1992
;;; G.W. Bennett 1996
;;;----------------------------------------------------------------------------------
(in-package :wb)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(font-mixin canvas-font)))
(defclass font-mixin ()
((canvas-font :initarg :font :reader canvas-font
:documentation "The window-basics font used for drawing characters."))
(:documentation
"A mixin class that allows a window-basics font to be stored."))
(defmethod (setf canvas-font) (new-font (self font-mixin))
;(cg::set-font self (canvas-font-to-host-font new-font)) 18oct05
(setf (cg::font self) (canvas-font-to-host-font new-font)) ;18oct05
(setf (slot-value self 'canvas-font) new-font)
new-font)
#|
(defmethod initialize-instance :after ((self font-mixin)
&rest initargs
&key font)
(declare (ignore initargs))
(if (canvas-font-p self)
(setf (canvas-font self) font)
(setf (canvas-font self)
(host-font-to-canvas-font (cg::font self)))))
|#
| 1,723 | Common Lisp | .l | 36 | 41.805556 | 92 | 0.524776 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 1aac19efa42db3c030b32030a3317c0460184e0089b90c983fac85eaa5a0bf56 | 33,643 | [
-1
] |
33,646 | font.lsp | rwoldford_Quail/source/window-basics/fonts/font.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; font.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;;
;;; This file is part of the Window-Basics package intended to provide a uniform
;;; window environment for Common Lisp programming.
;;;
;;; For copyright information and history, see window-basics-copyright.lisp
;;;
;;; Authors:
;;; R.W. Oldford 1992
;;;
;;;
;;;
;;;----------------------------------------------------------------------------------
(in-package :wb)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(canvas-font-transfer-modes canvas-font-styles canvas-font-names
canvas-make-font copy-canvas-font canvas-font-p canvas-font-name
set-canvas-font-name canvas-font-style set-canvas-font-style
canvas-font-size set-canvas-font-size
canvas-font-transfer-mode set-canvas-font-transfer-mode
canvas-font-ascent canvas-font-descent canvas-font-leading
canvas-font-height with-canvas-font canvas-font-equal)))
(defun canvas-font-transfer-modes ()
"Returns a list of legal transfer modes for canvas fonts"
(h-draw:font-transfer-modes))
(defun canvas-font-styles ()
"Returns the list of currently available canvas font styles."
(h-draw:font-styles))
(defun canvas-font-names ()
"Returns a list of font names currently available."
(h-draw:font-names))
(defun canvas-make-font (&key
(name NIL)
(style :plain)
(size 10)
(transfer-mode NIL))
"Makes a font of with the given font characteristics."
(if (not (listp style))
(setf style (list style)))
(list 'canvas-font name style size transfer-mode))
(defun canvas-font-equal (font1 font2)
"Tests whether font1 and font2 represent the same canvas-font."
(flet ((sort-font-list (font)
(list
(canvas-font-name font)
(canvas-font-size font)
(canvas-font-transfer-mode font)
(sort (canvas-font-style font)
#'(lambda (x y)
(< (position x (canvas-font-styles))
(position y (canvas-font-styles))))))))
(equal (sort-font-list (copy-canvas-font font1))
(sort-font-list (copy-canvas-font font2)))))
(defun copy-canvas-font (canvas-font)
"Returns a new canvas-font that is a copy of the one given."
(copy-tree canvas-font))
(defun canvas-font-p (font)
"Returns t if font is a canvas font, NIL otherwise."
(and (listp font)
(eq (first font) 'canvas-font)))
(defun canvas-font-name (canvas-font)
"Returns the name of this canvas font."
(second canvas-font))
(defun set-canvas-font-name (canvas-font name)
"Sets the name of this canvas font."
(if (member name (canvas-font-names)
:test
#'(lambda (a b)
(cond
((and (stringp a) (stringp b))
(string-equal a b))
(T (equal a b)))))
(setf (second canvas-font) name)
(error "Illegal canvas font name ~s" name))
(h-draw:clear-host-font-cache canvas-font)
name)
(defun canvas-font-style (canvas-font)
"Returns the style list of this canvas font."
(third canvas-font))
(defun set-canvas-font-style (canvas-font style)
"Sets the style list of this canvas font."
(cond
((null style)
(error "Illegal canvas font style ~s" style))
((listp style)
(loop for s in style
do
(set-canvas-font-style canvas-font s)))
((member style (canvas-font-style canvas-font)) style)
((member style (canvas-font-styles))
(cond
((eql :plain style) (setf (third canvas-font) (list style)))
(T (setf (third canvas-font)
(append (list style)
(remove :plain (third canvas-font)))))))
(T (error "Illegal canvas font style ~s" style))
)
(h-draw:clear-host-font-cache canvas-font)
style)
(defun canvas-font-size (canvas-font)
"Returns the size of this canvas font."
(fourth canvas-font))
(defun set-canvas-font-size (canvas-font size)
"Sets the size of this canvas font."
(if (and (integerp size)
(<= 1 size)
(<= size 127))
(setf (fourth canvas-font) size)
(error "Illegal canvas font size ~s" size))
(h-draw:clear-host-font-cache canvas-font)
size)
(defun canvas-font-transfer-mode (canvas-font)
"Returns the transfer-mode of this canvas font."
(fifth canvas-font))
(defun set-canvas-font-transfer-mode (canvas-font transfer-mode)
"Sets the transfer-mode of this canvas font."
(if (member transfer-mode (canvas-font-transfer-modes))
(setf (fifth canvas-font) transfer-mode)
(error "Illegal canvas font transfer-mode ~s" transfer-mode))
(h-draw:clear-host-font-cache canvas-font)
transfer-mode)
(defmacro with-canvas-font (canvas font &body forms)
"Performs the forms with the font of canvas temporarily reset to ~
the value given. A NIL font is ignored."
(let ((old-font (gensym "with-canvas-font")))
`(let (,old-font)
(cond
((and ,font (not (canvas-font-equal ,font (canvas-font ,canvas))))
(setf ,old-font (canvas-font ,canvas))
(setf (canvas-font ,canvas) ,font)
,@forms
(setf (canvas-font ,canvas) ,old-font))
(T ,@forms)))))
(defun canvas-font-description (canvas-font)
"Returns four values that represent (in pixels) the ascent, ~
descent, max-width, and leading (suggested spacing between ~
lines) of the canvas-font."
(h-draw:host-font-description
(if (canvas-font-p canvas-font)
(canvas-font-to-host-font canvas-font)
canvas-font)))
(defun canvas-font-ascent (canvas-or-font &key font)
"Returns the ascent of the font supplied or the ascent ~
of the font associated with the canvas if a canvas is given ~
instead."
(setf font
(or (if (canvas-font-p canvas-or-font)
canvas-or-font
NIL)
font
(if (canvas-p canvas-or-font)
(canvas-font canvas-or-font)
NIL)))
(canvas-font-description font))
(defun canvas-font-descent (canvas-or-font &key font)
"Returns the descent of the font supplied or the descent ~
of the font associated with the canvas if a canvas is given ~
instead."
(setf font
(or (if (canvas-font-p canvas-or-font)
canvas-or-font
NIL)
font
(if (canvas-p canvas-or-font)
(canvas-font canvas-or-font)
NIL)))
(second (multiple-value-list (canvas-font-description font))))
(defun canvas-font-leading (canvas-or-font &key font)
"Returns the leading of the font supplied or the leading ~
of the font associated with the canvas if a canvas is given ~
instead."
(setf font
(or (if (canvas-font-p canvas-or-font)
canvas-or-font
NIL)
font
(if (canvas-p canvas-or-font)
(canvas-font canvas-or-font)
NIL)))
(fourth (multiple-value-list (canvas-font-description font))))
(defun canvas-font-height (canvas-or-font &key font)
"Returns the height of the font supplied or the height ~
of the font associated with the canvas if a canvas is given ~
instead."
(setf font
(or (if (canvas-font-p canvas-or-font)
canvas-or-font
NIL)
font
(if (canvas-p canvas-or-font)
(canvas-font canvas-or-font)
NIL)))
(multiple-value-bind (ascent descent widmax leading)
(canvas-font-description font)
(declare (ignore widmax))
(+ ascent descent leading)))
(defun canvas-font-to-host-font (canvas-font)
"Translates the canvas font representation to the representation ~
of fonts in the host Common Lisp. ~
(:see-also host-font-to-canvas-font canvas-make-font)"
(h-draw:cached-host-font canvas-font))
(defun host-font-to-canvas-font (host-font)
"Translates the host Common Lisp font representation to the representation ~
of a canvas font in window-basics. ~
(:see-also canvas-font-to-host-font canvas-make-font)"
(let
((name (h-draw:get-canvas-font-name host-font))
(size (h-draw:get-canvas-font-size host-font))
(style (h-draw:get-canvas-font-style host-font))
(mode (h-draw:get-canvas-font-transfer-mode host-font)))
(canvas-make-font
:name name
:size size
:style style
:transfer-mode mode)
)
)
| 9,039 | Common Lisp | .l | 224 | 32.5 | 130 | 0.603797 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 00fafcc36bc6889d7417864b0bdd319a66c4bef861b18e4f712a0f1dc64671a3 | 33,646 | [
-1
] |
33,647 | default-fonts-pc.lsp | rwoldford_Quail/source/window-basics/fonts/default-fonts-pc.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; default-fonts-pc.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;; This file is part of the Window-Basics package intended to provide a uniform
;;; window environment for Common Lisp programming.
;;;
;;; For copyright information and history, see window-basics-copyright.lisp
;;; Authors:
;;; N.G. Bennett 1993
;;; R.W. Oldford 1992
;;; G.W. Bennett 1996
;;;
;;;----------------------------------------------------------------------------------
(in-package :wb)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(*very-small-graphics-font* *small-graphics-font*
*normal-graphics-font* *large-graphics-font*
*help-normal-text-font* *help-small-text-font*
*help-key-font* *help-little-key-font*
*help-lisp-font* *help-normal-title-font* *help-small-title-font*
*help-lisp-title-font* *prompt-normal-font*)))
;;; Most of the :name values should be faces, I think
;;; Thus times <-> times\ new\ roman
;;; courier <-> courier but helvetica <-?-> ms\ sans\ serif
;;; swiss is the name of a FAMILY
;;; See p7-8 of Volume 2 of ACLPC2.0
;;; for small things we could use small\ fonts
;;; and the sizes should be the ;;nn values
;;; For now only the sizes have been done
(defparameter *very-small-graphics-font*
(canvas-make-font :name (cons :modern :times\ new\ roman)
:size 7 :style nil) ;;11)
"Canvas font used for very small graphics characters.")
(defparameter *small-graphics-font*
(canvas-make-font :name (cons :modern :times\ new\ roman)
:size 9 :style nil) ;;14)
"Canvas font used for small graphics characters.")
(defparameter *normal-graphics-font*
(canvas-make-font :name (cons :modern :times\ new\ roman)
:size 12 :style nil) ;;17)
"Canvas font used for normal graphics characters.")
(defparameter *large-graphics-font*
(canvas-make-font :name (cons :modern :times\ new\ roman)
:size 20 ;;20
:style :bold)
"Canvas font used for large graphics characters.")
(defparameter *help-normal-text-font*
(canvas-make-font :name (cons :swiss :courier)
:size 10 :style nil) ;;14)
"Canvas font used for normal text in help.")
(defparameter *help-small-text-font*
(canvas-make-font :name (cons :swiss :courier)
:size 9 :style nil);;11)
"Canvas font used for small text in help.")
(defparameter *help-key-font*
(canvas-make-font :name (cons :swiss :courier)
:size 9 ;;14
:style :bold)
"Canvas font used for keys in help.")
(defparameter *help-little-key-font*
(canvas-make-font :name (cons :swiss :courier)
:size 7 ;;11
:style :bold)
"Small canvas font used for keys in help.")
(defparameter *help-lisp-font*
(canvas-make-font :name (cons :swiss :courier)
:size 12) ;;14)
"Canvas font used for displaying lisp code in help.")
(defparameter *help-normal-title-font*
(canvas-make-font :name (cons :swiss :courier)
:size 12) ;;14)
"Canvas font used for normal text in help title.")
(defparameter *help-small-title-font*
(canvas-make-font :name (cons :swiss :courier)
:size 9) ;;11)
"Canvas font used for small text in help title.")
(defparameter *help-lisp-title-font*
(canvas-make-font :name (cons :swiss :courier)
:size 12 ;;14
:style :bold)
"Canvas font used for displaying lisp code in help title.")
;;; NOTE this is 'defined' as *title-normal-font* in wb/host-host-menu-canvas-pc.lsp
;;; to avoid compiler complaints [not exported]. If the definition below is changed
;;; consider whether *title-normal-fonts* needs adjustment too.
;;; gwb 28sep2023
(defparameter *prompt-normal-font* ;(defparameter *prompt-normal-font*
(canvas-make-font :name (cons :roman :times\ new\ roman)
:size 12
:style nil)
;(cg::make-font :roman "times new roman" 20)
;(canvas-make-font :name (cons :roman :times\ new\ roman)
; :size 12 :style NIL)
"Canvas font used for prompts")
| 4,357 | Common Lisp | .l | 95 | 40.747368 | 115 | 0.617967 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 692d24fccb42f7136e8cee540e6e03c1ba995658439a30c3f9d76959954dbcee | 33,647 | [
-1
] |
33,648 | font-mixin-sblx.lsp | rwoldford_Quail/source/window-basics/fonts/font-mixin-sblx.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; font-mixin-pc.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;; This file is part of the Window-Basics package intended to provide a uniform
;;; window environment for Common Lisp programming.
;;;
;;; For copyright information and history, see window-basics-copyright.lisp
;;; Authors:
;;; R.W. Oldford 1992
;;; G.W. Bennett 1996
;;;----------------------------------------------------------------------------------
(in-package :wb)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(font-mixin canvas-font))) ;15MAR2021
(defclass font-mixin ()
((canvas-font :initarg :font :reader canvas-font
:documentation "The window-basics font used for drawing characters."))
(:documentation
"A mixin class that allows a window-basics font to be stored."))
#| not needed because fonts are not associated with canvases
(defmethod (setf canvas-font) (new-font (self font-mixin))
;(cg::set-font self (canvas-font-to-host-font new-font)) 18oct05
(setf (cg::font self) (canvas-font-to-host-font new-font)) ;18oct05
(setf (slot-value self 'canvas-font) new-font)
new-font)
|#
(defmethod (setf canvas-font) (new-font (self font-mixin))
(let ((mp (clim:get-frame-pane self 'host-pane)))
(setf (clim:medium-text-style mp)
(canvas-font-to-host-font new-font))
(setq new-font (host-font-to-canvas-font (clim:medium-text-style mp)))
(setf (slot-value self 'canvas-font) new-font)
new-font))
;;; I don't yet know what has to happen here 16MAR2021
;(defmethod (setf canvas-font) (new-font (self scrolling-window))
; (ccl::set-view-font (the-scroller self)
; (canvas-font-to-host-font new-font))
; (call-next-method))
#|
(defmethod initialize-instance :after ((self font-mixin)
&rest initargs
&key font)
(declare (ignore initargs))
(if (canvas-font-p self)
(setf (canvas-font self) font)
(setf (canvas-font self)
(host-font-to-canvas-font (cg::font self)))))
|#
| 2,329 | Common Lisp | .l | 50 | 42.48 | 102 | 0.57941 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | fc229cf8f83f6e1d815dec35b60c23538d2d8e8c97b3f58903749d86c703ee7e | 33,648 | [
-1
] |
33,650 | default-fonts-sblx.lsp | rwoldford_Quail/source/window-basics/fonts/default-fonts-sblx.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; default-fonts-sblx.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;; This file is part of the Window-Basics package intended to provide a uniform
;;; window environment for Common Lisp programming.
;;;
;;; For copyright information and history, see window-basics-copyright.lisp
;;; Authors:
;;; N.G. Bennett 1993
;;; R.W. Oldford 1992
;;; G.W. Bennett 1996
;;;
;;;----------------------------------------------------------------------------------
(in-package :wb)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(*very-small-graphics-font* *small-graphics-font*
*normal-graphics-font* *large-graphics-font*
*help-normal-text-font* *help-small-text-font*
*help-key-font* *help-little-key-font*
*help-lisp-font* *help-normal-title-font* *help-small-title-font*
*help-lisp-title-font*)))
;;; Most of the :name values should be faces, I think
;;; Thus times <-> times\ new\ roman
;;; courier <-> courier but helvetica <-?-> ms\ sans\ serif
;;; swiss is the name of a FAMILY
;;; See p7-8 of Volume 2 of ACLPC2.0
;;; for small things we could use small\ fonts
;;; and the sizes should be the ;;nn values
;;; For now only the sizes have been done
(defparameter *very-small-graphics-font*
(canvas-make-font :name :sans-serif;(cons :modern :times\ new\ roman)
:size :very-small :style :roman) ;;11)
"Canvas font used for very small graphics characters.")
(defparameter *small-graphics-font*
(canvas-make-font :name :sans-serif;(cons :modern :times\ new\ roman)
:size :small :style :roman) ;;14)
"Canvas font used for small graphics characters.")
(defparameter *normal-graphics-font*
(canvas-make-font :name :sans-serif;(cons :modern :times\ new\ roman)
:size :normal :style :roman) ;;17)
"Canvas font used for normal graphics characters.")
(defparameter *large-graphics-font*
(canvas-make-font :name :sans-serif;(cons :modern :times\ new\ roman)
:size :large :style :roman)
"Canvas font used for large graphics characters.")
(defparameter *help-normal-text-font*
(canvas-make-font :name nil;(cons :modern :times\ new\ roman)
:size :normal :style :roman);;14)
"Canvas font used for normal text in help.")
(defparameter *help-small-text-font*
(canvas-make-font :name nil;(cons :modern :times\ new\ roman)
:size :small :style :roman);;11)
"Canvas font used for small text in help.")
(defparameter *help-key-font*
(canvas-make-font :name nil;(cons :modern :times\ new\ roman)
:size :normal :style :bold)
"Canvas font used for keys in help.")
(defparameter *help-little-key-font*
(canvas-make-font :name nil;(cons :modern :times\ new\ roman)
:size :small :style :bold)
"Small canvas font used for keys in help.")
(defparameter *help-lisp-font*
(canvas-make-font :name :serif;(cons :modern :times\ new\ roman)
:size :normal :style :fix) ;;14)
"Canvas font used for displaying lisp code in help.")
(defparameter *help-normal-title-font*
(canvas-make-font :name nil;(cons :modern :times\ new\ roman)
:size :normal :style :roman) ;;14)
"Canvas font used for normal text in help title.")
(defparameter *help-small-title-font*
(canvas-make-font :name nil;(cons :modern :times\ new\ roman)
:size :small :style :roman) ;;11)
"Canvas font used for small text in help title.")
(defparameter *help-lisp-title-font*
(canvas-make-font :name :fix;(cons :modern :times\ new\ roman)
:size :normal :style :roman)
"Canvas font used for displaying lisp code in help title.")
#|
(defparameter *prompt-normal-font*
(canvas-make-font :name nil;(cons :modern :times\ new\ roman)
:size :normal :style :roman)
"Canvas font used for prompts")
|# | 4,036 | Common Lisp | .l | 85 | 44 | 114 | 0.638465 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | cb3756ecc490d6b271032d30004df1b4067e5a2cbfddab89011389ebc967dd0f | 33,650 | [
-1
] |
33,652 | host-draw-pc.lsp | rwoldford_Quail/source/window-basics/host/host-draw-pc.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; host-draw-pc.lsp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) 1991 Statistical Computing Laboratory, University of Waterloo
;;; Authors:
;;; R.W. Oldford 1991.
;;; G.W. Bennett 1995.
;;;--------------------------------------------------------------------------------
;;; This contains checked pieces of host-draw and accumulates routines as they are done
(in-package "HOST-DRAW")
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(make-point)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(point-x point-y *hardcopy-ptr* pen-show pen-hide pen-shown-p
pen-position pen-size set-pen-size pen-mode set-pen-mode pen-pattern
set-pen-pattern set-pen-color move-to move line-to line draw-line
draw-rectangle draw-filled-rectangle draw-inside-rectangle
erase-rect invert-rectangle draw-ellipse draw-filled-ellipse draw-arc
fill-arc erase-arc invert-arc fill-arc draw-polygon
make-bitmap copy-bits
draw-filled-polygon make-bitmap copy-bits origin set-origin
draw-string draw-char)
))
(defun make-point (x &optional y)
"Returns a point having x and y as its coordinates."
(if y
(cg::make-position x y)
(if (cg::positionp x)
x
(error "X (~s) is not a position or y missing" x)
)))
(defun point-x (point)
"Returns the x-coordinate of point."
(cg::position-x point))
(defun point-y (point)
"Returns the y-coordinate of point."
(cg::position-y point))
(defvar *hardcopy-ptr*
NIL
"A system dependent pointer to an open printer device.")
(defun pen-show (canvas)
(declare (ignore canvas))
nil)
(defun pen-hide (canvas)
(declare (ignore canvas))
nil)
(defun pen-shown-p (canvas)
(declare (ignore canvas))
nil)
(defun pen-position (canvas)
(let ((mp (cg::frame-child canvas)))
(cg::current-position mp)))
(defun pen-size (canvas)
(let ((mp (cg::frame-child canvas)))
(cg::line-width mp)))
#| ;;original version 18oct05
(defun set-pen-size (canvas h &optional v)
(declare (inline point-x point-y))
(let ((mp (cg::frame-child canvas)))
(if v
(cg::set-line-width mp (floor (+ h v) 2))
(cg::set-line-width mp (floor (+ (point-x h)
(point-y h))
2)))))
|#
;; start new version 18oct05
(defun set-pen-size (canvas h &optional v)
(declare (inline point-x poin-y))
(let ((mp (cg::frame-child canvas)))
(if v
(setf (cg::line-width mp) (floor (+h v) 2))
(setf (cg::line-width mp) (floor (+ (point-x h)
(point-y h))
2)))))
;; end new version 18oct05
(defun pen-mode (canvas)
(let ((mp (cg::frame-child canvas)))
(cg::paint-operation mp)))
(defun set-pen-mode (canvas new-mode)
(let ((mp (cg::frame-child canvas)))
;(cg::set-paint-operation mp new-mode) 18oct05
(setf (cg::paint-operation mp) new-mode) ;18oct05
))
(defun set-pen-pattern (canvas new-pattern)
(let ((mp (cg::frame-child canvas)))
;(cg::set-line-texture mp new-pattern) 18oct05
(setf (cg::line-texture mp) new-pattern) ;18oct05
))
#| old version 18oct05
(defun set-pen-color (canvas new-color)
(let ((mp (cg::frame-child canvas)))
(cg::set-foreground-color mp new-color)))
|#
;;; start new version 18oct05
(defun set-pen-color (canvas new-color)
(let ((mp (cg::frame-child canvas)))
(setf (cg::foreground-color mp) new-color)))
;;; end new version 18oct05
(defun move-to (canvas h &optional v)
(let ((mp (cg::frame-child canvas)))
(if v
(cg::move-to-x-y mp h v)
(cg::move-to mp h))))
(defun move (canvas h &optional v)
(let ((mp (cg::frame-child canvas)))
(if v
(cg::move-by-x-y mp h v)
(cg::move-by mp h))))
(defun line-to (canvas h &optional v)
(let ((mp (cg::frame-child canvas)))
(cg::draw-to mp (make-point h v))))
(defun line (canvas h &optional v)
(let ((mp (cg::frame-child canvas)))
(cg::draw-by mp (make-point h v))))
#|original version
(defun draw-line (canvas x1 y1 x2 y2)
(move-to canvas x1 y1)
(line-to canvas x2 y2))
|#
;; Add a point if we are drawing horizontally or vertically
;; to fix the cross symbol in static form (vs dynamic form).
(defun draw-line (canvas x1 y1 x2 y2)
(let ((mp (cg::frame-child canvas)))
(move-to canvas x1 y1)
(line-to canvas x2 y2)
(cond ((= x1 x2)
(cg::draw-to mp (cg::make-position x2 (+ 1 y2))))
((= y1 y2)
(cg::draw-to mp (cg::make-position (+ 1 x2) y2)))
)
(cg::move-to mp (cg::make-position x2 y2) ;; to expected end for next draw
)))
(defun draw-rectangle (canvas left top right bot) ;;x1 x2 y1 y2)
(let ((mp (cg::frame-child canvas)))
(cg::draw-box mp (cg::make-box left top right bot))) ;; x1 y1 x2 y2)))
)
;; Version compatible with fast-macros using centre and radius
;; in drawing boxes - 15 Feb 98
;; and compatible with V/V-M/draw-macros.lsp/with-point-symbol-bounds
;; 17 Feb 98. and fixed overall Feb 25 1998
(defun draw-inside-rectangle (canvas left &optional top right bot)
"Draws a specified box no longer worrying about ~
Inside but compatible with fast-macros."
(let ((mp (cg::frame-child canvas)))
(cond ((numberp left)
(let* ((mx (truncate (+ left right) 2))
(my (truncate (+ top bot ) 2))
(sh (truncate (- right left) 2))
(sv (truncate (- bot top) 2))
(lhs (- mx sh))
(rhs (+ lhs (- right left)))
(ths (if (oddp (- bot top)) (- my sv -1) (- my sv))) ;<**
(bhs (+ ths (- bot top))))
(if (= 1 (- rhs lhs)) ;;02nov99
(setf (cg::pixel-x-y mp lhs ths) cg::black) ;;02nov99
(cg::draw-box mp (cg::make-box lhs ths rhs bhs)))
))
((cg::boxp left)
;;; left is then a box which must be picked apart
(let* ((lx (cg::box-left left)) (rx (cg::box-right left))
(ty (cg::box-top left)) (by (cg::box-bottom left))
(mx (truncate (+ lx rx) 2))
(my (truncate (+ ty by ) 2))
(sh (truncate (- rx lx) 2))
(sv (truncate (- by ty) 2))
(lhs (- mx sh))
(rhs (+ lhs (- rx lx)))
(ths (if (oddp (- by ty)) (- my sv -1) (- my sv)))
(bhs (+ ths (- by ty))))
(if (= 1 (- rhs lhs)) ;;02nov99
(setf (cg::pixel-x-y mp lhs ths) cg::black) ;;02nov99
(cg::draw-box mp (cg::make-box lhs ths rhs bhs)))
))
((cg::positionp top)
;;; top is a position and thus so is left. left is top-left top is bottom-right
(let* ((lx (cg::position-x left)) (rx (cg::position-x top))
(ty (cg::position-y left)) (by (cg::position-y top))
(mx (truncate (+ lx rx) 2))
(my (truncate (+ ty by ) 2))
(sh (truncate (- rx lx) 2))
(sv (truncate (- by ty) 2))
(lhs (- mx sh))
(rhs (+ lhs (- rx lx)))
(ths (if (oddp (- by ty)) (- my sv -1) (- my sv)))
(bhs (+ ths (- by ty))))
(if (= 1 (- rhs lhs)) ;;02nov99
(setf (cg::pixel-x-y mp lhs ths) cg::black) ;;02nov99
(cg::draw-box mp (cg::make-box lhs ths rhs bhs)))
))
((cg::positionp right)
;;; left *is* left, top *is* top, right *is* position(bottom-right)
(let* ((lx left) (rx (cg::position-x right)) (ty top)
(by (cg::position-y right))
(mx (truncate (+ lx rx) 2))
(my (truncate (+ ty by ) 2))
(sh (truncate (- rx lx) 2))
(sv (truncate (- by ty) 2))
(lhs (- mx sh))
(rhs (+ lhs (- rx lx)))
(ths (if (oddp (- by ty)) (- my sv -1) (- my sv)))
(bhs (+ ths (- by ty))))
(if (= 1 (- rhs lhs)) ;;02nov99
(setf (cg::pixel-x-y mp lhs ths) cg::black) ;;02nov99
(cg::draw-box mp (cg::make-box lhs ths rhs bhs)))
))
#|
(t
;;; all four arguments are what they say they are
(let* ((mx (truncate (+ left right) 2))
(my (truncate (+ top bot ) 2))
(sh (truncate (- right left) 2))
(sv (truncate (- bot top) 2))
(lhs (- mx sh))
(rhs (+ lhs (- right left)))
(ths (if (oddp (- bot top)) (- my sv -1) (- my sv))) ;<**
(bhs (+ ths (- bot top))))
(if (= 1 (- rhs lhs)) ;;02nov99
(setf (cg::pixel-x-y mp lhs ths) cg::black) ;;02nov99
(cg::draw-box mp (cg::make-box lhs ths rhs bhs)))
))|#
)))
(defun draw-filled-rectangle (canvas left &optional top right bot)
"Greg's try at draw-filled-rectangle"
;;; fill-box demands a box as well as a stream
;;; So I have to invert the order of tests as I've done elsewhere
;;; in draw-ellipse
(let ((mp (cg::frame-child canvas)))
(if bot (if (oddp (- bot top))
(cg::fill-box mp (cg::make-box left (+ 1 top) right (+ 1 bot)))
(cg::fill-box mp (cg::make-box left top right bot)))
(if right (cg::fill-box mp (cg::make-box-from-corners (cg::make-position left top) right))
(if top (cg::fill-box mp (cg::make-box-from-corners left top))
(cg::fill-box mp left))))))
;;; New version to make compatible with draw-inside-rectangle
;;; Feb 25 1998
(defun erase-rect (canvas left &optional top right bot)
"Erases a box 1 pixel inside specified box"
(cond ((cg::boxp left)
;;; left is then a box which must be picked apart;
(let* ((lx (cg::box-left left)) (rx (cg::box-right left))
(ty (cg::box-top left)) (by (cg::box-bottom left))
(mx (truncate (+ lx rx) 2))
(my (truncate (+ ty by ) 2))
(sh (truncate (- rx lx) 2))
(sv (truncate (- by ty) 2))
(lhs (- mx sh))
(rhs (+ lhs (- rx lx)))
(ths (if (oddp (- by ty)) (- my sv -1) (- my sv)))
(bhs (+ ths (- by ty)))
(the-box (cg::make-box lhs ths rhs bhs)))
(let ((mp (cg::frame-child canvas)))
(cg::erase-box mp the-box)
(cg::erase-contents-box mp the-box))
))
((cg::positionp top)
;;; top is a position and thus so is left. left is top-left top is bottom-right
(let* ((lx (cg::position-x left)) (rx (cg::position-x top))
(ty (cg::position-y left)) (by (cg::position-y top))
(mx (truncate (+ lx rx) 2))
(my (truncate (+ ty by ) 2))
(sh (truncate (- rx lx) 2))
(sv (truncate (- by ty) 2))
(lhs (- mx sh))
(rhs (+ lhs (- rx lx)))
(ths (if (oddp (- by ty)) (- my sv -1) (- my sv)))
(bhs (+ ths (- by ty)))
(the-box (cg::make-box lhs ths rhs bhs)))
(let ((mp (cg::frame-child canvas)))
(cg::erase-box mp the-box)
(cg::erase-contents-box mp the-box)))
)
((cg::positionp right)
;;; left *is* left, top *is* top, right *is* position(bottom-right)
(let* ((lx left) (rx (cg::position-x right)) (ty top)
(by (cg::position-y right))
(mx (truncate (+ lx rx) 2))
(my (truncate (+ ty by ) 2))
(sh (truncate (- rx lx) 2))
(sv (truncate (- by ty) 2))
(lhs (- mx sh))
(rhs (+ lhs (- rx lx)))
(ths (if (oddp (- by ty)) (- my sv -1) (- my sv)))
(bhs (+ ths (- by ty)))
(the-box (cg::make-box lhs ths rhs bhs)))
(let ((mp (cg::frame-child canvas)))
(cg::erase-box mp the-box)
(cg::erase-contents-box mp the-box)))
)
(t
;;; all four arguments are what they say they are
(let* ((mx (truncate (+ left right) 2))
(my (truncate (+ top bot ) 2))
(sh (truncate (- right left) 2))
(sv (truncate (- bot top) 2))
(lhs (- mx sh))
(rhs (+ lhs (- right left)))
(ths (if (oddp (- bot top)) (- my sv -1) (- my sv))) ;<**
(bhs (+ ths (- bot top)))
(the-box (cg::make-box lhs ths rhs bhs)))
(let ((mp (cg::frame-child canvas)))
(cg::erase-box mp the-box)
(cg::erase-contents-box mp the-box)))
)
))
;;; New version ends
(defun comp-color (canvas)
"Takes the complement of the current rgb-color triple of stream - returns this new triple"
(let* ((mp (cg::frame-child canvas))
(current (cg::foreground-color mp))
( new_red (logxor 255 (cg::rgb-red current)))
( new_green (logxor 255 (cg::rgb-green current)))
( new_blue (logxor 255 (cg::rgb-blue current)))
(newfgcol (cg::make-rgb :red new_red :green new_green
:blue new_blue)))
newfgcol))
(defun invert-rectangle (canvas left &optional top right bot)
"A new version using a supplied CG macro"
(let ((mp (cg::frame-child canvas)))
(cg::with-paint-operation
;(mp cg::invert) 19oct05
(mp cg::po-invert) ;19oct05
;; (cg::with-foreground-color (canvas (comp-color canvas))
(if bot (cg::fill-box mp
(cg::make-box left top right bot))
(if right
(cg::fill-box mp
(cg::make-box-from-corners
(cg::make-position left top) (cg::make-position
(cg::position-y right)
(cg::position-x right)
)))
(if top
(cg::fill-box mp
(cg::make-box-from-corners
(cg:make-position (cg::position-y left)
(cg::position-x left)) (cg::make-position
(cg::position-y top)
(cg::position-x top))))
(cg::fill-box mp (cg::make-box (cg::box-left left) ;; wrapped args with cg::make-box 25JUL2023
(cg::box-top left) (cg::box-right left)
(cg::box-bottom left))
))
)
)
)
))
(defun draw-ellipse (canvas left &optional top right bot)
;;; aclpc uses quite a different set of parameters for ellipses
;;; centre, semi-major and minor axes, semi-major-axis-angle
(cond ((cg::boxp left)
;;; left is then a box which must be picked apart
(let* ((lx (cg::box-left left)) (rx (cg::box-right left))
(ty (cg::box-top left)) (by (cg::box-bottom left))
(centre (cg::make-position (/ (+ lx rx) 2) (/ (+ ty by) 2)))
; (majorhalf (- rx lx)) (minorhalf (- by ty)))
(majorhalf (/ (- rx lx) 2)) (minorhalf (/ (- by ty) 2)) ;; took out halves 10Nov99
(mp (cg::frame-child canvas))
)
(cg::draw-ellipse mp centre majorhalf minorhalf 0))
)
((cg::positionp top)
;;; top is a position and thus so is left
;;; left is top-left while top is bottom-right
(let* ((lx (cg::position-x left)) (rx (cg::position-x top))
(ty (cg::position-y left)) (by (cg::position-y top))
(centre (cg::make-position (/ (+ lx rx) 2) (/ (+ ty by) 2)))
;(majorhalf (- rx lx)) (minorhalf (- by ty)))
(majorhalf (/ (- rx lx) 2)) (minorhalf (/ (- by ty) 2)) ;; took out halves 10Nov99
(mp (cg::frame-child canvas))
)
(cg::draw-ellipse mp centre majorhalf minorhalf 0))
)
((cg::positionp right)
;;; left *is* left, top *is* top, right is pos(bottom-right)
(let* ((lx left) (rx (cg::position-x right)) (ty top)
(by (cg::position-y right))
(centre (cg::make-position (/ (+ lx rx) 2) (/ (+ ty by) 2)))
; (majorhalf (- rx lx)) (minorhalf (- by ty)))
(majorhalf (/ (- rx lx) 2)) (minorhalf (/ (- by ty) 2)) ;; took out halves 10Nov99
(mp (cg::frame-child canvas))
)
(cg::draw-ellipse mp centre majorhalf minorhalf 0))
)
(t
;;; all four arguments are what they say they are
;;; Check for single point 05jan00
(cond ((or (eq 1 (- right left)) (eq right left))
(setf (cg:pixel-x-y canvas left top)
(cg:foreground-color canvas)))
(t
(let* ((lx left) (rx right) (ty top) (by bot)
(centre (cg::make-position (/ (+ lx rx) 2) (/ (+ ty by) 2)))
; (majorhalf (- rx lx)) (minorhalf (- by ty)))
(majorhalf (/ (- rx lx) 2)) (minorhalf (/ (- by ty) 2))
;; took out halves 10Nov99
(mp (cg::frame-child canvas))
)
(cg::draw-ellipse mp centre majorhalf minorhalf 0))
)
))
))
;;; Changed 10Nov99 to add the circumference to the interior.
(defun draw-filled-ellipse (canvas left &optional top right bot)
;;; aclpc uses quite a different set of parameters for ellipses
;;; centre, semi-major and minor axes, semi-major-axis-angle
(cond ((cg::boxp left)
;;; left is then a box which must be picked apart
(let* ((lx (cg::box-left left)) (rx (cg::box-right left))
(ty (cg::box-top left)) (by (cg::box-bottom left))
(centre (cg::make-position (/ (+ lx rx) 2) (/ (+ ty by) 2)))
; (majorhalf (- rx lx)) (minorhalf (- by ty)))
(majorhalf (/ (- rx lx) 2)) (minorhalf (/ (- by ty) 2)) ;; took out halves 10Nov99
(mp (cg::frame-child canvas)))
(cg::fill-ellipse mp centre majorhalf minorhalf 0)
(cg::draw-ellipse mp centre majorhalf minorhalf 0)))
((cg::positionp top)
;;; top is a position and thus so is left
;;; left is top-left while top is bottom-right
(let* ((lx (cg::position-x left)) (rx (cg::position-x top))
(ty (cg::position-y left)) (by (cg::position-y top))
(centre (cg::make-position (/ (+ lx rx) 2) (/ (+ ty by) 2)))
;(majorhalf (- rx lx)) (minorhalf (- by ty)))
(majorhalf (/ (- rx lx) 2)) (minorhalf (/ (- by ty) 2)) ;; took out halves 10Nov99
(mp (cg::frame-child canvas)))
(cg::fill-ellipse mp centre majorhalf minorhalf 0)
(cg::draw-ellipse mp centre majorhalf minorhalf 0)))
((cg::positionp right)
;;; left *is* left, top *is* top, right is pos(bottom-right)
(let* ((lx left) (rx (cg::position-x right)) (ty top)
(by (cg::position-y right))
(centre (cg::make-position (/ (+ lx rx) 2) (/ (+ ty by) 2)))
; (majorhalf (- rx lx)) (minorhalf (- by ty)))
(majorhalf (/ (- rx lx) 2)) (minorhalf (/ (- by ty) 2)) ;; took out halves 10Nov99
(mp (cg::frame-child canvas)))
(cg::fill-ellipse mp centre majorhalf minorhalf 0)
(cg::draw-ellipse mp centre majorhalf minorhalf 0)))
(t
;;; all four arguments are what they say they are
;;; Check for single point 05jan00
(cond ((or (eq 1 (- right left)) (eq right left))
(let ((mp (cg::frame-child canvas)))
(setf (cg:pixel-x-y mp left top)
(cg:foreground-color mp))))
(t
(let* ((lx left) (rx right) (ty top) (by bot)
(centre (cg::make-position (/ (+ lx rx) 2) (/ (+ ty by) 2)))
; (majorhalf (- rx lx)) (minorhalf (- by ty)))
(majorhalf (/ (- rx lx) 2)) (minorhalf (/ (- by ty) 2)) ;; took out halves 10Nov99
(mp (cg::frame-child canvas)))
(cg::fill-ellipse mp centre majorhalf minorhalf 0)
(cg::draw-ellipse mp centre majorhalf minorhalf 0)))
))))
(defun draw-arc (canvas start-angle arc-angle x-centre y-centre x-radius y-radius)
;;; Draws a SECTOR of an ellipse which includes drawing the radii
(let ( (lengthangle (+ start-angle arc-angle))
(centre (cg::make-position x-centre y-centre))
(mp (cg::frame-child canvas)))
(cg::draw-ellipse-sector mp centre x-radius y-radius 0 start-angle lengthangle)))
(defun fill-arc (canvas start-angle arc-angle
x-centre y-centre x-radius y-radius)
;;; Draws a filled SECTOR of an ellipse including drawing the radii
(let ( (lengthangle (+ start-angle arc-angle))
(centre (cg::make-position x-centre y-centre))
(mp (cg::frame-child canvas)))
(cg::fill-ellipse-sector mp centre x-radius y-radius 0 start-angle lengthangle)))
(defun erase-arc (canvas start-angle arc-angle
x-centre y-centre x-radius y-radius)
;;; Erases the SECTOR drawn by draw-arc
;;; and then erases the contents, if any
(let ( (lengthangle (+ start-angle arc-angle))
(centre (cg::make-position x-centre y-centre))
(mp (cg::frame-child canvas)))
(cg::erase-ellipse-sector mp centre x-radius y-radius 0 start-angle lengthangle)
(cg::erase-contents-ellipse-sector mp centre x-radius y-radius 0 start-angle lengthangle))
)
(defun invert-arc (canvas start-angle arc-angle
x-centre y-centre x-radius y-radius)
"A new version using supplied CG:: macro"
(let ((lengthangle (+ start-angle arc-angle))
(centre (cg::make-position x-centre y-centre))
(mp (cg::frame-child canvas)))
(cg::with-foreground-color (mp (comp-color canvas))
(cg::fill-ellipse-sector mp centre x-radius y-radius 0 start-angle lengthangle))) )
(defun draw-polygon (canvas list-of-points)
(let* ((mp (cg::frame-child canvas))
(pts list-of-points)
(start (first pts))
(first-x (car start))
(first-y (cdr start)))
;; Check for size = 1 right away for draw-polygon doe NOT default.
(cond ((equal (first pts) (second pts))
(setf (cg:pixel-x-y mp first-x first-y)
(cg:foreground-color mp))) ;; these 3 lines 07jan00
((and (= 4 (length pts)) (equal (first pts) (second pts)))
(cg::draw-polygonmp
(list
(cg::make-position (- first-x 1) first-y)
(cg::make-position first-x (+ 1 first-y))
(cg::make-position (+ 1 first-x) first-y)
(cg::make-position first-x (- first-y 1))
(cg::make-position (- first-x 1) first-y))))
((and (= 3 (length pts))(equal (first pts) (second pts)))
(cg::draw-polygonmp
(list
(cg::make-position (- first-x 1) (+ first-y 1))
(cg::make-position first-x (- first-y 1))
(cg::make-position (+ first-x 1) (+ first-y 1))
(cg::make-position (- first-x 1) (+ first-y 1)))))
(T
(cg::draw-polygon mp
(mapcar #'(lambda (x)
(cg::make-position
(car x) (cdr x)))
pts)))
)))
(defun draw-filled-polygon (canvas list-of-points)
(let* ((mp (cg::frame-child canvas))
(pts list-of-points)
(start (first pts))
(first-x (car start))
(first-y (cdr start)))
;;; Check for size = 1 off the top - see draw-polygon itself.
(cond ((equal (first pts) (second pts))
(setf (cg:pixel-x-y mp first-x first-y)
(cg:foreground-color mp))) ;; these 3 lines 07jan00
((equal (first pts) (second pts))
(let ((vert
;;(cg::fill-polygon canvas
(list
(cg::make-position (- first-x 1) first-y)
(cg::make-position first-x (+ 1 first-y))
(cg::make-position (+ 1 first-x) first-y)
(cg::make-position first-x (- first-y 1))
(cg::make-position (- first-x 1) first-y))))
(cg::fill-polygon mp vert)
(cg::draw-polygon mp vert)))
((and (= 3 (length pts))(equal (first pts) (second pts)))
(let ((vert
; (cg::fill-polygonmp
(list
(cg::make-position (- first-x 1) (+ first-y 1))
(cg::make-position first-x (- first-y 1))
(cg::make-position (+ first-x 1) (+ first-y 1))
(cg::make-position (- first-x 1) (+ first-y 1)))))
(cg::fill-polygon mp vert)
(cg::draw-polygon mp vert)))
(T
(let ((vert
;(cg::fill-polygon canvas
(mapcar #'(lambda (x)
(cg::make-position
(car x) (cdr x)))
pts)))
(cg::draw-polygon mp vert)
(cg::fill-polygon mp vert)))
)
))
#|
(defun draw-filled-polygon (canvas list-of-points)
(cg::fill-polygon canvas
(mapcar #'(lambda (x)
(cg::make-position
(car x) (cdr x)))
list-of-points)))
|#
(defun make-bitmap (left &optional top right bottom &aux rowbytes bm)
(declare (ignore left top right bottom rowbytes bm))
"This will make a bitmap one day. April 30, 1997 - gwb"
NIL
)
(defun copy-bits (source-bitmap dest-bitmap source-rect dest-rect
&optional (mode 0) mask-region)
(declare (ignore source-bitmap dest-bitmap source-rect dest-rect
mode mask-region))
"ACL surely contains the analoue of this. April 30, 1997 - gwb"
NIL
)
(defun kill-polygon (canvas polygon)
;;; will need to decompose polygon into its list of points
;;; if mcl thinks of it some single way
;; otherwise, if polygon IS its list of points
(let ((mp (cg::frame-child canvas)))
(cg::erase-polygon mp polygon)
(cg::erase-contents-polygon mp polygon)))
(defun draw-string (canvas string)
"Since acl draws DOWN, we have to move up first and then
draw a string on the canvas at the NEW current position with
the current font and colour."
(let* ((mp (cg::frame-child canvas))
(y-shift (cg::make-position 0 (- (cg::font-height
(cg::fontmetrics mp)))))
(current (cg::transparent-character-background mp))) ;N1
(cg::move-to mp (cg::position+ (cg::current-position mp)
y-shift))
(setf (cg::transparent-character-background mp) :transparent) ;N2
(princ string mp)
(setf (cg::transparent-character-background mp) current) ;N3
(cg::move-to mp (cg::position- (cg::current-position mp)
y-shift))
))
(defun draw-char (canvas char)
(let* ((mp (cg::frame-child canvas))
(current (cg::transparent-character-background mp))) ;N1
(setf (cg::transparent-character-background mp) :transparent) ;N2
(draw-string canvas (string char))
(setf (cg::transparent-character-background mp) current) ;N3
))
| 29,740 | Common Lisp | .l | 606 | 35.334983 | 138 | 0.486604 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 379f1baeec7fe8d010e7141937492d36f985cb8fdfbfa7f67b27e60a6c604284 | 33,652 | [
-1
] |
33,654 | host-window-sblx.lsp | rwoldford_Quail/source/window-basics/host/host-window-sblx.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; host-window-sblx.lsp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;; This file is part of the Window-Basics package intended to provide a uniform
;;; window environment for Common Lisp programming.
;;;
;;; For copyright information and history, see window-basics-copyright.lisp
;;; Authors:
;;; C.B. Hurley 1989-1991
;;; J.A. McDonald 1988-89
;;; R.W. Oldford 1989-1992
;;; J.O. Pedersen 1988-89
;;; G.W. Bennett 1996 2017
;;;--------------------------------------------------------------------
(in-package :wb)
;;; host-pane is an addition to the export list
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(host-window host-pane)))
(defclass host-window (clim::standard-application-frame)
()
(:documentation
"Mixin to canvas that captures properties of the host window system."))
#|
(defmethod cg::resize-window ((self host-window) pos)
"What happens when the window is resized"
(let ((result (call-next-method)))
(redisplay self) ;;;;;; <---- important bit
result)
)
(defmethod initialize-instance ((self host-window) &key)
(call-next-method)
;; (setf (current-position self) (list 0 0))
(setf (current-position self) (cg::make-position 0 0))
(setf *current-canvas* self))
|#
;;; Added Oct 28, 1997
;;; to set wb::*current-canvas*
(defclass host-pane (clim::application-pane) ())
;(defclass host-pane (clim-stream-pane) ())
#|
(defmethod cg::default-pane-class ((c host-window))
'host-pane)
(defmethod cg::select-window :after ((self host-window) &optional recursive-p)
(declare (special *current-canvas*)
(ignore recursive-p))
(setf *current-canvas* self))
|#
(defmethod clim::raise-frame :after ((self host-window))
(declare (special *current-canvas*))
(setf *current-canvas* (clim::raise-frame self)))
(defmethod clim:destroy-frame :after ((self host-window))
(declare (special *current-canvas*))
(setf *current-canvas* nil))
(defmethod clim:bury-frame :after ((self host-window))
(declare (special *current-canvas*))
(setf *current-canvas* nil))
;(defmethod cg::bring-window-to-front :after ((self host-pane))
; (declare (special *current-canvas*))
; (setf *current-canvas* (clim::raise-frame (clim::pane-frame self)))
#|
;;;28JAN02 this functionality has been assumed by calls to STATE
(defmethod cg::expand-window :around ((self host-pane))
(declare (special *current-canvas*))
(let ((result (call-next-method)))
(if result
(setf *current-canvas* (cg::parent self)))
result))
|#
#|
;;; Moved from Redisplay/canvas-redisplay-pc.lsp 052598 gwb.
(defmethod clim:redisplay-pane-frame :after ((c host-pane) &optional box)
(declare (special *current-canvas*)
(ignore box))
(let ((pw (clim::pane-frame c)))
(when (eq pw (first (wb::canvases)))
(setf *current-canvas* pw))
)
)
|# | 3,158 | Common Lisp | .l | 81 | 36.074074 | 89 | 0.619125 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 58a3a0d243ca969b427979b21e9691c1d98d65d69441c2a7accd06979ce2a5ac | 33,654 | [
-1
] |
33,656 | scrolling-window-sblx.lsp | rwoldford_Quail/source/window-basics/host/scrolling-window-sblx.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; scrolling-windows-sblx.lsp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;; This file is part of the Window-Basics package intended to provide a uniform
;;; window environment for Common Lisp programming.
;;;
;;; For copyright information and history, see window-basics-copyright.lisp
;;; Authors:
;;; R.W. Oldford 1989-1992
;;; G.W. Bennett 1996 2017
;;;----------------------------------------------------------------------------------
;;; A new class of windows which contain scroll-bars and a scrollable
;;; area.
;;; ----------------------------------------------------------------------------------
;;; Adapted from the scrolling-windows.lisp 1989 examples file distributed by apple
;;;(require :scrollers) ;; got it in wb-system-mcl.lisp
;;; Default changed to t for track-thumb-p
;;; my-scroller changed to the-scroller
;;; set-view-size changed to redisplay the entire window ... rwo 92
(in-package :wb)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '()))
(defclass scrolling-window ()
())
| 1,328 | Common Lisp | .l | 26 | 49.923077 | 86 | 0.5 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 134d554852e1ab42d7b9b3add7407e4559799454e0e41c8e90dc0f53dd032995 | 33,656 | [
-1
] |
33,662 | host-fonts-sblx.lsp | rwoldford_Quail/source/window-basics/host/host-fonts-sblx.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; host-fonts-sblx.lsp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) 1996 Statistical Computing Laboratory, University of Waterloo
;;;
;;; Authors:
;;;
;;; R.W.Oldford 1994.
;;; G.W.Bennett 1996 2017.
;;;
;;;-----------------------------------------------------------------------------
;;;
;;; ACL fonts have 4 attributes:
;;; Family - which is a keyword from the set
;;; :decorative - novelty fonts
;;; :modern - fixed pitch, constant stroke width
;;; :roman - proportional with serifs and variable stroke width
;;; :script - like handwriting
;;; :swiss - proportional without serifs and variable stroke width
;;; usually helvetica.
;;; nil - user does not mind which is used
;;;
;;; Face - which resembles Quail's name, with values
;;; :system :fixedsys :terminal :ms\ serif :ms\ sans\ serif
;;; :courier :symbol :small\ fonts :modern :marlett :arial
;;; :courier\ new :times\ new\ roman :wingdings
;;;
;;; Size - in PIXELS. This depends on Face at least as far as what
;;; is built in. It seems that (almost) any size can be used
;;; and that scaling is done in some way.
;;; Various forms deal with the conversion of points <-> pixels.
;;;
;;; Style - a LIST of zero or more of :bold, :italic, :underline, :condensed
;;;
;;; In this implementation a Quail font-name will be a pair (ACL_family. ACL_face)
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; 05 November 2019 gwb
;;; In mcclim, all this stuff seems to be under text-styles - Ch5 p77. ff.
;;; A text-style is a combination of 3 things - family, face, style
;;; (1) family clim supports :fix :serif :sans-serif or nil
;;; (2) face clim supports :roman :bold :italic (:bold italic) or nil
;;; these correspond to *font-styles* below
;;; (3) size logical sizes are
;;; :tiny :very-small :small :normal :large :very-large :huge :smaller : larger
;;; or there could be a real number <-> printer's points
;;; or nil
;;; There is clim::*default-text-style*
(in-package :HOST-DRAW)
(eval-when (:compile-toplevel :load-toplevel :execute)
(export '(font-transfer-modes font-styles font-transfer-modes font-names
cached-host-font clear-host-font-cache
get-canvas-font-name get-canvas-font-size get-canvas-font-style
get-canvas-font-transfer-mode host-font-description)
))
(defvar
*font-transfer-modes*
(list :boole-1
:boole-2
:boole-andc1
:boole-andc2
:boole-and
:boole-c1
:boole-c2
:boole-clr
:boole-eqv
:boole-ior
:boole-nand
:boole-nor
:boole-orc1
:boole-orc2
:boole-set
:boole-xor)
"Font transfer-modes cache")
#|
(defvar
*points-per-inch*
72
"The number of font points per inch")
|#
(defun font-transfer-modes ()
*font-transfer-modes*)
;;; acl code
;(defvar
; *font-styles*
; (list :ROMAN :BOLD :ITALIC :BOLD-ITALIC)
; "Font styles cache")
;;; clim code
(defvar
*mcclim-font-styles*
(list :roman :bold :italic (list :bold :italic) nil)
"Mcclim font faces, which acl called font-styles!")
(defun mcclim-font-styles ()
"A list of styles - the fourth attribute of a font"
*mcclim-font-styles*)
(defun font-styles ()
"A list of styles - the fourth attribute of a font"
*mcclim-font-styles*)
#|
(defun font-names ()
"Collects (family.face) list for (cg::screen cg::*system*)"
;(declare (special (cg::screen cg::*system*)))
(let (fonts
(root (cg::screen cg::*system*)))
(cg::with-device-context (hdc (cg::screen cg::*system*))
(loop for face in (cg::font-faces root)
do
(loop for family in (list :ROMAN :BOLD :BOLD-ITALIC :ITALIC NIL)
do
(push (cons family face) fonts))
))
fonts))
|#
;;; For now
(defvar *mcclim-font-family*
(list :fix :serif :sans-serif nil)
"Mcclim font families which acl calls font-faces"
)
(defun mcclim-font-family ()
"A list of families"
*mcclim-font-family*)
;;; Now we can define font-names as above
;;; Two utility forms
(defun cons-cartesian-product (x y)
"Creates the list of all (elt-of-x . elt-of-y)"
(let (w)
(dolist (p x w)
(dolist (q y)
(push (cons p q) w)))))
(defun list-cartesian-product (x y)
"Creates the list of all (elt-of-x elt-of-y)"
(let (w)
(dolist (p x w)
(dolist (q y)
(push (list p q) w)))))
(defun font-names ()
"Collects (family.face) list for (find-port)"
(cons-cartesian-product *mcclim-font-family* *mcclim-font-styles*))
(defvar *mcclim-font-sizes*
(list :normal :tiny :very-small :small :large :very-large :huge :smaller :larger nil)
"A list of mcclim font styles")
(defun mcclim-font-sizes ()
"Returns a list of mcclim font sizes"
*mcclim-font-sizes*)
#| Does not seem to be used
(defvar
*font-names*
NIL
"Font name cache")
|#
#| For now but goodness knows how to deal with this in any real sense
There is (clim-extensions:port-all-font-families (find-port))
which returns a list of 'available' families [in clim's sense]
but this is clearly inaccurate since most of the text-styles do not use DejaVu !
And the returned list does not include, for exmaple, :roman which is widely used
(defun built-in-font-types (&optional (canvas (cg::screen cg::*system*)))
"Creates a list of (list (cons family face) size style) for most of the
supplied fonts omitting ornamental ones."
(let (whole-list
(f-family (list :modern :roman :swiss NIL)))
;; :decorative and :script omitted from family
(cg::with-device-context (hdc (cg::screen cg::*system*))
(loop for a-family in f-family
do
(let (f-faces
(all-faces (cg::font-faces canvas)))
(loop for face in all-faces
do
(push face f-faces))
(loop for a-face in f-faces
do
(let ((f-sizes (cg::font-sizes canvas a-face)))
(loop for a-size in f-sizes
do
(let ((f-styles (list '() :bold :italic :underline :condensed)))
(loop for a-style in f-styles
do
(push (list (cons a-family a-face) a-size a-style) whole-list))))))))
)
whole-list))
|#
(defvar
*built-in-font-types* NIL ;create variable
;(built-in-font-types)
) ;; 09APR2020
;;; 29JAN2021
(defun built-in-font-types ()
"Creates a list of (list (cons family face) size style) for most of the
supplied fonts omitting ornamental ones."
(setf *built-in-font-types*
(list-cartesian-product (cons-cartesian-product *mcclim-font-family* *mcclim-font-styles*) *mcclim-font-sizes*)
))
(setf *built-in-font-types* (built-in-font-types))
(defun cached-host-font (canvas-font &optional (fonts *built-in-font-types*))
"Returns the host font that has been cached for this canvas-font.~
if one is not cached, it is found, cached, and returned."
(declare (ignorable fonts)) ;10MAY2024 for compiler style-warning
(let ((host-font (sixth canvas-font)))
(unless host-font
(setf host-font
(clim-user::make-text-style
;:family
(let ((name (second canvas-font)))
(if (member name (list :fix :serif :sans-serif))
name
nil))
;:face is s list
;; CLIM use it only if face has a cdr, otherwise just the element of face
(if (cdr (third canvas-font))
(third canvas-font)
(car (third canvas-font)))
;:size
(fourth canvas-font)
))
(nconc canvas-font (list host-font)))
host-font)
)
(defun clear-host-font-cache (canvas-font)
"Clears the host-font cache for this canvas-font."
(if (sixth canvas-font)
(rplacd (last canvas-font 2) nil)))
(defun get-canvas-font-name (host-font)
"Translates the host Common Lisp font representation to get the name
of the corresponding canvas-font in window-basics."
;(cons (cg::font-family host-font) (cg::font-face host-font))
(clim:text-style-family host-font)
)
(defun get-canvas-font-size (host-font)
"Translates the (pixel) size of the host Common Lisp font to the
(point) size of the corresponding canvas-font in window-basics."
;(cg::with-device-context (hdc (cg::screen cg::*system*))
;(font-pixel-to-point (cg::font-size host-font) canvas))
(clim:text-style-size host-font)
)
(defun get-canvas-font-style (host-font)
"Translates the host Common Lisp font representation to get the style
of the corresponding canvas-font in window-basics."
;(cg::with-device-context (hdc (cg::screen cg::*system*))
;(or (cg::font-style host-font) :plain))
(clim:text-style-face host-font)
)
(defun get-canvas-font-transfer-mode (host-font)
"Translates the host Common Lisp font representation to get the transfer-mode
of the corresponding canvas-font in window-basics."
(declare (ignore host-font))
;; don't know what we mean by this yet.
;:boole-1
nil)
#|
(defun host-font-description (host-font)
"Returns four values that represent (in pixels) the ascent,
descent, max-width, and leading (suggested spacing between
lines) of the host-font."
(let ((scrn (cg::screen cg::*system*)))
(cg::with-device-context (hdc scrn)
(if (cg::fontp host-font)
(let ((old-fh (cg::font-handle scrn))
font-metrics ascent descent width leading)
;(cg::set-font scrn host-font) 18oct05
(setf (cg::font scrn) host-font) ;18oct05
(setf font-metrics (cg::fontmetrics scrn))
(setq ascent
(cg::font-ascent font-metrics)
descent
(cg::font-descent font-metrics)
width
(cg::font-max-char-width font-metrics)
leading
(cg::font-leading font-metrics))
;(cg::set-font scrn old-fh) 18oct05
(setf (cg::font scrn) old-fh) ;18oct05
(values ascent descent width leading)
)
(error "Not a host font! : ~s" host-font)
)
)
)
)
|#
(defvar ascent nil)
(defvar descent nil)
(defvar width nil)
(defvar leading nil)
(defun host-font-description (host-font &key (pane (clim-user::frame-panes wb::*system-default-menubar*))) ;wb::*quail-menubar-window*))) ;*quail-menubar-pane*))
"Returns four values that represent (in pixels) the ascent,
descent, max-width, and leading (suggested spacing between
lines) of the host-font."
(setf ascent (clim:text-style-ascent host-font pane))
(setf descent (clim:text-style-descent host-font pane))
(setf width (clim:text-style-width host-font pane))
(setf leading (clim:text-style-height host-font pane))
(values ascent descent width leading))
;(eval-when (:compile-toplevel :load-toplevel)
; (host-font-description (clim:make-text-style :fix :roman :large) :pane (clim-user::frame-panes wb::*system-default-menubar*)))
#|
(defun font-pixel-to-point (pixel &optional (canvas (cg::screen cg::*system*)))
"Returns the point size of a font for canvas given pixel size."
(let ((scrn (cg::screen cg::*system*)))
(cg::with-device-context (hdc scrn)
(round (* *points-per-inch* (/ pixel (cg::stream-units-per-inch canvas)))))
))
(defun font-point-to-pixel (point &optional (canvas (cg::screen cg::*system*)))
"Returns the pixel size of a font for canvas given point size."
(let ((scrn (cg::screen cg::*system*)))
(cg::with-device-context (hdc scrn)
(round (* (cg::stream-units-per-inch canvas) (/ point *points-per-inch*))))
))
|# | 12,507 | Common Lisp | .l | 309 | 33.601942 | 161 | 0.595079 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 10a081181152f9a7285df4077f83ae17ff0d39c69752a56f47ec4a9f30c45109 | 33,662 | [
-1
] |
33,667 | host-menu-canvas-pc.lsp | rwoldford_Quail/source/window-basics/host/host-menu-canvas-pc.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; host-menu-canvas-pc.lsp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada
;;; This file is part of the Window-Basics package intended to provide a uniform
;;; window environment for Common Lisp programming.
;;;
;;; For copyright information and history, see window-basics-copyright.lisp
;;; Authors:
;;; R.W. Oldford 1989-1991
;;; G.W. Bennett 1996
;;; This file supersedes mn-c-apc.lsp
;;; was new-hmc-pc.lsp but became hmc-pc.lsp of May 19 1998
;;; to test building of Quail menubar ... gwb 051998
;;;-------------------------------------------------------------------------
(in-package :wb)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(*last-menubar* *system-default-menubar*)))
(defclass host-menu-canvas ()
()
(:documentation "A class to define how title menus should appear."))
(defclass qmbwin (cg::frame-window) ())
(defvar *system-default-menubar*
NIL
"The default menubar of the system.")
;; Added 042098 gwb
(defvar *extra-bar-height* NIL
"The width of an extra line on *quail-menubar*")
;; Added 042098 gwb
(defun set-extra-bar-height (&key (height 23))
"Sets the vertical adjustment of *quail-menubar* when an extra~
line is needed"
(setf *extra-bar-height* height))
;; Added 042098 gwb
(defvar *quail-menubar-window* NIL
"The window which hosts the Quail Menubar~
needed also to host the font wrt which menu calculations are performed.~
Its value will be established in make-default-system-menubar
which is called by set-system-default-menubar.")
;;; NOTE *title-normal-font* is used only in this file to get main menubar spacing correct.
;;; However, this definition is also in wb/fonts/default-fonts-pc.lsp as *prompt-normalfont*,
;;; whence it is exported. [fonts is after this file in window-basics.asd .. the current
;;; definition avoids compiler complaints.]
;;; If this definition is changed, consider whether the *prompt-normal-font* should
;;; be adjeusted too. gwb 28sep2023
(defvar *title-normal-font* (cg::make-font :roman "times new roman" 20)
"Canvas font used for menubars and prompts")
(defun menu-title-width (mnu &optional (stream *quail-menubar-window*))
"Finds the pixel width of mnu on the stream (default
*quail-menubar-window*).~
mnu can be a menu or a menu-item."
;; 20 is a fudge factor.
(let ((scrn (cg::screen cg::*system*))
;(a-font (wb::canvas-font-to-host-font wb::*prompt-normal-font*))
)
(if (cg::menu-item-p mnu)
(+ 20 (cg::with-font (scrn *title-normal-font*)
(cg::stream-string-width stream
(cg::title mnu))
)
)
(+ 20 (cg::with-font (scrn *title-normal-font*)
(cg::stream-string-width stream
(cg::title mnu))
)
)
))
)
(defun total-menu-title-width (mnb &optional
(stream *quail-menubar-window*))
"Find the sum of the stream-string-widths of the titles of the menus~
currently on mnb wrt stream (default *quail-menubar-window*)."
;; 20 is a factor which seems adequate.
(declare (ignore stream)) ;;30JUN2023
(let ((s 0)
(scrn (cg::screen cg::*system*))
;(a-font (wb::canvas-font-to-host-font wb::*prompt-normal-font*))
)
(loop for mnu in (cg::menu-items mnb)
do
(setq s (+ s (cg::with-font (scrn *title-normal-font*)
(cg::stream-string-width
(cg::screen cg::*system*)
(cg::title mnu))
20))))
s))
(defun total-menu-width (mnb)
"Find the sum of the stream-string-widths of the titles of the menus~
currently on menubar mnb"
(let ((s 0))
(loop for mnu in (cg::menu-items mnb)
do
(setq s (+ s
(let ((scrn (cg::screen cg::*system*))
;(a-font (wb::canvas-font-to-host-font wb::*prompt-normal-font*))
)
(cg::with-font (scrn *title-normal-font*)
(cg::stream-string-width scrn (cg::title mnu))
)
))))
s))
;; Added 042098 gwb
(defvar *quail-window-base-height* NIL
"The height (pixels) of just the title strip of *quail-menubar-window*.")
;; Added 042098 gwb
(defun set-quail-window-base-height (&key (height 31))
"Sets the height (pixels) of just the title strip of *quail-menubar-window*."
(setf *quail-window-base-height* height))
;; Added 042098 gwb
(defvar *quail-window-min-width* NIL
"The minimum width (pixels) to hold title plus controls.")
;; Added 042098 gwb
(defun set-quail-window-min-width (&key (width 250))
"Sets the minimum width (pixels) to hold title plus controls."
(setf *quail-window-min-width* width))
(defun make-system-default-menubar ()
"Makes the default quail menubar which is a bitmap-window + menubar~
which cannot be user-scrolled or user-resized.~
Returns the menubar of the window."
(unless (and *quail-window-min-width* *quail-window-base-height*
*extra-bar-height*)
(set-quail-window-min-width)
(set-quail-window-base-height)
(set-extra-bar-height))
(let* (( win (cg::make-window :qmbwin ;':qmbwin 11JUL2023
:device 'cg::bitmap-window :parent (cg::screen cg::*system*) :title "QUAIL MENUBAR"
:user-resizable NIL :user-scrollable NIL
:window-exterior (cg::make-box 1 1
(+ 1 *quail-window-min-width*)
(+ *quail-window-base-height* *extra-bar-height*))
:font (cg::make-font-ex nil :Arial 13 nil)
)
;( mb1 (cg::make-window ':qmb :device 'cg::menu-bar :parent win )) ;;30JUN2023 seems not to be needed
)
;(cg::menu win) ;(cg::window-menu win) try this 15jun2004
)
(cg::open-menu NIL
'cg::menu-bar win)
(setf *quail-menubar-window* win)
(cg::menu win)
))
(defun set-system-default-menubar
(&optional (menubar (make-system-default-menubar)))
"Sets the *system-default-menubar* to be the value of the optional ~
argument menubar. Defaults to a the menubar of a
non-scrollable, non-resizable bitmap-window."
; (declare (special cg::*screen*))
(setf *system-default-menubar* menubar)
)
(eval-when (load)
(set-system-default-menubar)
;(setf *quail-menubar* *system-default-menubar*) ;; 11JUN2023 since *q-m* is only used in this file, twice otherwise for extra-height ??
)
(defvar *last-menubar* *system-default-menubar*
"The list of elements of the last menubar. To be updated ~
and downdated as canvases are activated and deactivated.")
(defun spot-on-menubar (mnb mnu)
"Finds position of mnu on mnb using titles~
in menu-item-titles of mnb.
mnu can be a menu or a menu-item."
(let* ((title (if (cg::menu-item-p mnu) (cg::title mnu)
(cg::title mnu)))
(items (cg::menu-items mnb))
(menu-titles (mapcar #'cg::title items))
(spot (position title menu-titles :test #'string-equal)))
spot))
(defun add-line-to-menubar (win mnb mnu)
"If necessary increases the height of win by enough to accomodate~
a new line of menus. *extra-bar-height* is that amount"
(unless *extra-bar-height*
(set-extra-bar-height))
(let* ((winbox (cg::exterior win))
(wintopleft (cg::box-top-left winbox))
(winwidth (cg::box-width winbox))
(win-height (cg::box-height winbox))
(n-full-bars (floor (/ (total-menu-title-width mnb) (screen-width))))
)
(when (and (not (spot-on-menubar mnb mnu))
(> (+ (total-menu-title-width mnb) (menu-title-width mnu))
(* (+ 1 n-full-bars) (screen-width))))
(setf (cg::exterior win)
(cg::make-box-relative-from-corner wintopleft winwidth
(+ win-height *extra-bar-height*)))))
NIL)
(defun remove-lines-from-menubar (win mnb mnu)
"If necessary decreases the height of win by enough to accomodate~
removal of one or more lines of menus. *extra-bar-height* is that amount"
(declare (ignore mnu)) ;It's already gone
(unless *quail-window-base-height* (set-quail-window-base-height))
(let* ((winbox (cg::exterior win))
(wintopleft (cg::box-top-left winbox))
(winwidth (cg::box-width winbox))
(win-height (cg::box-height winbox))
(n-full-bars (floor (/ (total-menu-title-width mnb) (screen-width))))
(nbars (floor (/ win-height wb::*extra-bar-height*)))
)
(when (and ;(> n-full-bars 0)
(> nbars 2)
(< (total-menu-title-width mnb)
(* (+ 1 n-full-bars) (screen-width))))
(setf (cg::exterior win)
(cg::make-box-relative-from-corner wintopleft (+ winwidth 20)
(+ *quail-window-base-height* (* (+ 1 n-full-bars) *extra-bar-height*))))
)
NIL))
(defun extend-menubar-by-menu (mnb mnu)
"If necessary extends the window of mnb ~
- to accomodate addition of mnu"
(let* ((win (cg::parent mnb))
(update (+ (total-menu-title-width mnb)
;; may need to update wrt win
(+ 20 (menu-title-width mnu))))
(wintopleft (cg::exterior-top-left win))
(winwidth (cg::exterior-width win))
(winheight (cg::exterior-height win))
)
(when (and (< update (screen-width))
(< winwidth update))
;;; It seems that I have to setf the window-interior for I cannot just
;;; setf its box-right
;;; 10 is a fudge factor which seems sufficient.
;; Following comment from quail-menubar version ... rwo
;;; 4 is a fudge factor which seems sufficient.
(setf (cg::exterior win)
(cg::make-box-relative-from-corner
wintopleft (+ update 10) winheight))
)
NIL))
(defun contract-menubar-by-menu (mnb mnu)
"If necessary contracts the window of mnb to accomodate removal of mnu~
which has gone anyway so ignore it"
(declare (ignore mnu))
(let* ((win (cg::parent mnb))
(update (total-menu-title-width mnb ))
(wintopleft (cg::exterior-top-left win))
(winwidth (cg::exterior-width win))
(winheight (cg::exterior-height win))
)
(when (> winwidth update)
;;; It seems that I have to setf the window-interior for I cannot just
;;; setf its box-right . Again 20 (10?)
;; is a fudge factor which seems to work.
(setf (cg::exterior win)
(cg::make-box-relative-from-corner
wintopleft (max (+ update 20 )
*quail-window-min-width*) winheight))
)
NIL ))
;;; New version after change to single QMB
(defun put-title-menus-on-menubar (canvas)
"title-menubar seems to be a list of things"
(declare
(special *current-canvas*
*system-default-menubar*
*last-menubar*))
(setf *current-canvas* canvas)
(let ((title-menus (title-menus-of canvas))
(title-menubar *system-default-menubar*))
(when
title-menus
(setf title-menus
(sort (loop for m in title-menus collect m)
#'(lambda (k1 k2)
(string< (string k1) (string k2)))
:key #'car))
(setf title-menubar
(loop for (title . m) in title-menus
do
;(unless (spot-on-menubar title-menubar m)
;(extend-menubar-by-menu title-menubar m)
(cg::add-to-menu title-menubar
(make-instance 'cg::menu-item :title (cg::title m)
:value m))
;)
))
)
(setf *last-menubar* title-menubar)
)
)
;;; end new version.
;;; START Original version of add-menu-in-menubar 18JUN2023
(defun add-menu-in-menubar (menu &optional
(menubar *system-default-menubar*))
"Adds the menu to a menubar. ~
if it is not already there. Adjusts the width of the menubar if necessary.~
menu may be a menu or a menu-item
(:see-also remove-menu-from-menubar)"
(declare (special *system-default-menubar*))
(unless (spot-on-menubar menubar menu)
;(add-line-to-menubar (cg::parent menubar) menubar menu) ;;26JUN2023
;(extend-menubar-by-menu menubar menu) ;;26JUN2023
(cg::add-to-menu menubar ;menu menubar
(if (cg::menu-item-p menu)
menu
(make-instance 'cg::menu-item :title (cg::title menu)
:value menu)))))
;;; END Original version of add-menu-in-menubar 18JUN2023
#|
;;; REVISED VERSION 18JUN2023
(defun add-menu-in-menubar (menu &optional
(menubar *system-default-menubar*))
"Adds the menu to a menubar. ~
if it is not already there. Adjusts the width of the menubar if necessary.~
menu may be a menu or a menu-item
(:see-also remove-menu-from-menubar)"
(declare (special *system-default-menubar*))
(unless (spot-on-menubar menubar menu)
(add-line-to-menubar (cg::parent menubar) menubar menu)
(extend-menubar-by-menu menubar menu))
(cg::add-to-menu menubar
(if (cg::menu-item-p menu)
menu
(make-instance 'cg::menu-item :title (cg::title menu)
:value menu))))
|#
(defun remove-menu-from-menubar (menu &optional (menubar
*system-default-menubar*))
"Removes the menu from a menubar. ~
if it is there. Adjusts the width of the menubar after removal.
(:see-also install-quail-menubar add-menu-in-menubar)"
(let* ((items (cg::menu-items menubar))
(menu-titles (mapcar #'cg::title items))
(title (cg::title menu))
(spot (position title menu-titles :test #'string-equal)))
(when spot (loop for i from spot to (1- (length items))
do
(cg::remove-from-menu menubar (elt items i))
)) ;; strip everything off from spot to the end - OK
(remove-lines-from-menubar (cg::parent menubar)
menubar menu)
(contract-menubar-by-menu menubar menu)
(when spot (loop for i from (1+ spot) to (1- (length items))
do
(add-menu-in-menubar (elt items i) menubar)))
;;(release-menu-space menu)
))
(defmethod initialize-instance :after ((self host-menu-canvas)
&rest initargs)
(declare (ignore initargs))
(if (title-menus-of self)
(put-title-menus-on-menubar self)))
;;; Added 19 June 1998. See closing-hmc.lsp
(defmethod cg::user-close ((w host-menu-canvas))
(declare (special *current-canvas*))
(let ((tms (title-menus-of w))
(result (call-next-method)))
(when result
(loop for (title . tm) in tms
do
(wb::remove-menu-from-menubar tm)
(wb::release-menu-space tm)
)
(setf *current-canvas* (canvas-at-top))
(if *current-canvas*
(put-title-menus-on-menubar *current-canvas*)))
result))
#+:aclpc-linux (setf (cg::height wb::*quail-menubar-window*) 49)
| 16,054 | Common Lisp | .l | 358 | 35.304469 | 138 | 0.579885 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 934279afb627b3f3d1fca0a8582900ee6a7d28487629d57fa4d62c3d700778b5 | 33,667 | [
-1
] |
33,668 | host-system-sblx.lsp | rwoldford_Quail/source/window-basics/host/host-system-sblx.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; host-system-sblx.lsp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) 1991 Statistical Computing Laboratory, University of Waterloo
;;; Authors:
;;; R.W. Oldford 1991.
;;; G.W. Bennett 2017
;;;--------------------------------------------------------------------------------
(in-package :wb)
;(eval-when (:compile-toplevel :load-toplevel :execute)
;(shadow '(MAKE-POSITION COPY-POSITION POSITION-X POSITION-Y
;MOVE-TO LINE-TO DRAW-LINE DRAW-ELLIPSE DRAW-POLYGON) ))
;; (use-package :common-graphics)
| 701 | Common Lisp | .l | 13 | 50.692308 | 83 | 0.40843 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 54a4fedd2f00e50be1639377431df0cf5540e4d3ba524376705cd910c00079e4 | 33,668 | [
-1
] |
33,670 | host-menu-canvas-sblx.lsp | rwoldford_Quail/source/window-basics/host/host-menu-canvas-sblx.lsp | ;;; This is ~/RESERVE/lc2-Quail/source/window-basics/host/new-host-menu-canvas-sblx.lsp
;;; a re-type of h-m-c-sblx.lsp
;;; to try to get around the halt of the compile/load od that .fasl
;;; for reasons I do not understand
;;; 13 October 2020
(in-package :wb)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(*last-menubar* *system-default-menubar*)))
(defclass host-menu-canvas ()
()
(:documentation "A class to define how title menus should appear."))
(defvar *system-default-menubar*
NIL
"The default menubar of the system.")
#|
(defvar *quail-menubar-window* NIL
"The window which hosts the Quail Menubar~
needed also to host the font wrt menu calculations are performed.
Its vaue will be established in make-default-system-menubar
which is called by set-system-default-menubar.")
|#
(defvar *system-default-menubar-base-height* NIL
"The height (pixels) of just the title strip of *system-default-menubar*.")
(defun set-system-default-menubar-base-height (&key (height 100))
"Sets the height (pixels) of just the title strip of *system-default-menubar*."
(setf *system-default-menubar-base-height* height))
(define-application-frame QUAILMENUBAR ()
()
(:menu-bar QUAILMENUBAR-command-table)
(:panes
(display :application))
(:layouts
(default display))
(:geometry :height (set-system-default-menubar-base-height)))
(define-QUAILMENUBAR-command com-quail ()
)
(define-QUAILMENUBAR-command com-plots ()
)
(define-QUAILMENUBAR-command com-extra-menus ()
)
(define-QUAILMENUBAR-command com-inactive ()
)
(make-command-table 'quail-command-table
:errorp NIL
:menu '(("Inactive" :command com-inactive)))
(make-command-table 'plots-command-table
:errorp nil
:menu '(("Inactive" :command com-inactive)))
(make-command-table 'extra-menus-command-table
:errorp nil
:menu '(("Inactive" :command com-inactive)))
(make-command-table 'QUAILMENUBAR-command-table
:errorp nil
:menu '(("Quail" :menu quail-command-table)
("Plots" :menu plots-command-table)
("Extra Menus" :menu extra-menus-command-table)))
(defvar *system-default-menubar-thread-name* "QMB")
(defun set-system-default-menubar-thread-name (&key (string "QMB"))
(setf *system-default-menubar-thread-name* string))
(defun make-default-system-menubar (&key (thread-name *system-default-menubar-thread-name*))
(flet ((run ()
(let ((frame (make-application-frame 'QUAILMENUBAR :pretty-name "QUAIL MENUBAR")))
;(setq *quail-menubar-window* frame)
(setq *system-default-menubar* frame)
(run-frame-top-level frame))))
(sb-thread::make-thread #'run :name thread-name)))
(defvar *quail-window-base-height* NIL
"The height (pixels) of just the title strip of *quail-menubar-window*.")
(defun set-quail-window-base-height (&key (height 100))
"Sets the height (pixels) of just the title strip of *quail-menubar-window*."
(setf *quail-window-base-height* height))
#|
(defun set-system-default-menubar ()
"Sets the *system-default-menubar* to be *quail-menubar-window*
as returned from make-default-system-menubar above"
(unless *system-default-menubar*
(setf *system-default-menubar* *quail-menubar-window*)))
|#
(eval-when (:load-toplevel)
(unless *system-default-menubar*
(make-default-system-menubar)))
(defun thread-from-name (name)
(dolist (x (sb-thread::list-all-threads))
(if (string-equal name (sb-thread::thread-name x))
(return x))))
(defvar *system-default-menubar-thread* (thread-from-name *system-default-menubar-thread-name*))
(defun command-table-items (frame-symbol)
"Get command table items from an application frame identified by frame-symbol"
(let (foo)
(clim-user::map-over-command-table-commands
(lambda (elt) (push elt foo))
(clim-user::frame-command-table (clim-user::find-application-frame frame-symbol)))
(nreverse foo)))
(defvar *last-menubar* *system-default-menubar*
"The list of elements of the last menubar. To be updated ~
and downdated as canvases are activated and deactivated.")
| 3,985 | Common Lisp | .l | 95 | 39.726316 | 107 | 0.747412 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | ac84d77d8283fabfde0c688aa2229b42c04c5f9b3c6cdf8c83613684494103d6 | 33,670 | [
-1
] |
33,673 | host-fonts-pc.lsp | rwoldford_Quail/source/window-basics/host/host-fonts-pc.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; host-fonts-pc.lsp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) 1996 Statistical Computing Laboratory, University of Waterloo
;;;
;;; Authors:
;;;
;;; R.W.Oldford 1994.
;;; G.W.Bennett 1996.
;;;
;;;-----------------------------------------------------------------------------
;;;
;;; ACL fonts have 4 attributes:
;;; Family - which is a keyword from the set
;;; :decorative - novelty fonts
;;; :modern - fixed pitch, constant stroke width
;;; :roman - proportional with serifs and variable stroke width
;;; :script - like handwriting
;;; :swiss - proportional without serifs and variable stroke width
;;; usually helvetica.
;;; nil - user does not mind which is used
;;;
;;; Face - which resembles Quail's name, with values
;;; :system :fixedsys :terminal :ms\ serif :ms\ sans\ serif
;;; :courier :symbol :small\ fonts :modern :marlett :arial
;;; :courier\ new :times\ new\ roman :wingdings
;;;
;;; Size - in PIXELS. This depends on Face at least as far as what
;;; is built in. It seems that (almost) any size can be used
;;; and that scaling is done in some way.
;;; Various forms deal with the conversion of points <-> pixels.
;;;
;;; Style - a LIST of zero or more of :bold, :italic, :underline, :condensed
;;;
;;; In this implementation a Quail font-name will be a pair (ACL_family. ACL_face)
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :HOST-DRAW)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(font-transfer-modes font-styles font-transfer-modes font-names
cached-host-font clear-host-font-cache
get-canvas-font-name get-canvas-font-size get-canvas-font-style
get-canvas-font-transfer-mode host-font-description)
))
(defvar
*font-transfer-modes*
(list :boole-1
:boole-2
:boole-andc1
:boole-andc2
:boole-and
:boole-c1
:boole-c2
:boole-clr
:boole-eqv
:boole-ior
:boole-nand
:boole-nor
:boole-orc1
:boole-orc2
:boole-set
:boole-xor)
"Font transfer-modes cache")
(defvar
*points-per-inch*
72
"The number of font points per inch")
(defun font-transfer-modes ()
*font-transfer-modes*)
(defvar
*font-styles*
(list :plain :bold :italic :underline :condensed)
"Font styles cache")
(defun font-styles ()
"A list of styles - the fourth attribute of a font"
*font-styles*)
(defun font-names ()
"Collects (family.face) list for (cg::screen cg::*system*)"
;(declare (special (cg::screen cg::*system*)))
(let (fonts
(root (cg::screen cg::*system*)))
(cg::with-device-context (hdc (cg::screen cg::*system*))
(loop for face in (cg::font-faces root)
do
(loop for family in (list :modern :roman :swiss NIL)
do
(push (cons family face) fonts))
))
fonts))
(defvar
*font-names*
NIL
"Font name cache")
(defun built-in-font-types (&optional (canvas (cg::screen cg::*system*)))
"Creates a list of (list (cons family face) size style) for most of the ~
supplied fonts omitting ornamental ones."
(let (whole-list
(f-family (list :modern :roman :swiss NIL)))
;; :decorative and :script omitted from family
(cg::with-device-context (hdc (cg::screen cg::*system*))
(loop for a-family in f-family
do
(let (f-faces
(all-faces (cg::font-faces canvas)))
(loop for face in all-faces
do
(push face f-faces))
(loop for a-face in f-faces
do
(let ((f-sizes (cg::font-sizes canvas a-face)))
(loop for a-size in f-sizes
do
(let ((f-styles (list '() :bold :italic :underline :condensed)))
(loop for a-style in f-styles
do
(push (list (cons a-family a-face) a-size a-style) whole-list))))))))
)
whole-list))
(defvar
*built-in-font-types*
(built-in-font-types)
)
(defun cached-host-font (canvas-font &optional (fonts *built-in-font-types*))
"Returns a real ACL font from the result of matching canvas-font ~
over a list representing real ACL fonts."
(declare (ignore fonts))
(let ((host-font (sixth canvas-font)))
(unless host-font
(setf host-font
(cg::make-font
(car (second canvas-font))
(cdr (second canvas-font))
(font-point-to-pixel (fourth canvas-font))
(if (equal (list :plain) (third canvas-font))
NIL
(third canvas-font))))
(nconc canvas-font (list host-font)))
host-font)
)
(defun clear-host-font-cache (canvas-font)
"Clears the host-font cache for this canvas-font."
(if (sixth canvas-font)
(setf canvas-font (nbutlast canvas-font))))
(defun get-canvas-font-name (host-font)
"Translates the host Common Lisp font representation to get the name ~
of the corresponding canvas-font in window-basics."
(cons (cg::font-family host-font) (cg::font-face host-font)))
(defun get-canvas-font-size (host-font &optional (canvas (cg::screen cg::*system*)))
"Translates the (pixel) size of the host Common Lisp font to the ~
(point) size of the corresponding canvas-font in window-basics."
(cg::with-device-context (hdc (cg::screen cg::*system*))
(font-pixel-to-point (cg::font-size host-font) canvas)))
(defun get-canvas-font-style (host-font)
"Translates the host Common Lisp font representation to get the style ~
of the corresponding canvas-font in window-basics."
(cg::with-device-context (hdc (cg::screen cg::*system*))
(or (cg::font-style host-font) :plain)))
(defun get-canvas-font-transfer-mode (host-font)
"Translates the host Common Lisp font representation to get the transfer-mode ~
of the corresponding canvas-font in window-basics."
(declare (ignore host-font))
;; don't know what we mean by this yet.
:boole-1)
(defun host-font-description (host-font)
"Returns four values that represent (in pixels) the ascent, ~
descent, max-width, and leading (suggested spacing between ~
lines) of the host-font."
(let ((scrn (cg::screen cg::*system*)))
(cg::with-device-context (hdc scrn)
(if (cg::fontp host-font)
(let ((old-fh (cg::font-handle scrn))
font-metrics ascent descent width leading)
;(cg::set-font scrn host-font) 18oct05
(setf (cg::font scrn) host-font) ;18oct05
(setf font-metrics (cg::fontmetrics scrn))
(setq ascent
(cg::font-ascent font-metrics)
descent
(cg::font-descent font-metrics)
width
(cg::font-max-char-width font-metrics)
leading
(cg::font-leading font-metrics))
;(cg::set-font scrn old-fh) 18oct05
(setf (cg::font scrn) old-fh) ;18oct05
(values ascent descent width leading)
)
(error "Not a host font! : ~s" host-font)
)
)
)
)
(defun font-pixel-to-point (pixel &optional (canvas (cg::screen cg::*system*)))
"Returns the point size of a font for canvas given pixel size."
(let ((scrn (cg::screen cg::*system*)))
(cg::with-device-context (hdc scrn)
(round (* *points-per-inch* (/ pixel (cg::stream-units-per-inch canvas)))))
))
(defun font-point-to-pixel (point &optional (canvas (cg::screen cg::*system*)))
"Returns the pixel size of a font for canvas given point size."
(let ((scrn (cg::screen cg::*system*)))
(cg::with-device-context (hdc scrn)
(round (* (cg::stream-units-per-inch canvas) (/ point *points-per-inch*))))
))
| 8,735 | Common Lisp | .l | 204 | 33.338235 | 128 | 0.545294 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | b4e67d4b33070c99bec8a16ac5257eeca181e5937f57c4cadba642efaf24596d | 33,673 | [
-1
] |
33,674 | host-system-pc.lsp | rwoldford_Quail/source/window-basics/host/host-system-pc.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; host-system-pc.lsp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) 1991 Statistical Computing Laboratory, University of Waterloo
;;; Authors:
;;; R.W. Oldford 1991.
;;;--------------------------------------------------------------------------------
(in-package :wb)
(eval-when (:compile-toplevel :load-toplevel :execute)
(shadow '(MAKE-POSITION COPY-POSITION POSITION-X POSITION-Y
MOVE-TO LINE-TO DRAW-LINE DRAW-ELLIPSE DRAW-POLYGON) ))
;; (use-package :common-graphics)
| 682 | Common Lisp | .l | 12 | 52.416667 | 84 | 0.397015 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | c104c38d91dbc6864eeaafa5105918a915ddde82c1ba2008524720b48e595f34 | 33,674 | [
-1
] |
33,676 | host-draw-sblx.lsp | rwoldford_Quail/source/window-basics/host/host-draw-sblx.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; host-draw-sblx.lsp
;;; for mcclim
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) 1991 Statistical Computing Laboratory, University of Waterloo
;;; Authors:
;;; R.W. Oldford 1991.
;;; G.W. Bennett 1995 2017.
;;;--------------------------------------------------------------------------------
;;; This contains checked pieces of host-draw and accumulates routines as they are done
(in-package "HOST-DRAW")
;;; MCCLIM note 25JULY2020
;;; Most of these functions refer to canvas, which is an application-frame,
;;; whereas the stream needed is its pane of type 'wb::host-pane
;;; which is defined in the wb package in host-window-sblx!!
;;; Moved the (shadw.) contents to window-basics-package.lsp 01SEP2021
;(shadow '(make-point point-x point-y draw-line draw-rectangle draw-ellipse draw-polygon))
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(make-point)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(point-x point-y *hardcopy-ptr* pen-show pen-hide pen-shown-p
pen-position pen-size set-pen-size pen-mode set-pen-mode pen-pattern
set-pen-pattern set-pen-color move-to move line-to line draw-line
draw-rectangle draw-filled-rectangle draw-inside-rectangle
erase-rect invert-rectangle draw-ellipse draw-filled-ellipse draw-arc
fill-arc erase-arc invert-arc fill-arc draw-polygon
make-bitmap copy-bits
draw-filled-polygon make-bitmap copy-bits origin set-origin
draw-string draw-char)
))
(defun is-position (arg)
(eql (type-of arg) 'CLIM:STANDARD-POINT))
(defun make-point (x &optional y)
"Returns a point having x and y as its coordinates."
(if y
(clim-user::make-point x y)
(if (is-position x) ;; There seems to be no positionp
x
(error "X (~s) is not a position or y missing" x)
)))
;; point-x point-y will have to be shadowed
(defun point-x (point)
"Returns the x-coordinate of point."
(clim-user::point-x point))
(defun point-y (point)
"Returns the y-coordinate of point."
(clim-user::point-y point))
(defvar *hardcopy-ptr*
NIL
"A system dependent pointer to an open printer device.")
;; The effect pen-show and pen-hide and pen-shown-p would have
;; to depend on things like +transparent-ink+.
(defun pen-show (canvas)
(declare (ignore canvas))
nil)
(defun pen-hide (canvas)
(declare (ignore canvas))
nil)
(defun pen-shown-p (canvas)
(declare (ignore canvas))
nil)
;; There is clim-user::pointer-position which takes pointer as an argument.
;; but its stream-cursor-position I need.
(defun pen-position (canvas)
(let ((mp (clim-user::get-frame-pane canvas 'wb::host-pane)))
(multiple-value-bind (x y)
(clim-user::stream-cursor-position mp)
(make-point x y))))
;(declare (ignore canvas))
;NIL
;)
;; width for lines comes from a :thickness argument when they are drawn
;; there is a generic fn line-style-thickness with arg line-style.
;; There is make-line-style, but I don't yet see how to get the current
;; value of thickness associated with a pane.
;; Aha! I do now. Look under medium- things!!
;; There is, for example, (medium-line-style *test-pane*) which returns
;; a standard-line-style [P 62] and then I can ask for
;; (line-style-thickness (m-l-s *t-p*)) -> 1
;; Then there is (medium-foreground/background *t-p*) and so on.
(defun pen-size (canvas)
(let* ((mp (clim-user::get-frame-pane canvas 'wb::host-pane))
(its-styles (clim-user::medium-line-style mp)))
(clim-user::line-style-thickness its-styles)
))
;; pen-size <-> line-thickness is part of (medium-line-style some-pane)
;; which is immutable (!). Thus we cannot write to it directly.
;; We have to copy the elements of the current one, replacing the
;; thickness we want.
;; When there is no v, h must be a point.
(defun set-pen-size (canvas h &optional v)
#-:sbcl(declare (inline point-x point-y))
(format t "~%Just inside set-pen-size")
(format t "~%s-p-s h is ~s " h)
(format t "~%s-p-s v is ~s " v)
(format t "~%s-p-s canvas is ~s " canvas)
(format t "~%s-p-s is it a frame ? ~s " (clim:application-frame-p canvas))
(format t "~%s-p-s its host-pane pane is ~s " (clim:get-frame-pane canvas 'host-pane))
(let* ((its-pane (clim::get-frame-pane canvas 'host-pane)) ;,_ from 'wb::host-pane 09FE21
(its-line-style (clim:medium-line-style its-pane))
(its-unit (clim:line-style-unit its-line-style))
(its-dashes (clim:line-style-dashes its-line-style))
(its-joint-shape (clim:line-style-joint-shape its-line-style))
(its-cap-shape (clim:line-style-cap-shape its-line-style))
(new-thickness (if v (floor (+ h v) 2)
(floor (+ (point-x h) (point-y h)) 2)))
(new-style (clim:make-line-style :unit its-unit :thickness new-thickness :dashes its-dashes
:joint-shape its-joint-shape :cap-shape its-cap-shape))
)
(format t "~%s-p-s In set-pen-size after defvar new-thickness check current values BEFORE make-line-style")
(format t "~%s-p-s input canvas is ~s " canvas)
(format t "~%s-p-s is canvas a frame ? ~s " (clim:application-frame-p canvas))
(format t "~%s-p-s input h is ~s " h)
(format t "~%s-p-s input v is ~s " v)
(format t "~%s-p-s its-pane is ~s " its-pane)
(format t "~%s-p-s its-line-style is ~s " its-line-style)
(format t "~%s-p-s its-unit is ~s " its-unit)
(format t "~%is-p-s ts-dashes is ~s " its-dashes)
(format t "~%s-p-s its-joint-shape is ~s " its-joint-shape)
(format t "~%s-p-s its-cap-shape is ~s " its-cap-shape)
(format t "~%s-p-s new-thickness is ~s " new-thickness)
(format t "~%s-p-s new-style is ~s " new-style)
(setf (clim:medium-line-style its-pane) new-style)
)
)
;; Need to find out what paint-operation is and
;; therefore what clim calls it
(defun pen-mode (canvas)
(declare (ignore canvas))
)
(defun set-pen-mode (canvas new-mode)
"There does not seem to be any analogue of the mode/operation in CLIM"
(declare (ignore canvas new-mode))
)
(defun set-pen-pattern (canvas new-pattern)
"Sets the drawing color of canvas to (Q)new-color"
(let ((mp (clim::get-frame-pane canvas 'wb::host-pane)))
(setf (clim:medium-foreground mp) new-pattern))
)
;; drawing in color under clim is done via he :ink option
;; to whichever drawing function is being invoked, so it's tied to
;; the drawing function rather than to the pane. But foreground and
;; background colors can be changed at any time (says P83). How
;; to do this ?
;; Apparently by using (setf (medium-foreground something)) P58
(defun set-pen-color (canvas new-color)
"Sets the drawing color of canvas to (Q)new-color"
(let ((mp (clim::get-frame-pane canvas 'wb::host-pane)))
(format t "~% Just inside h-draw:set-pen-color")
(format t "~%s-p-c new-color is ~s " new-color)
(format t "~%s-p-c canvas is ~s " canvas)
(format t "~%s-p-c is canvas a frame ? ~s " (clim:application-frame-p canvas))
(format t "~%s-p-c does canvas have a host-pane ~s " (clim:get-frame-pane canvas 'host-pane))
(setf (clim:medium-foreground mp) new-color)))
;; move-to will depend on setting the position of the mouse.
;; Said mouse is an instance of a clim pointer (p283).
;; Pointers are associated with clim ports (p283).
;; I find this via (clim::user port *some-pane*) (p353-4). Thus the
;; current position is
;;; (clim-user::pointer-position (clim-user::port-point
;;; (clim-user::port *some-pane*))).
;;; This is setfable (p283). The functions pointer-set-position [and friends]
;; are not available!
;; But really it is the position of the cursor which I need to set (P329+).
(defun move-to (canvas h &optional v)
(let ((mp (clim-user::get-frame-pane canvas 'wb::host-pane)))
(if v
(clim-user::stream-set-cursor-position mp h v)
(clim-user::stream-set-cursor-position mp
(clim-user::point-x h) (clim-user::point-y h))
)))
;; and there is stream-increment-cursor-position which does just that!
(defun move (canvas h &optional v)
(let ((mp (clim-user::get-frame-pane canvas 'wb::host-pane)))
(if v
(clim-user::stream-increment-cursor-position mp h v)
(clim-user::stream-increment-cursor-position mp (clim-user::point-x h)
(clim-user::point-y h))
)))
;; Presumably line-to draws from the current cursor position
(defun line-to (canvas h &optional v)
(let* ((mp (clim-user::get-frame-pane canvas 'wb::host-pane))
(its-curs-pos (multiple-value-bind (p q) (clim-user::stream-cursor-position mp)
(make-point p q)
)))
(clim-user::draw-line mp its-curs-pos (make-point h v))
))
(defun line (canvas h &optional v)
(let* ((mp (clim-user::get-frame-pane canvas 'wb::host-pane))
(its-curs-pos (multiple-value-bind (p q) (clim-user::stream-cursor-position mp)
(make-point p q)))
(cp-x (point-x its-curs-pos))
(cp-y (point-y its-curs-pos)))
(if v
(clim-user::draw-line* mp cp-x cp-y (+ cp-x h) (+ cp-y v))
(clim-user::draw-line* mp cp-x cp-y (+ cp-x (point-x h)) (+ cp-y (point-y h)))
)))
;; draw-line will have to be shadowed too.
(defun draw-line (canvas x1 y1 x2 y2)
(move-to canvas x1 y1)
(line-to canvas x2 y2)
(move-to canvas (make-point x2 y2)) ;; to expected end for next draw
)
;; draw-rectangle will have to be shadowed
;; (p33.) By default draw-rectangle(*) has :filled t
(defun draw-rectangle (canvas left top right bot)
(let ((mp (clim-user::get-frame-pane canvas 'wb::host-pane)))
(clim-user::draw-rectangle* mp left top right bot :filled NIL)
))
;; There seems to be no rectangle-p in clim-user.
;; (setf rect (make-rectangle p1 p2)) - where p1 and p2 are points - works
;; (type-of rect) -> the symbol STANDARD-RECTANGLE
;; so (equal (type-of zot) 'STANDARD-RECTANGLE) shuld do
;; likewise for cg::position-p -> type 'STANDARD-POINT
;; An auxiliary form to unpack various rectangle inputs
(defun unpack-rectangle-args (canvas left &optional top right bottom)
(declare (ignore canvas))
(cond ((numberp bottom)
(list left top right bottom))
((equal (type-of right) 'CLIM:STANDARD-POINT)
(list left top (clim-user::point-x right) (clim-user::point-y right)))
((equal (type-of top) 'CLIM:STANDARD-POINT)
(list (clim-user::point-x left) (clim-user::point-y left) (clim-user::point-x top) (clim-user::point-y top)))
((equal (type-of left) 'CLIM:STANDARD-RECTANGLE)
(list (clim-user::rectangle-min-x left) (clim-user::rectangle-min-y left)
(clim-user::rectangle-max-x left) (clim-user::rectangle-max-y left)))
))
;; Now we can check the type of rectangle and draw appropriately
(defun draw-inside-rectangle (canvas left &optional top right bot)
"Draws the (unfilled) rectangle left+1 top+1 right-1 bot-1 if that is not degenerate,
~a horizontal/vertical line if appropriate, or nothing."
(let* ((mp (clim-user::get-frame-pane canvas 'wb::host-pane))
(ltrb (unpack-rectangle-args canvas left top right bot))
(lx (first ltrb))
(tx (second ltrb))
(rx (third ltrb))
(bx (fourth ltrb))
)
(if (or (> (1+ lx) (1- rx)) (> (1+ tx) (1- bx)))
NIL
(if (eq (1+ lx) (1- rx))
(clim-user::draw-line* mp (1+ lx) tx (1+ lx) bx)
(if (eq (1+ tx) (1- bx))
(clim-user::draw-line* mp lx (1+ tx) rx (1+ tx))
(clim-user::draw-rectangle* mp (1+ lx) (1+ tx) (1- rx) (1- bx) :filled NIL))
))
))
;; clim-user::draw-rectangle* uses :filled T as its default
;; the following seems to work
(defun draw-filled-rectangle (canvas left &optional top right bot)
"Draws the filled rectangle left+1 top+1 right-1 bot-1 if that is not degenerate,
~a horizontal/vertical line if appropriate, or nothing."
(let* ((mp (clim-user::get-frame-pane canvas 'wb::host-pane))
(ltrb (unpack-rectangle-args canvas left top right bot))
(lx (first ltrb))
(tx (second ltrb))
(rx (third ltrb))
(bx (fourth ltrb))
)
;(format t "~% mp is ~s " mp)
;(format t "~% lx is ~d " lx)
;(format t "~% tx is ~d " tx)
;(format t "~% rx is ~d " rx)
;(format t "~% bx is ~d " bx)
(if (or (> (1+ lx) (1- rx)) (> (1+ tx) (1- bx)))
NIL
(if (eq (1+ lx) (1- rx))
(clim-user::draw-line* mp (1+ lx) tx (1+ lx) bx)
(if (eq (1+ tx) (1- bx))
(clim-user::draw-line* mp lx (1+ tx) rx (1+ tx))
(clim-user::draw-rectangle* mp (1+ lx) (1+ tx) (1- rx) (1- bx)))
))
))
;; mcclim erases by drawing with the background color explicitly, it seems.
(defun erase-rect (canvas left &optional top right bot)
(let* ((mp (clim-user::get-frame-pane canvas 'wb::host-pane))
(ltrb (unpack-rectangle-args canvas left top right bot))
(lx (first ltrb))
(tx (second ltrb))
(rx (third ltrb))
(bx (fourth ltrb))
)
(if (or (> (1+ lx) (1- rx)) (> (1+ tx) (1- bx)))
NIL
(if (eq (1+ lx) (1- rx))
(clim-user::draw-line* mp lx tx lx bx :ink (clim-user::medium-background mp))
(if (eq (1+ tx) (1- bx))
(clim-user::draw-line* mp lx tx rx tx :ink (clim-user::medium-background mp))
(clim-user::draw-rectangle* mp lx tx rx bx :filled NIL :ink (clim-user::medium-background mp)))
;(clim-user::draw-rectangle* mp (1+ lx) (1+ tx) (1- rx) (1- bx) :filled NIL :ink (clim-user::medium-background mp)))
))
))
(defun erase-filled-rectangle (canvas left &optional top right bot)
"Draws the filled rectangle left top right bot if that is not degenerate,
~a horizontal/vertical line if appropriate, or nothing."
(let* ((mp (clim-user::get-frame-pane canvas 'wb::host-pane))
(ltrb (unpack-rectangle-args canvas left top right bot))
(lx (first ltrb))
(tx (second ltrb))
(rx (third ltrb))
(bx (fourth ltrb))
)
(if (or (> (1+ lx) (1- rx)) (> (1+ tx) (1- bx)))
NIL
(if (eq (1+ lx) (1- rx))
(clim-user::draw-line* mp (1+ lx) tx (1+ lx) bx :ink (clim-user::medium-background mp))
(if (eq (1+ tx) (1- bx))
(clim-user::draw-line* mp lx (1+ tx) rx (1+ tx) :ink (clim-user::medium-background mp))
(clim-user::draw-rectangle* mp lx tx rx bx :ink (clim-user::medium-background mp)))
;(clim-user::draw-rectangle* mp (1+ lx) (1+ tx) (1- rx) (1- bx) :ink (clim-user::medium-background mp)))
))
))
;; Things to be sorted out here .. perhaps the return values from color-rgb need to the
;; *255 and rounded to integer ? Truncated more likely.
;; (mapcar #'(lambda (x) (truncate x)) (mapcar #'(lambda (y) (* 255 y)) (multiple-value-list (color-rgb +yellow+))))
;; -> (255 255 0) seems to do the job.
(defun comp-color (canvas)
"Takes the complement of the current rgb-color triple of stream - returns this new triple"
(let* ((mp (clim-user::get-frame-pane canvas 'wb::host-pane))
(current (clim-user::medium-foreground mp))
(its-rgb (mapcar #'(lambda (x) (truncate x))
(mapcar #'(lambda (y) (* 255 y)) (multiple-value-list (clim-user::color-rgb current)))))
(new_red (/ (- 255 (first its-rgb)) 255))
( new_green (/ (- 255.0 (second its-rgb)) 255))
( new_blue (/ (- 255.0 (third its-rgb)) 255))
(newfgcol (clim-user::make-rgb-color new_red new_green
new_blue)))
newfgcol))
;;(comp-color *test-frame*) {whose foreground color is +black+} ->
;; #<NAMED-COLOR "white">
;; The following seems to work
;; using :ink rather than wrapping with cg::po-invert as the Allegro version does
;; NOTE:: This requires that the rectangle be drawn after something like
;; (setf (medium-foreground *some-color*)) since invert-rectangle takes the inverse
;; or complement of that foreground. If the drawing is not done this way, there is no way
;; to get the color with which the rectangle was drawn.
(defun invert-rectangle (canvas left &optional top right bot)
"A mcclim version"
(let* ((mp (clim-user::get-frame-pane canvas 'wb::host-pane))
(ltrb (unpack-rectangle-args canvas left top right bot))
(lx (first ltrb))
(tx (second ltrb))
(rx (third ltrb))
(bx (fourth ltrb)))
(clim-user::draw-rectangle* mp lx tx rx bx :ink (comp-color canvas))
))
#|
(if bot (clim-user::draw-rectangle* mp left top right bot :ink (comp-color canvas))
(if right
(clim-user::draw-rectangle mp (clim-user::make-point left top) right :ink (comp-color canvas))
(if top
(clim-user::draw-rectangle mp left top :ink (comp-color canvas))
(clim-user::draw-rectangle* mp (clim-user::rectangle-min-x left)
(clim-user::rectangle-min-y left)
(clim-user::rectangle-max-x left)
(clim-user::rectangle-max-y left) :ink (comp-color canvas))
)
)
)
))
|#
(defun draw-ellipse (canvas left &optional top right bot)
"Draws an unfillled ellipse, parallel to the axes, for which LTRB is the surrounding box."
(let* ((mp (clim-user::get-frame-pane canvas 'wb::host-pane))
(ltrb (unpack-rectangle-args canvas left top right bot))
(cx (truncate (/ (+ (first ltrb) (third ltrb)) 2)))
(cy (truncate (/ (+ (second ltrb) (fourth ltrb)) 2)))
(semix (- (third ltrb) cx))
(semiy (- (fourth ltrb) cy))
)
(if (and (> semix 0) (> semiy 0))
(clim-user::draw-ellipse* mp cx cy semix 0 0 semiy :filled NIL)
NIL)
))
(defun draw-filled-ellipse (canvas left &optional top right bot)
"Draws a fillled ellipse, parallel to the axes, for which LTRB is the surrounding box."
(let* ((mp (clim-user::get-frame-pane canvas 'wb::host-pane))
(ltrb (unpack-rectangle-args canvas left top right bot))
(cx (truncate (/ (+ (first ltrb) (third ltrb)) 2)))
(cy (truncate (/ (+ (second ltrb) (fourth ltrb)) 2)))
(semix (- (third ltrb) cx))
(semiy (- (fourth ltrb) cy))
)
(if (and (> semix 0) (> semiy 0))
(clim-user::draw-ellipse* mp cx cy semix 0 0 semiy )
NIL)
))
(defun draw-arc (canvas start-angle arc-angle x-centre y-centre x-radius y-radius)
"Draws a SECTOR of an ellipse which includes drawing the radii"
(let ((mp (clim-user::get-frame-pane canvas 'wb::host-pane)))
(clim-user::draw-ellipse* mp x-centre y-centre x-radius 0 0 y-radius :start-angle start-angle :end-angle arc-angle :filled NIL)
))
(defun fill-arc (canvas start-angle arc-angle x-centre y-centre x-radius y-radius)
"Draws a SECTOR of an ellipse which includes drawing the radii"
(let ((mp (clim-user::get-frame-pane canvas 'wb::host-pane)))
(clim-user::draw-ellipse* mp x-centre y-centre x-radius 0 0 y-radius :start-angle start-angle :end-angle arc-angle )
))
(defun erase-arc (canvas start-angle arc-angle x-centre y-centre x-radius y-radius)
"Erases a SECTOR of an ellipse which includes the radii and the contents, if any"
(let ((mp (clim-user::get-frame-pane canvas 'wb::host-pane)))
(clim-user::draw-ellipse* mp x-centre y-centre x-radius 0 0 y-radius :start-angle start-angle :end-angle arc-angle
:filled NIL :ink (clim-user::medium-background mp))
(clim-user::draw-ellipse* mp x-centre y-centre x-radius 0 0 y-radius :start-angle start-angle :end-angle arc-angle
:ink (clim-user::medium-background mp))
))
(defun invert-arc (canvas start-angle arc-angle
x-centre y-centre x-radius y-radius)
"Inverts a filled arc"
(let ((mp (clim-user::get-frame-pane canvas 'wb::host-pane)))
(clim-user::draw-ellipse* mp x-centre y-centre x-radius 0 0 y-radius :start-angle start-angle :end-angle arc-angle
:ink (comp-color canvas))
))
;; This needs to be shadowed
(defun draw-polygon (canvas list-of-points)
"Draws an unfilled polygon defined by a list of x-y coordinates or a list of points"
(let* ((mp (clim-user::get-frame-pane canvas 'wb::host-pane))
(head (car list-of-points)))
(if (numberp head)
(clim-user::draw-polygon* mp list-of-points :filled NIL)
(if (equal (type-of head) 'CLIM:STANDARD-POINT)
(clim-user::draw-polygon mp list-of-points :filled NIL))
)))
(defun draw-filled-polygon (canvas list-of-points)
"Draws a filled polygon defined by a list of x-y coordinates or a list of points"
(let* ((mp (clim-user::get-frame-pane canvas 'wb::host-pane))
(head (car list-of-points)))
(if (numberp head)
(clim-user::draw-polygon* mp list-of-points)
(if (equal (type-of head) 'CLIM:STANDARD-POINT)
(clim-user::draw-polygon mp list-of-points)
NIL))
))
(defun make-bitmap (left &optional top right bottom &aux rowbytes bm)
(declare (ignore left top right bottom rowbytes bm))
"This will make a bitmap one day. April 30, 1997 - gwb"
NIL
)
(defun copy-bits (source-bitmap dest-bitmap source-rect dest-rect
&optional (mode 0) mask-region)
(declare (ignore source-bitmap dest-bitmap source-rect dest-rect
mode mask-region))
"ACL surely contains the analogue of this. April 30, 1997 - gwb"
NIL
)
(defun kill-polygon (canvas polygon)
"Erases a polygon+contents - input list of xi y1 coords, list of (xi,yi) points, CLIM polygon"
(let ((mp (clim-user::get-frame-pane canvas 'wb::host-pane)))
(cond ((and (listp polygon) (numberp (first polygon)))
;;; we have a long list of coordinates x1 y1 x2 y2 ...
(clim-user::map-over-polygon-segments
#'(lambda (x1 y1 x2 y2) (clim-user::draw-line* mp x1 y1 x2 y2
:ink (clim-user::medium-background mp)))
(clim-user::make-polygon* polygon))
(clim-user::draw-polygon* mp polygon :ink (clim-user::medium-background mp)))
((equal (type-of polygon) 'CLIM:STANDARD-POLYGON)
;;; we have a clim polygon
(clim-user::map-over-polygon-segments
#'(lambda (x1 y1 x2 y2) (clim-user::draw-line* mp x1 y1 x2 y2
:ink (clim-user::medium-background mp)))
polygon)
(clim-user::draw-polygon* mp (poly2crds polygon)
:ink (clim-user::medium-background mp)))
((and (listp polygon) (equal (type-of (car polygon)) 'CLIM:STANDARD-POINT))
;; we have a list of vertices
(clim-user::map-over-polygon-segments
#'(lambda (x1 y1 x2 y2) (clim-user::draw-line* mp x1 y1 x2 y2
:ink (clim-user::medium-background mp)))
(clim-user::make-polygon polygon))
(clim-user::draw-polygon mp polygon
:ink (clim-user::medium-background mp)))
)
)
)
(defun poly2crds (polygon)
"Argument is a CLIM polygon .. result is list of coordinates xi yi"
(let* ((polypts (clim-user::polygon-points polygon))
(zoo (list ())))
(mapcar #'(lambda (pt)
(setf zoo (push (clim-user::point-x pt) zoo))
(setf zoo (push (clim-user::point-y pt) zoo)))
polypts)
(rest (reverse zoo))
))
#| Not neede - for the record!
(defun pts2crds (polygon)
"Argument is list of vertices .. result is list of coordinates xi yi"
(let ((zoo (list ())))
(mapcar #'(lambda (pt)
(setf zoo (push (clim-user::point-x pt) zoo))
(setf zoo (push (clim-user::point-y pt) zoo)))
polypts)
(rest (reverse zoo))
))
|#
;;; At some point we should consider whether there is to be a *default-quail-text-style*
;;; and where it should be defined - here or down in fonts somewhere.
(defun draw-string (canvas string)
"Draws a string at the current cursor position - a tex-style needs to be supplied. Cannot be 0 0"
(let* ((mp (clim-user::get-frame-pane canvas 'wb::host-pane))
(cur-pos (multiple-value-list (clim-user::stream-cursor-position mp)))
(position (clim-user::make-point (first cur-pos) (second cur-pos))))
;(format t "~%mp is ~s " mp)
;(format t "~%current-position is ~s " current-position)
(clim-user::draw-text mp string position :text-style (clim:make-text-style :fix :bold :large))
))
(defun draw-char (canvas char)
"Uses h-draw:draw-string and thus draws at the current cursor position"
(let ((mp (clim-user::get-frame-pane canvas 'wb::host-pane)))
(draw-string mp char)
))
| 25,958 | Common Lisp | .l | 509 | 42.935167 | 136 | 0.606481 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 905c5718d86b70a52b86cf180d6944b1fdc11545ee838f8fe56c73495fc7998c | 33,676 | [
-1
] |
33,678 | host-draw-package.lsp | rwoldford_Quail/source/window-basics/host/host-draw-package.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; host-draw-package.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1991 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1992.
;;;
;;;
;;;----------------------------------------------------------------------------
#+:cl-2
(defpackage "HOST-DRAW"
;#+:sbcl-linux (:use :clim-lisp :clim :clim-extensions) ; "COMMON-LISP" 19 November 2019
;#+:aclpc-linux (:use :common-lisp)
(:use "COMMON-LISP")
(:nicknames "H-DRAW")
(:IMPORT-FROM "QUAIL-KERNEL"
*QUAIL-RESTORE-LISP-FUNCTIONS*
*QUAIL-STANDARD-INPUT*
*QUAIL-STANDARD-OUTPUT*
*QUAIL-QUERY-IO*
*QUAIL-DEBUG-IO*
*QUAIL-ERROR-OUTPUT*
*QUAIL-TRACE-OUTPUT*
*QUAIL-TERMINAL-IO*
QUAIL-PRINT
QUAIL-ERROR
QUAIL-CERROR
QUAIL-QUERY
QUAIL-Y-OR-N-P
QUAIL-YES-OR-NO-P)
#+:ccl
(:shadow
"MAKE-POINT")
#+:aclpc
(:shadow
"MOVE-TO" "LINE-TO" "DRAW-LINE" "DRAW-ELLIPSE" "DRAW-POLYGON")
#+:ccl
(:export
"MAKE-POINT"))
#-:cl-2
(in-package "HOST-DRAW" :use '(pcl lisp) :nicknames '(H-DRAW))
#-:CL-2
(IMPORT '(QUAIL-KERNEL::*QUAIL-RESTORE-LISP-FUNCTIONS*
QUAIL-KERNEL:*QUAIL-STANDARD-INPUT*
QUAIL-KERNEL:*QUAIL-STANDARD-OUTPUT*
QUAIL-KERNEL:*QUAIL-QUERY-IO*
QUAIL-KERNEL:*QUAIL-DEBUG-IO*
QUAIL-KERNEL:*QUAIL-ERROR-OUTPUT*
QUAIL-KERNEL:*QUAIL-TRACE-OUTPUT*
QUAIL-KERNEL:*QUAIL-TERMINAL-IO*
QUAIL-KERNEL:QUAIL-ERROR
QUAIL-KERNEL:QUAIL-CERROR
QUAIL-KERNEL:QUAIL-QUERY
QUAIL-KERNEL:QUAIL-Y-OR-N-P
QUAIL-KERNEL:QUAIL-YES-OR-NO-P)
"HOST-DRAW")
| 2,077 | Common Lisp | .l | 62 | 24.725806 | 91 | 0.464908 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | d5b9f3dd0568b509b0c0041c22683d3b8290e0346679097b86b6ea8fe3fdecf3 | 33,678 | [
-1
] |
33,679 | scrolling-window-pc.lsp | rwoldford_Quail/source/window-basics/host/scrolling-window-pc.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; scrolling-windows-pc.lsp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;; This file is part of the Window-Basics package intended to provide a uniform
;;; window environment for Common Lisp programming.
;;;
;;; For copyright information and history, see window-basics-copyright.lisp
;;; Authors:
;;; R.W. Oldford 1989-1992
;;; G.W. Bennett 1996
;;;----------------------------------------------------------------------------------
;;; A new class of windows which contain scroll-bars and a scrollable
;;; area.
;;; ----------------------------------------------------------------------------------
;;; Adapted from the scrolling-windows.lisp 1989 examples file distributed by apple
;;;(require :scrollers) ;; got it in wb-system-mcl.lisp
;;; Default changed to t for track-thumb-p
;;; my-scroller changed to the-scroller
;;; set-view-size changed to redisplay the entire window ... rwo 92
(in-package :wb)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '()))
(defclass scrolling-window ()
())
| 1,347 | Common Lisp | .l | 26 | 49.653846 | 87 | 0.488266 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 6ed5907ec392c75fc4109d3ae2ea2d34a39e7c98ad53d9db3c6de83783b57f22 | 33,679 | [
-1
] |
33,681 | host-window-pc.lsp | rwoldford_Quail/source/window-basics/host/host-window-pc.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; host-window-pc.lsp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;; This file is part of the Window-Basics package intended to provide a uniform
;;; window environment for Common Lisp programming.
;;;
;;; For copyright information and history, see window-basics-copyright.lisp
;;; Authors:
;;; C.B. Hurley 1989-1991
;;; J.A. McDonald 1988-89
;;; R.W. Oldford 1989-1992
;;; J.O. Pedersen 1988-89
;;; G.W. Bennett 1996
;;;--------------------------------------------------------------------
(in-package :wb)
;;; host-pane is an addition to the export list
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(host-window host-pane)))
(defclass host-window (cg::bitmap-window)
()
(:documentation
"Mixin to canvas that captures properties of the host window system."))
#|
(defmethod cg::resize-window ((self host-window) pos)
"What happens when the window is resized"
(let ((result (call-next-method)))
(redisplay self) ;;;;;; <---- important bit
result)
)
(defmethod initialize-instance ((self host-window) &key)
(call-next-method)
;; (setf (current-position self) (list 0 0))
(setf (current-position self) (cg::make-position 0 0))
(setf *current-canvas* self))
|#
;;; Added Oct 28, 1997
;;; to set wb::*current-canvas*
(defclass host-pane (cg::bitmap-pane) ())
(defmethod cg::default-pane-class ((c host-window))
'host-pane)
(defmethod cg::select-window :after ((self host-pane) &optional recursive-p)
(declare (special *current-canvas*)
(ignore recursive-p))
(setf *current-canvas* (cg::parent self)))
(defmethod cg::bring-window-to-front :after ((self host-pane) &key recurse) ;;21JUL2023 from KenC 2023-06-05, 21:41
(declare (ignore recurse)) ;; ditto
(declare (special *current-canvas*))
(setf *current-canvas* (cg::parent self)))
#|
;;;28JAN02 this functionality has been assumed by calls to STATE
(defmethod cg::expand-window :around ((self host-pane))
(declare (special *current-canvas*))
(let ((result (call-next-method)))
(if result
(setf *current-canvas* (cg::parent self)))
result))
|#
;;; Moved from Redisplay/canvas-redisplay-pc.lsp 052598 gwb.
(defmethod cg::redisplay-window :after ((c host-pane) &optional box)
(declare (special *current-canvas*)
(ignore box))
(let ((pw (cg::parent c)))
(when (eq pw (first (wb::canvases)))
(setf *current-canvas* pw))
)
) | 2,734 | Common Lisp | .l | 68 | 36.970588 | 116 | 0.601883 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 78b6ab10a385725f4f966577d77483591a14180c2fc3201065519eb4bff3ef17 | 33,681 | [
-1
] |
33,682 | cr-host-window-pc.lsp | rwoldford_Quail/source/window-basics/host/cr-host-window-pc.lsp |
On (d m y) (21 MAR 2002)
At (h:m) (16 ":" 31)
From directory "\\Program Files\\SOFTWARE\\QUAIL\\CR-QUAIL\\Source\\Window-Basics\\Host\\"
Analysing "host-window-pc.lsp"
Results to "cr-host-window-pc.lsp"
**********************************************************************
(IN-PACKAGE :WB)
----------------------------------------------------------------------
**********************************************************************
(EVAL-WHEN (:COMPILE-TOPLEVEL :LOAD-TOPLEVEL :EXECUTE)
(EXPORT '(HOST-WINDOW HOST-PANE)))
----------------------------------------------------------------------
**********************************************************************
(DEFCLASS HOST-WINDOW (CG:BITMAP-WINDOW) NIL
(:DOCUMENTATION
"Mixin to canvas that captures properties of the host window system."))
----------------------------------------------------------------------
**********************************************************************
(DEFCLASS HOST-PANE (CG:BITMAP-PANE) NIL)
----------------------------------------------------------------------
**********************************************************************
(DEFMETHOD CG:DEFAULT-PANE-CLASS ((C HOST-WINDOW)) 'HOST-PANE)
----------------------------------------------------------------------
**********************************************************************
(DEFMETHOD CG:SELECT-WINDOW :AFTER
((SELF HOST-PANE) &OPTIONAL RECURSIVE-P)
(DECLARE (SPECIAL *CURRENT-CANVAS*) (IGNORE RECURSIVE-P))
(SETF *CURRENT-CANVAS* (CG:PARENT SELF)))
----------------------------------------------------------------------
**********************************************************************
(DEFMETHOD CG:BRING-WINDOW-TO-FRONT :AFTER ((SELF HOST-PANE))
(DECLARE (SPECIAL *CURRENT-CANVAS*))
(SETF *CURRENT-CANVAS* (CG:PARENT SELF)))
----------------------------------------------------------------------
**********************************************************************
(DEFMETHOD CG:REDISPLAY-WINDOW :AFTER ((C HOST-PANE) &OPTIONAL BOX)
(DECLARE (SPECIAL *CURRENT-CANVAS*) (IGNORE BOX))
(LET ((PW (CG:PARENT C)))
(WHEN (EQ PW (FIRST (WB::CANVASES))) (SETF *CURRENT-CANVAS* PW))))
----------------------------------------------------------------------
USE-EQL: Unless something special is going on, use EQL, not EQ.
----------------------------------------------------------------------
| 2,454 | Common Lisp | .l | 42 | 54.880952 | 91 | 0.342523 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | a59b33498ec4d9a00ad014716749fa464295923cfc0f4fc39e04ee0928dee1ab | 33,682 | [
-1
] |
33,688 | host-draw-package.lsp | rwoldford_Quail/source/window-basics/host/test/host-draw-package.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; host-draw-package.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1991 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1992.
;;;
;;;
;;;----------------------------------------------------------------------------
#+:cl-2
(defpackage "HOST-DRAW"
(:nicknames "H-DRAW")
(:IMPORT-FROM "QUAIL-KERNEL"
*QUAIL-RESTORE-LISP-FUNCTIONS*
*QUAIL-STANDARD-INPUT*
*QUAIL-STANDARD-OUTPUT*
*QUAIL-QUERY-IO*
*QUAIL-DEBUG-IO*
*QUAIL-ERROR-OUTPUT*
*QUAIL-TRACE-OUTPUT*
*QUAIL-TERMINAL-IO*
QUAIL-PRINT
QUAIL-ERROR
QUAIL-CERROR
QUAIL-QUERY
QUAIL-Y-OR-N-P
QUAIL-YES-OR-NO-P)
#+:ccl
(:shadow
"MAKE-POINT")
#+:ccl
(:export
"MAKE-POINT"))
#-:cl-2
(in-package "HOST-DRAW" :use '(pcl lisp) :nicknames '(H-DRAW))
#-:CL-2
(IMPORT '(QUAIL-KERNEL::*QUAIL-RESTORE-LISP-FUNCTIONS*
QUAIL-KERNEL:*QUAIL-STANDARD-INPUT*
QUAIL-KERNEL:*QUAIL-STANDARD-OUTPUT*
QUAIL-KERNEL:*QUAIL-QUERY-IO*
QUAIL-KERNEL:*QUAIL-DEBUG-IO*
QUAIL-KERNEL:*QUAIL-ERROR-OUTPUT*
QUAIL-KERNEL:*QUAIL-TRACE-OUTPUT*
QUAIL-KERNEL:*QUAIL-TERMINAL-IO*
QUAIL-KERNEL:QUAIL-ERROR
QUAIL-KERNEL:QUAIL-CERROR
QUAIL-KERNEL:QUAIL-QUERY
QUAIL-KERNEL:QUAIL-Y-OR-N-P
QUAIL-KERNEL:QUAIL-YES-OR-NO-P)
"HOST-DRAW") | 1,833 | Common Lisp | .l | 56 | 23.428571 | 86 | 0.441874 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 7d225599564c7fd4541b74261b581e230ebb2f044ba9993344d5e5a1255866a1 | 33,688 | [
-1
] |
33,689 | rotate1.lsp | rwoldford_Quail/source/window-basics/fast-graphics/rotate1.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; rotate.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;;
;;; This file is an addition to Window-basics for moving pointclouds
;;;
;;;
;;; Authors:
;;; H.A. Chipman 1991
;;; C.B. Hurley 1991 George Washington University
;;;
;;;
;;;
;;;
;;;----------------------------------------------------------------------------------
(in-package :wb)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(rotate-point-cloud draw-point-cloud scale-data-for-region
mapply-rotation! rotate-line-segments draw-line-segments
make-rotation-transform make-shift-transform)))
(defun x-shift (region)
(declare (inline + aref round /))
#:-sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(round (+ (aref region 0) (/ (aref region 2) 2))))
(defun y-shift (region)
(declare (inline + aref round /))
#:-sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(round (+ (aref region 1) (/ (aref region 3) 2))))
(defun make-shift-transform (region)
#:-sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(make-instance '2d-shift
:x-shift (x-shift region) :y-shift (y-shift region)))
(defun make-rotation-transform (region direction )
#:-sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(let* ((xhift (x-shift region))
(yshift (y-shift region)))
(ecase direction
(:x (make-instance '3d-x-rotate&2d-shift :angle 0
:x-shift xhift :y-shift yshift))
(:y (make-instance '3d-y-rotate&2d-shift :angle 0
:x-shift xhift :y-shift yshift))
(:z (make-instance '3d-z-rotate&2d-shift :angle 0
:x-shift xhift :y-shift yshift)))))
(defun rotate-point-cloud (c points
&key axes axis-color
(steps 100) (increment (/ pi 30)) (direction :y)
size fill? symbol color invisible?
( plot-rgn (canvas-region c) )
(standardize? nil) (center? nil) (viewport-coords? nil)
erase-points erase-axes
stop-fn)
"Rotates a point-cloud using plotting traps. The point cloud is in list form~
with each sublist an x,y,z observation. !!"
#:-sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(inline canvas-move-axes
canvas-move-symbols
mapply-transform-store
)
)
(declare (inline rotatef incf))
(let ((data (append points axes )))
(if viewport-coords?
(progn
(if (and (not standardize?) center?)
(setq data (center-data-lists data))
(if standardize?
(setq data (standardize-data-lists data))))
(setq data (scale-data-for-region data plot-rgn))))
(let* ((old-points (copy-tree points)) (old-axes (copy-tree axes))
(new-points (copy-tree points)) (new-axes (copy-tree axes))
(rot (make-rotation-transform plot-rgn direction ))
(bg-color (canvas-background-color c))
(single-color? (every #'(lambda(c) (eq-colors c (car color))) color)))
(if (and (colored-canvas-p c) (not single-color?))
(setq color (rgb-colors color)))
(mapply-transform-store rot data (append old-points old-axes))
(unless erase-points
(with-pen-values-restored c
(canvas-draw-symbols c old-points :symbol symbol
:color color :fill? fill? :size size
:invisible? invisible? :single-color? single-color? )
(canvas-set-pen c :color bg-color)))
(unless erase-axes
(with-pen-values-restored c
(canvas-draw-axes c old-axes :color axis-color)
(canvas-set-pen c :color bg-color)))
(incf (angle-of rot) increment)
(mapply-transform-store rot data (append new-points new-axes))
(with-pen-values-restored c
(canvas-move-symbols c (or erase-points old-points) new-points
:symbol symbol :color color :fill? fill?
:size size :invisible? invisible?
:rgb-color? t :single-color? single-color? )
(canvas-set-pen c :color bg-color))
(with-pen-values-restored c
(canvas-move-axes c (or erase-axes old-axes) new-axes :color axis-color )
(canvas-set-pen c :color bg-color))
;;; loop with the do keyword - better than "loop". CW 03/1997.
; (loop for k from 1 below steps
; until (if (functionp stop-fn) (funcall stop-fn))
; do
(do ((k 1 (incf k)))
((or (= k steps) (if (functionp stop-fn) (funcall stop-fn))))
(incf (angle-of rot) increment)
(rotatef old-axes new-axes) (rotatef old-points new-points)
(mapply-transform-store rot data (append new-points new-axes))
(with-pen-values-restored c
(canvas-move-symbols c old-points new-points :symbol symbol
:color color :fill? fill? :size size
:invisible? invisible?
:rgb-color? t :single-color? single-color?)
(canvas-set-pen c :color bg-color)
)
(when axes
(with-pen-values-restored c
(canvas-move-axes c old-axes new-axes :color axis-color)
(canvas-set-pen c :color bg-color))))
(values rot new-points new-axes)
)))
(defun draw-point-cloud (c points
&key axes
size fill? symbol color invisible?
( plot-rgn (canvas-region c) )
(standardize? nil) (center? nil)
(viewport-coords?))
"Draws a point-cloud using plotting traps. The point cloud is in list form~
with each sublist an x,y,z observation. !!"
#:-sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(let ((data (append points axes )))
(if viewport-coords?
(progn
(if (and (not standardize?) center?)
(setq data (center-data-lists data))
(if standardize?
(setq data (standardize-data-lists data))))
(setq data (scale-data-for-region data plot-rgn))))
(let* ((bg-color (canvas-background-color c))
(scaled-data (scale-data-for-region
data plot-rgn))
(shift (make-shift-transform plot-rgn ))
(scaled-points (subseq scaled-data 0 (length points)))
(scaled-axes (subseq scaled-data (length points) )))
(mapply-transform! shift scaled-data )
(with-pen-values-restored c
(canvas-draw-symbols c scaled-points :symbol symbol
:color color :fill? fill? :size size
:invisible? invisible?)
(canvas-set-pen c :color bg-color))
(with-pen-values-restored c
(canvas-draw-axes c scaled-axes )
(canvas-set-pen c :color bg-color)
)
)))
(defmethod mapply-rotation! ((rot 3d-rotate) (a list) &key (integer? t))
#:-sbcl(declare (optimize (speed 3) (safety 0) (space 0) (compilation-speed 0))
(inline mapply-transform! ))
(declare (inline elt round * / float))
(if integer?
(mapply-transform! rot a)
(let* ((big 10000)
(integer-coefs
(loop for c in a collect
(loop for ci in c collect
(round (* big ci))))))
(mapply-transform! rot integer-coefs)
(loop for cnew in integer-coefs
for cold in a do
(loop for ci in cnew
for i upfrom 0
do
(setf (elt cold i) (float (/ ci big))))))))
(defun scale-data-for-region (data region)
"scales data so that when rotated and shifted it will always fit in a window~
with minimum dimension SIZE ~
Data should already be centered at 0"
#:-sbcl(declare (optimize (speed 3) (safety 0) (space 0) (compilation-speed 0)))
(declare (inline round *))
(let* ((size (min (aref region 2) (aref region 3)))
(d (/ size
(sqrt (loop for di in data
maximize (loop for dij in di
sum (* dij dij))))
2)))
(loop for di in data collect
(loop for dij in di collect (round (* dij d))))
))
(defun standardize-data-lists (data )
"scales 3-d data so that each dimension has mean 0 and variance 1"
#:-sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(let* ((mean #'(lambda(i)
(/ (loop for di in data sum (elt di i)) (length data))))
(sd #'(lambda(i m)
(sqrt (/ (loop for di in data sum (expt (- (elt di i) m) 2))
(length data)))))
(m0 (funcall mean 0)) (sd0 (funcall sd 0 m0))
(m1 (funcall mean 1)) (sd1 (funcall sd 1 m1))
(m2 (funcall mean 2)) (sd2 (funcall sd 2 m2)))
(loop with means = (list m0 m1 m2)
with sds = (list sd0 sd1 sd2)
for d in data collect
(loop for di in d
for m in means
for sd in sds
collect (/ (- di m) sd)))))
(defun center-data-lists (data )
"center 3-d data so that each dimension has mean 0 "
#:-sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(let* (
(mean #'(lambda(i)
(/ (loop for di in data sum (elt di i)) (length data))))
(m0 (funcall mean 0))
(m1 (funcall mean 1))
(m2 (funcall mean 2)) )
(loop with means = (list m0 m1 m2)
for d in data collect
(loop for di in d
for m in means
collect (- di m)))))
(defun rotate-line-segments (c points
&key axes axis-color
(steps 100) (increment (/ pi 30)) (direction :y)
width color invisible?
( plot-rgn (canvas-region c) )
(standardize? nil) (center? nil) (viewport-coords? nil)
erase-points erase-axes
stop-fn)
"Rotates lines using plotting traps. points gives the lines coordinates,~
where points has even length, each pair giving the segment endpoints. "
#:-sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(inline canvas-move-axes
canvas-move-lines
mapply-transform-store
)
)
(declare (inline rotatef incf))
(let ((data (append points axes )))
(if viewport-coords?
(progn
(if (and (not standardize?) center?)
(setq data (center-data-lists data))
(if standardize?
(setq data (standardize-data-lists data))))
(setq data (scale-data-for-region data plot-rgn))))
(let* ((old-points (copy-tree points)) (old-axes (copy-tree axes))
(new-points (copy-tree points)) (new-axes (copy-tree axes))
(rot (make-rotation-transform plot-rgn direction ))
(single-color? (every #'(lambda(c) (eq-colors c (car color))) color))
(single-width? (every #'(lambda(c) (= c (car width))) width))
(bg-color (canvas-background-color c))
)
(if (and (colored-canvas-p c) (not single-color?))
(setq color (rgb-colors color)))
(mapply-transform-store rot data (append old-points old-axes))
(if (and single-color? single-width?)
(setq color (car color)))
(if single-width?
(setq width (car width)))
(unless erase-points
(with-pen-values-restored c
(canvas-draw-lines c old-points
:color color :width width
:invisible? invisible?)
(canvas-set-pen c :color bg-color)))
(unless erase-axes
(with-pen-values-restored c
(canvas-draw-axes c old-axes :color axis-color)
(canvas-set-pen c :color bg-color)))
(incf (angle-of rot) increment)
(mapply-transform-store rot data (append new-points new-axes))
(with-pen-values-restored c
(canvas-move-lines c (or erase-points old-points) new-points
:color color
:width width :invisible? invisible?
:rgb-color? t )
(canvas-set-pen c :color bg-color))
(with-pen-values-restored c
(canvas-move-axes c (or erase-axes old-axes) new-axes :color axis-color )
(canvas-set-pen c :color bg-color))
; (loop for k from 1 below steps
; until (if (functionp stop-fn) (funcall stop-fn))
; do
(do ((k 1 (incf k)))
((or (= k steps) (if (functionp stop-fn) (funcall stop-fn))))
(incf (angle-of rot) increment)
(rotatef old-axes new-axes) (rotatef old-points new-points)
(mapply-transform-store rot data (append new-points new-axes))
(with-pen-values-restored c
(canvas-move-lines c old-points new-points
:color color :width width
:invisible? invisible?
:rgb-color? t :single-color? single-color?)
(canvas-set-pen c :color bg-color))
(when axes
(with-pen-values-restored c
(canvas-move-axes c old-axes new-axes :color axis-color)
(canvas-set-pen c :color bg-color))) )
(values rot new-points new-axes)
)))
(defun draw-line-segments (c points
&key axes
width color invisible?
( plot-rgn (canvas-region c) )
(standardize? nil) (center? nil)
(viewport-coords?))
"Draws lines using plotting traps. points gives the lines coordinates,~
where points has even length, each pair giving the segment endpoints. "
#:-sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(let ((data (append points axes ))
(bg-color (canvas-background-color c)))
(if viewport-coords?
(progn
(if (and (not standardize?) center?)
(setq data (center-data-lists data))
(if standardize?
(setq data (standardize-data-lists data))))
(setq data (scale-data-for-region data plot-rgn))))
(let* ((scaled-data (scale-data-for-region
data plot-rgn))
(shift (make-shift-transform plot-rgn ))
(scaled-points (subseq scaled-data 0 (length points)))
(scaled-axes (subseq scaled-data (length points) )))
(mapply-transform! shift scaled-data )
(with-pen-values-restored c
(canvas-draw-lines c scaled-points
:color color :width width
:invisible? invisible?)
(canvas-set-pen c :color bg-color))
(with-pen-values-restored c
(canvas-draw-axes c scaled-axes )
(canvas-set-pen c :color bg-color))
)))
| 17,037 | Common Lisp | .l | 353 | 33.640227 | 124 | 0.518454 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 3e37a472451679a8e8ae80b7b815630d4ab79b65d1a6682105261e1ad3179d1c | 33,689 | [
-1
] |
33,690 | point-defs-sblx.lsp | rwoldford_Quail/source/window-basics/fast-graphics/point-defs-sblx.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; working-point-defs-sblx.lsp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;; This file is an addition to Window-basics for moving pointclouds
;;;
;;; Authors:
;;; H.A. Chipman 1991
;;; C.B. Hurley 1991 George Washington University
;;; R.W. Oldford 1992.
;;; N.G. Bennett 1993
;;; G.W. Bennett 1996
;;;
;;;
;;;-------------------------------------------------------------------
(in-package :wb)
(defconstant +host-xor-mode+ (boole-to-op :boole-xor))
(defconstant +host-or-mode+ (boole-to-op :boole-1))
(defconstant +host-bic-mode+ (boole-to-op :boole-1))
(defconstant +host-copy-mode+ (boole-to-op :boole-1))
(defmacro fast-draw-box (canvas x y size fill?)
;(let ((s2 (gensym)) (lx (gensym)) (ly (gensym)) (mp (gensym)))
`(let* (;(s2 (truncate ,size 2))
;(lx (- ,x s2))
;(ly (- ,y s2))
(mp (get-frame-pane ,canvas 'host-pane)))
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(cond ((eq ,size 1)
(medium-draw-point* mp ,x ,y))
(T
(if ,fill?
(medium-draw-rectangle* mp ,x ,y (+ ,x ,size) (+ ,y ,size) T)
(medium-draw-rectangle* mp ,x ,y (+ ,x ,size) (+ ,y ,size) NIL)))
))
;)
)
;;; (test-fast-draw-box *test-frame* 100 100 20 NIL) -> an outlined box of the right size and place.
;;; on to fast-erase-box
(defmacro fast-erase-box (canvas x y size fill?)
;(let ((mpbg (gensym)) (mp (gensym)) (s2 (gensym)) (lx (gensym))
;(ly (gensym)) (mpfg (gensym)))
`(let* ((mp (get-frame-pane ,canvas 'host-pane))
(mpbg (medium-background (get-frame-pane ,canvas 'host-pane)))
;(mpfg (medium-foreground (get-frame-pane ,canvas 'host-pane)))
;(s2 (truncate ,size 2))
;(lx (- ,x s2))
;(ly (- ,y s2))
)
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(with-drawing-options (mp :ink mpbg)
(cond ((eq ,size 1)
(medium-draw-point* mp ,x ,y))
(T
(if ,fill?
(draw-rectangle* mp ,x ,y (+ ,x ,size) (+ ,y ,size) :filled T)
(draw-rectangle* mp ,x ,y (+ ,x ,size) (+ ,y ,size) :filled NIL))
)
))
)
;)
)
;;; on to fast-draw/erase-circle
;;; draw
(defmacro fast-draw-circle (canvas x y size fill? )
"Uses medium-draw-ellipse* centred at x y"
;(let ((s2 (gensym))
; (mp (gensym)))
`(let ((mp (get-frame-pane ,canvas 'host-pane)))
(cond ((eq 1 ,size)
(medium-draw-point* mp ,x ,y))
(t
(let ((s2 (if (oddp ,size) (1- (truncate (+ 1 ,size) 2))
(truncate (+ 1 ,size) 2)))) ;;; added + 1 24JNE99 oddp 11NOV99
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(if ,fill?
(medium-draw-ellipse* mp ,x ,y s2 0 0 s2 0 (* 2 pi) T)
(medium-draw-ellipse* mp ,x ,y s2 0 0 s2 0 (* 2 pi) NIL)
)
))
))
;)
)
;;; now erase
(defmacro fast-erase-circle (canvas x y size fill?)
;(let ((mpbg (gensym)) (mp (gensym)) (s2 (gensym)) (lx (gensym))
;(ly (gensym)) (mpfg (gensym)))
`(let* ((mp (get-frame-pane ,canvas 'host-pane))
(mpbg (medium-background (get-frame-pane ,canvas 'host-pane)))
;(mpfg (medium-foreground (get-frame-pane ,canvas 'host-pane)))
(s2 (truncate ,size 2))
;(lx (- ,x s2))
;(ly (- ,y s2))
)
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(with-drawing-options (mp :ink mpbg)
(cond ((eq ,size 1)
(medium-draw-point* mp ,x ,y))
(T
(if ,fill?
(medium-draw-ellipse* mp ,x ,y s2 0 0 s2 0 (* 2 pi) T)
(medium-draw-ellipse* mp ,x ,y s2 0 0 s2 0 (* 2 pi) NIL)
))
))
)
;)
)
;;; draw/erase cross
;;; draw
(defmacro fast-draw-cross (canvas x y s fill? )
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (ignore fill?))
;(let ((s2 (gensym))
; (l (gensym))
; (mp (gensym)))
`(let* ((s2 (if (oddp ,s) (1- (truncate (+ 1 ,s) 2))
(truncate (+ 1 ,s) 2)))
(l (list (h-draw::make-point (- ,x s2) ,y )
(h-draw::make-point (+ ,x s2 1) ,y )
(h-draw::make-point ,x (- ,y s2) )
(h-draw::make-point ,x (+ ,y s2 1))
))
(mp (get-frame-pane ,canvas 'host-pane)))
(medium-draw-line* mp (h-draw::point-x (first l)) (h-draw::point-y (first l)) (h-draw::point-x (second l)) (h-draw::point-y (second l)))
(medium-draw-line* mp (h-draw::point-x (third l)) (h-draw::point-y (third l)) (h-draw::point-x (fourth l)) (h-draw::point-y (fourth l)))
)
;)
)
;;; erase
(defmacro fast-erase-cross (canvas x y s fill? )
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (ignore fill?))
;(let ((s2 (gensym))
; (l (gensym))
; (mp (gensym))
; (mpbg (gensym))
; (mpfg (gensym)))
`(let* ((s2 (if (oddp ,s) (1- (truncate (+ 1 ,s) 2))
(truncate (+ 1 ,s) 2)))
(l (list (h-draw::make-point (- ,x s2) ,y )
(h-draw::make-point (+ ,x s2 1) ,y )
(h-draw::make-point ,x (- ,y s2) )
(h-draw::make-point ,x (+ ,y s2 1))
))
(mp (get-frame-pane ,canvas 'host-pane))
(mpbg (medium-background (get-frame-pane ,canvas 'host-pane)))
;(mpfg (medium-foreground (get-frame-pane ,canvas 'host-pane)))
)
(with-drawing-options (mp :ink mpbg)
(medium-draw-line* mp (h-draw::point-x (first l)) (h-draw::point-y (first l)) (h-draw::point-x (second l)) (h-draw::point-y (second l)))
(medium-draw-line* mp (h-draw::point-x (third l)) (h-draw::point-y (third l)) (h-draw::point-x (fourth l)) (h-draw::point-y (fourth l)))
)
)
;)
)
;;; draw/erase diamond
;;; draw
;;; Here is a forn which works:
; (draw-polygon* *pane* '(140 150 150 140 160 150 150 160 140 150) :filled nil :closed t)
;10200
(defmacro fast-draw-diamond (canvas x y s fill? )
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
;(let ((s2 (gensym))
; (l (gensym)) (r (gensym))
; (tp (gensym)) (b (gensym)) (mp (gensym))
; )
`(let* ((s2 (truncate ,s 2))
(l (- (the fixnum ,x) s2))
(b (+ (the fixnum ,y) s2))
(r (+ (the fixnum ,x) s2))
(tp (- (the fixnum ,y) s2))
(mp (get-frame-pane ,canvas 'host-pane)))
(declare (type fixnum l r tp b s2))
(if ,fill?
(medium-draw-polygon* mp (list ,x tp r ,y r ,y ,x b ,x b l ,y l ,y ,x tp) NIL T)
(medium-draw-polygon* mp (list ,x tp r ,y r ,y ,x b ,x b l ,y l ,y ,x tp) T NIL))
)
;)
)
;;; erase [there does not seem to be one in other point-defs files]
(defmacro fast-erase-diamond (canvas x y s fill? )
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
;(let ((s2 (gensym))
; (l (gensym)) (r (gensym))
; (tp (gensym)) (b (gensym))(mp (gensym)) (mpbg (gensym))
; )
`(let* ((s2 (truncate ,s 2))
(l (- (the fixnum ,x) s2))
(b (+ (the fixnum ,y) s2))
(r (+ (the fixnum ,x) s2))
(tp (- (the fixnum ,y) s2))
(mp (get-frame-pane ,canvas 'host-pane))
(mpbg (medium-background (get-frame-pane ,canvas 'host-pane))))
(declare (type fixnum l r tp b s2))
(with-drawing-options (mp :ink mpbg)
(if ,fill?
(medium-draw-polygon* mp (list ,x tp r ,y r ,y ,x b ,x b l ,y l ,y ,x tp) NIL T)
(medium-draw-polygon* mp (list ,x tp r ,y r ,y ,x b ,x b l ,y l ,y ,x tp) T NIL))
)
)
;)
)
;;; draw/erase triangle
;;; draw
(defmacro fast-draw-triangle (canvas x y s fill? )
;(let ((s2 (gensym))
; (l (gensym)) (r (gensym))
; (tp (gensym)) (b (gensym))
; (mp(gensym)))
`(let* ((s2 (truncate ,s 2))
(l (- (the fixnum ,x) s2))
(b (+ (the fixnum ,y) s2))
(r (+ (the fixnum ,x) s2))
(tp (- (the fixnum ,y) s2))
(mp (get-frame-pane ,canvas 'host-pane)))
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(type fixnum l r tp b s2))
(if ,fill?
(medium-draw-polygon* mp (list l b ,x tp ,x tp r b r b l b) NIL T)
(medium-draw-polygon* mp (list l b ,x tp ,x tp r b r b l b) T NIL)
))
;)
)
;;;erase
(defmacro fast-erase-triangle (canvas x y s fill? )
;(let ((s2 (gensym))
; (l (gensym)) (r (gensym))
; (tp (gensym)) (b (gensym))
; (mp(gensym))
; (mpbg (gensym)))
`(let* ((s2 (truncate ,s 2))
(l (- (the fixnum ,x) s2))
(b (+ (the fixnum ,y) s2))
(r (+ (the fixnum ,x) s2))
(tp (- (the fixnum ,y) s2))
(mp (get-frame-pane ,canvas 'host-pane))
(mpbg (medium-background (get-frame-pane ,canvas 'host-pane))))
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(type fixnum l r tp b s2))
(with-drawing-options (mp :ink mpbg)
(if ,fill?
(medium-draw-polygon* mp (list l b ,x tp ,x tp r b r b l b) NIL T)
(medium-draw-polygon* mp (list l b ,x tp ,x tp r b r b l b) T NIL)
))
)
;)
)
;;; draw/erase star
;;; draw , but first
(defconstant +cos-18+ (cos (* pi 0.1))) ;10MAY2024 to comply with convention about naming constants with + not *
(defconstant +cos-54+ (cos (* pi 0.3)))
(defconstant +sin-18+ (sin (* pi 0.1)))
(defconstant +sin-54+ (sin (* pi 0.3)))
#|
(defmacro fast-draw-star (canvas x y s fill? )
(declare (ignore fill?) (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
;(let ((r (gensym)) (r*c18 (gensym))
; (r*s18 (gensym)) (r*c54 (gensym)) (r*s54 (gensym))
; (x1 (gensym)) (y1 (gensym))
; (x2 (gensym)) (y2 (gensym))
; (x3 (gensym))
; (x4 (gensym))
; (x5 (gensym)) (y5 (gensym))
; (mp (gensym)))
;;; Check for size = 1 off the top
`(let ((mp (get-frame-pane ,canvas 'host-pane)))
(cond ((= 1 ,s)
(medium-draw-point* mp ,x ,y))
(T
(let* ((r (if (oddp ,s) (1- (truncate (+ 1 ,s) 2))
(truncate (+ 1 ,s) 2))) ;; added +1 27Jne99
(r*c18 (round (* r *cos-18*)))
(r*s18 (round (* r *sin-18*)))
(r*c54 (round (* r *cos-54*)))
(r*s54 (round (* r *sin-54*)))
(,x1 (+ (the fixnum ,x) (the fixnum r*c18)))
(,y1 (- (the fixnum ,y) (the fixnum r*s18)))
(,x2 (the fixnum ,x))
(,y2 (- (the fixnum ,y) (the fixnum r)))
(,x3 (- (the fixnum ,x) (the fixnum r*c18)))
(,x4 (- (the fixnum ,x) (the fixnum r*c54)))
(,x5 (+ (the fixnum ,x) (the fixnum r*c54)))
(,y5 (+ (the fixnum ,y) (the fixnum r*s54)))
)
(medium-draw-lines* mp (list ,x ,y ,x1 ,y1 ,x ,y ,x2 ,y2 ,x ,y ,x3 ,y1 ,x ,y ,x4 ,y5 ,x ,y ,x5 ,y5))
))))
;)
)
|#
;;;New version because of the *s
(defmacro fast-draw-star (canvas x y s fill? )
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (ignore fill?))
;(let ((r (gensym)) (r*c18 (gensym))
; (r*s18 (gensym)) (r*c54 (gensym)) (r*s54 (gensym))
; (x1 (gensym)) (y1 (gensym))
; (x2 (gensym)) (y2 (gensym))
; (x3 (gensym))
; (x4 (gensym))
; (x5 (gensym)) (y5 (gensym))
; (mp (gensym)))
;;; Check for size = 1 off the top
`(let ((mp (get-frame-pane ,canvas 'host-pane)))
(cond ((= 1 ,s)
(medium-draw-point* mp ,x ,y))
(T
(let* ((r (if (oddp ,s) (1- (truncate (+ 1 ,s) 2))
(truncate (+ 1 ,s) 2))) ;; added +1 27Jne99
(rc18 (round (* r +cos-18+)))
(rs18 (round (* r +sin-18+)))
(rc54 (round (* r +cos-54+)))
(rs54 (round (* r +sin-54+)))
(x1 (+ (the fixnum ,x) (the fixnum rc18)))
(y1 (- (the fixnum ,y) (the fixnum rs18)))
(x2 (the fixnum ,x))
(y2 (- (the fixnum ,y) (the fixnum r)))
(x3 (- (the fixnum ,x) (the fixnum rc18)))
(x4 (- (the fixnum ,x) (the fixnum rc54)))
(x5 (+ (the fixnum ,x) (the fixnum rc54)))
(y5 (+ (the fixnum ,y) (the fixnum rs54)))
)
(medium-draw-lines* mp (list ,x ,y x1 y1 ,x ,y x2 y2 ,x ,y x3 y1 ,x ,y x4 y5 ,x ,y x5 y5))
))))
;)
)
;;; erase
#|
(defmacro fast-erase-star (canvas x y s fill? )
(declare (ignore fill?) (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
;(let ((r (gensym)) (r*c18 (gensym))
; (r*s18 (gensym)) (r*c54 (gensym)) (r*s54 (gensym))
; (x1 (gensym)) (y1 (gensym))
; (x2 (gensym)) (y2 (gensym))
; (x3 (gensym))
; (x4 (gensym))
; (x5 (gensym)) (y5 (gensym))
; (mp (gensym))
; (mpbg (gensym)))
;;; Check for size = 1 off the top
`(let ((mp (get-frame-pane ,canvas 'host-pane)))
(cond ((= 1 ,s)
(medium-draw-point* mp ,x ,y))
(T
(let* ((r (if (oddp ,s) (1- (truncate (+ 1 ,s) 2))
(truncate (+ 1 ,s) 2))) ;; added +1 27Jne99
(r*c18 (round (* r *cos-18*)))
(r*s18 (round (* r *sin-18*)))
(r*c54 (round (* r *cos-54*)))
(r*s54 (round (* r *sin-54*)))
(,x1 (+ (the fixnum ,x) (the fixnum r*c18)))
(,y1 (- (the fixnum ,y) (the fixnum r*s18)))
(,x2 (the fixnum ,x))
(,y2 (- (the fixnum ,y) (the fixnum r)))
(,x3 (- (the fixnum ,x) (the fixnum r*c18)))
(,x4 (- (the fixnum ,x) (the fixnum r*c54)))
(,x5 (+ (the fixnum ,x) (the fixnum r*c54)))
(,y5 (+ (the fixnum ,y) (the fixnum r*s54)))
(mpbg (medium-background (get-frame-pane ,canvas 'host-pane)))
)
(with-drawing-options (mp :ink mpbg)
(medium-draw-lines* mp (list ,x ,y ,x1 ,y1 ,x ,y ,x2 ,y2 ,x ,y ,x3 ,y1 ,x ,y ,x4 ,y5 ,x ,y ,x5 ,y5))
)
))))
;)
)
|#
;;; new version because of the *s
(defmacro fast-erase-star (canvas x y s fill? )
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (ignore fill?))
;(let ((r (gensym)) (r*c18 (gensym))
; (r*s18 (gensym)) (r*c54 (gensym)) (r*s54 (gensym))
; (x1 (gensym)) (y1 (gensym))
; (x2 (gensym)) (y2 (gensym))
; (x3 (gensym))
; (x4 (gensym))
; (x5 (gensym)) (y5 (gensym))
; (mp (gensym))
; (mpbg (gensym)))
;;; Check for size = 1 off the top
`(let ((mp (get-frame-pane ,canvas 'host-pane)))
(cond ((= 1 ,s)
(medium-draw-point* mp ,x ,y))
(T
(let* ((r (if (oddp ,s) (1- (truncate (+ 1 ,s) 2))
(truncate (+ 1 ,s) 2))) ;; added +1 27Jne99
(rc18 (round (* r +cos-18+)))
(rs18 (round (* r +sin-18+)))
(rc54 (round (* r +cos-54+)))
(rs54 (round (* r +sin-54+)))
(x1 (+ (the fixnum ,x) (the fixnum rc18)))
(y1 (- (the fixnum ,y) (the fixnum rs18)))
(x2 (the fixnum ,x))
(y2 (- (the fixnum ,y) (the fixnum r)))
(x3 (- (the fixnum ,x) (the fixnum rc18)))
(x4 (- (the fixnum ,x) (the fixnum rc54)))
(x5 (+ (the fixnum ,x) (the fixnum rc54)))
(y5 (+ (the fixnum ,y) (the fixnum rs54)))
(mpbg (medium-background (get-frame-pane ,canvas 'host-pane)))
)
(with-drawing-options (mp :ink mpbg)
(medium-draw-lines* mp (list ,x ,y x1 y1 ,x ,y x2 y2 ,x ,y x3 y1 ,x ,y x4 y5 ,x ,y x5 y5))
)
))))
;)
)
;;; draw/erase symbol
;;; draw
;;;;NOTE the test-fast-draw
(defmacro fast-draw-symbol (canvas sim x y size fill )
`(let ()
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(case ,sim
(:box (fast-draw-box ,canvas ,x ,y ,size ,fill))
(:circle (fast-draw-circle ,canvas ,x ,y ,size ,fill ))
(:cross (fast-draw-cross ,canvas ,x ,y ,size ,fill ))
(:star (fast-draw-star ,canvas ,x ,y ,size ,fill ))
(:diamond (fast-draw-diamond ,canvas ,x ,y ,size ,fill ))
(:triangle (fast-draw-triangle ,canvas ,x ,y ,size ,fill ))
(t NIL))))
;;; erase
(defmacro fast-erase-symbol (canvas sim x y size fill )
`(let ()
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(case ,sim
(:box (fast-erase-box ,canvas ,x ,y ,size ,fill))
(:circle (fast-erase-circle ,canvas ,x ,y ,size ,fill ))
(:cross (fast-erase-cross ,canvas ,x ,y ,size ,fill ))
(:star (fast-erase-star ,canvas ,x ,y ,size ,fill ))
(:diamond (fast-erase-diamond ,canvas ,x ,y ,size ,fill ))
(:triangle (fast-erase-triangle ,canvas ,x ,y ,size ,fill ))
(t NIL))))
;;; mode-draw/erase
;;; since there does not seem to be a mode, just call fast/draw-erase
;;; NOTE the use of test- here
;;; draw
(defmacro mode-draw-symbol (canvas sim x y size fill mode)
(declare (ignore mode))
;(let ((mp (gensym)))
`(let ((mp (get-frame-pane ,canvas 'host-pane)))
#:-sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
;(fast-draw-symbol ,canvas ,sim ,x ,y ,size ,fill)
(fast-draw-symbol ,canvas ,sim ,x ,y ,size ,fill)
)
;)
)
;;; erase
(defmacro mode-erase-symbol (canvas sim x y size fill mode)
(declare (ignore mode))
;(let ((mp (gensym)))
`(let ((mp (get-frame-pane ,canvas 'host-pane)))
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
;(fast-erase-symbol ,canvas ,sim ,x ,y ,size ,fill)
(fast-erase-symbol ,canvas ,sim ,x ,y ,size ,fill)
)
;)
)
;;; cc-set-rgb-color
(defmacro cc-set-rgb-color (canvas color)
;(let ((mp (gensym)))
`(let ((mp (get-frame-pane ,canvas 'host-pane)))
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(when ,color
;(cg::set-foreground-color ,mp ,color) 18oct05
(setf (medium-foreground mp) ,color) ;18oct05
))
;)
)
;;; set-draw-color
;;; UNTESTED BECAUSE I DO NOT HAVE (COLORED-CANVAS-P)
(defmacro set-draw-color (canvas color)
;(let ((mp (gensym)))
`(let ((mp (get-frame-pane ,canvas 'host-pane)))
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(when ,color
(if (colored-canvas-p ,canvas)
(if (colorp ,color)
;(cg::set-foreground-color ,mp ,color) 18oct05
(setf (medium-foreground mp) ,color) ;18oct05
))))
;)
)
;;; bw-set-color
;;; UNTESTED BECUASE I DO NOT HAVE (COLORED-CANVAS-P) NEEDED BY TEST-SET-DRAW-COLOR
;;; Note there is (make-gray-color luminence) where luminence 0 = black, 1 = white
(defmacro bw-set-color (canvas color)
`(let ()
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(when ,color
(set-draw-color ,canvas ,color))))
;;; set-fast-color
;;; UNTESTED AS ABOVE
(defmacro set-fast-color (canvas color)
;(let ((mp (gensym)))
`(let ((mp (get-frame-pane ,canvas 'host-pane)))
(if (colored-canvas-p ,canvas)
;(cg::set-foreground-color ,mp ,color) 18oct05
(setf (medium-foreground mp) ,color) ;18oct05
))
;)
)
;;; fast-move-to
(defmacro fast-move-to (canvas x y)
;(let ((mp (gensym)))
`(let ((mp (get-frame-pane ,canvas 'host-pane)))
(stream-set-cursor-position mp ,x ,y))
;)
)
;;; fast-line-to
(defmacro fast-line-to (canvas x y)
;(let ((mp (gensym))
; (cur-pos (gensym))
; (cur-pos-x (gensym))
; (cur-pos-y (gensym)))
`(let* ((mp (get-frame-pane ,canvas 'host-pane))
(cur-pos (multiple-value-list (stream-cursor-position (get-frame-pane ,canvas 'host-pane))))
(cur-pos-x (first cur-pos))
(cur-pos-y (second cur-pos)))
(medium-draw-line* mp cur-pos-x cur-pos-y ,x ,y)
)
;)
)
;;; fast-erase-to
(defmacro erase-line-to (canvas x y)
;(let ((mp (gensym))
; (mpbg (gensym))
; (cur-pos (gensym))
; (cur-pos-x (gensym))
; (cur-pos-y (gensym)))
`(let* ((mp (get-frame-pane ,canvas 'host-pane))
(cur-pos (multiple-value-list (stream-cursor-position (get-frame-pane ,canvas 'host-pane))))
(cur-pos-x (first cur-pos))
(cur-pos-y (second cur-pos))
(mpbg (medium-background (get-frame-pane ,canvas 'host-pane))))
(with-drawing-options (mp :ink mpbg)
(medium-draw-line* mp cur-pos-x cur-pos-y ,x ,y)
)
)
;)
)
;;; fast-draw-line
(defmacro fast-draw-line (canvas x1 y1 x2 y2 )
;(let ((mp (gensym)))
`(let ((mp (get-frame-pane ,canvas 'host-pane)))
(medium-draw-line* mp ,x1 ,y1 ,x2 ,y2)
)
;)
)
;;; fast-erase-line
(defmacro fast-erase-line (canvas x1 y1 x2 y2 )
;(let ((mp (gensym))
; (mpbg (gensym)))
`(let* ((mp (get-frame-pane ,canvas 'host-pane))
(mpbg (medium-background mp) ))
(with-drawing-options (mp :ink mpbg)
(medium-draw-line* mp ,x1 ,y1 ,x2 ,y2)
)
)
;)
)
;;; mode-draw-line
;;; there is no mode that I can see, so imitate test-fast-draw-line
(defmacro mode-draw-line (canvas x1 y1 x2 y2 mode)
#+:sbcl(declare (ignore mode))
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
;(let ((mp (gensym)))
;`(let ((mp (get-frame-pane ,canvas 'host-pane)))
`(fast-draw-line ,canvas
(the fixnum ,x1)
(the fixnum ,y1)
(the fixnum ,x2)
(the fixnum ,y2))
;)
;)
)
;;; mode-erase-line
(defmacro mode-erase-line (canvas x1 y1 x2 y2 mode)
#+:sbcl(declare (ignore mode))
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
;(let ((mp (gensym)))
;`(let ((mp (get-frame-pane ,canvas 'host-pane)))
`(fast-erase-line ,canvas
(the fixnum ,x1)
(the fixnum ,y1)
(the fixnum ,x2)
(the fixnum ,y2))
;)
;)
)
;;; DONE | 24,350 | Common Lisp | .l | 614 | 30.65798 | 146 | 0.482776 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 3fccbb9c5e2f116b2fc2f1cd1337edc0b113ffdd670afbfe6a63a3771e89156c | 33,690 | [
-1
] |
33,692 | points-sblx.lsp | rwoldford_Quail/source/window-basics/fast-graphics/points-sblx.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; points-sblx.lsp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;; This file is an addition to Window-basics for moving pointclouds
;;;
;;; Authors:
;;; H.A. Chipman 1991
;;; C.B. Hurley 1991 George Washington University
;;; G.W. Bennett 1996
;;;
;;;
;;;----------------------------------------------------------------------------------
(in-package :wb)
(defun xor-draw-points (canvas points &key erase? &allow-other-keys)
"Draws or erases single pixel points ~
Results with color background are undefined."
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (ignore erase? ))
(let ((mp (get-frame-pane canvas 'host-pane)))
(loop
for (x y) fixnum in points
do
;(format t "~%x and y are ~d ~d " x y)
(medium-draw-point* mp x y)
)
))
;;;
(defun xor-move-points (canvas old new &key none &allow-other-keys )
"Moves single pixel points.~
Results with color background are undefined."
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (ignore none))
(let* ((mp (get-frame-pane canvas 'host-pane))
(mpbg (medium-background (get-frame-pane canvas 'host-pane))))
(loop
for (xo yo ) fixnum in old
for (x y ) fixnum in new
do
(with-drawing-options (mp :ink mpbg)
(medium-draw-point* mp xo yo))
(medium-draw-point* mp x y))
)
)
;;;
(defun xor-draw-boxes (canvas points &key size erase?
&allow-other-keys)
"Draws or erases filled squares with varying size.~
Results with color background are undefined."
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (ignore erase? ))
(let* ((mp (get-frame-pane canvas 'host-pane)))
(loop
for (x y ) fixnum in points for s fixnum in size
do
(medium-draw-rectangle* mp x y (+ x s) (+ y s) T)
)
))
;;;
(defun xor-move-boxes (canvas old new &key size (old-size size)
&allow-other-keys)
"Moves filled squares with varying size.~
Results with color background are undefined."
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(let* ((mp (get-frame-pane canvas 'host-pane))
(mpbg (medium-background (get-frame-pane canvas 'host-pane))))
(loop for (xo yo ) fixnum in old
for (x y ) fixnum in new
for so fixnum in old-size
for s fixnum in size
do
(with-drawing-options (mp :ink mpbg)
(medium-draw-rectangle* mp xo yo (+ xo so 1) (+ yo so 1) T)
)
(medium-draw-rectangle* mp x y (+ x s ) (+ y s) T)
)))
;;;
(defun xor-draw-circles (canvas points &key size erase?
&allow-other-keys)
"Draws or erases filled circles with varying size.~
Results with color background are undefined."
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (ignore erase? ))
;(let ((mp (get-frame-pane canvas 'host-pane)))
(loop
for (x y) fixnum in points for s fixnum in size
do
(fast-draw-circle canvas x y s T)
)
; )
)
;;;
(defun xor-move-circles (canvas old new &key size (old-size size)
&allow-other-keys)
"Moves filled circles with varying size.~
Results with color background are undefined."
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(let* ((mp (get-frame-pane canvas 'host-pane))
(mpbg (medium-background (get-frame-pane canvas 'host-pane))))
(loop for (xo yo ) fixnum in old
for (x y ) fixnum in new
for so fixnum in old-size
for s fixnum in size
do
(with-drawing-options (mp :ink mpbg)
(fast-erase-circle canvas xo yo so T)
)
(fast-draw-circle canvas x y s T)
))
)
;;; DONE | 4,438 | Common Lisp | .l | 126 | 28.388889 | 85 | 0.542102 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 7b4630592c388f2b1cf940177aabed0ec350694342b93172df9c2187c975d067 | 33,692 | [
-1
] |
33,693 | lines-pc.lsp | rwoldford_Quail/source/window-basics/fast-graphics/lines-pc.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; lines-pc.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;; This file is an addition to Window-basics for moving pointclouds
;;;
;;; Authors:
;;; H.A. Chipman 1991
;;; C.B. Hurley 1991 George Washington University
;;; R.W. Oldford 1992
;;; G.W. Bennett 1996
;;;
;;;
;;;--------------------------------------------------------------------
(in-package :wb)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(canvas-draw-lines canvas-erase-lines canvas-move-lines)))
;; coords are lists with even length (s1 e1 s2 e2...) where s1 and e1 are the start
;; and end of the first line
(defun draw-fw-lines (canvas coords &key (width 1)
(invisible? (list nil nil nil))
color
erase? &allow-other-keys)
"Draws or erases colored fixed width lines"
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(type fixnum width)
(special cg::po-paint cg::po-replace cg::po-invert cg::po-erase))
(let ((mp (cg::frame-child canvas)))
(with-focused-canvas canvas
;; (choose-mode canvas :erase? erase?)
;(cg::set-line-width mp width) 18oct05
(setf (cg::line-width mp) width) ;180ct05
(cg::with-foreground-color (mp color)
(loop with h = (canvas-height canvas)
for (xs ys) fixnum in coords by #'cddr
for (xe ye) fixnum in (cdr coords) by #'cddr
for i in invisible?
unless i
do
(if erase?
(fast-erase-line canvas xs ( - h ys) xe (- h ye))
(fast-draw-line canvas xs (- h ys) xe (- h ye)))
))
)))
(defun xor-move-fw-lines (canvas old-coords new-coords
&key (width 1) color &allow-other-keys )
"Moves colored fixed width lines~
Results with color background are undefined"
(declare (special *host-xor-mode* cg::po-paint cg::po-replace cg::po-invert cg::po-erase)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(type fixnum width))
(let ((mp (cg::frame-child canvas)))
(with-focused-canvas canvas
(h-draw::set-pen-mode canvas *host-xor-mode*)
;(cg::set-line-width mp width) 18oct05
(setf (cg::line-width mp) width) ;18oct05
(cg::with-foreground-color (mp color)
(loop with h = (canvas-height canvas)
for (sx1 sy1 ) fixnum in old-coords by #'cddr
for (ex1 ey1 ) fixnum in (cdr old-coords) by #'cddr
for (sx2 sy2 ) fixnum in new-coords by #'cddr
for (ex2 ey2 ) fixnum in (cdr new-coords) by #'cddr
do
(cg::with-paint-operation
;(mp cg::erase) ;; Need this to avoid 19oct05
(mp cg::po-erase) ;19oct05
;; BLACK original lines
(fast-draw-line canvas sx1 (- h sy1) ex1 (- h ey1)))
(fast-draw-line canvas sx2 (- h sy2) ex2 (- h ey2))))
)
))
(defun move-fw-lines (canvas old-coords new-coords
&key (width 1) color &allow-other-keys )
"Moves colored fixed width lines"
(declare (special *host-or-mode* *host-bic-mode*
cg::po-paint cg::po-replace cg::po-invert cg::po-erase)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(type fixnum width))
;; (set-draw-color canvas color)
(let ((mp (cg::frame-child canvas)))
(with-focused-canvas canvas
;(cg::set-line-width mp width) 18oct05
(setf (cg::line-width mp) width) ;18oct05
(cg::with-foreground-color (mp color)
(loop with h = (canvas-height canvas)
for (sx1 sy1 ) fixnum in old-coords by #'cddr
for (ex1 ey1 ) fixnum in (cdr old-coords) by #'cddr
for (sx2 sy2 ) fixnum in new-coords by #'cddr
for (ex2 ey2 ) fixnum in (cdr new-coords) by #'cddr
do
(cg::with-paint-operation
;(mp cg::erase) 19oct05
(mp cg::po-erase) ;19oct05
(mode-erase-line canvas sx1 (- h sy1) ex1 (- h ey1) *host-bic-mode*))
(mode-draw-line canvas sx2 (- h sy2) ex2 (- h ey2) *host-or-mode*)))
)
))
(defun draw-multi-color-lines (canvas coords &key (width 1) color invisible?
erase? &allow-other-keys)
"Draws or erases lines with varying color."
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(type fixnum width)
(special cg::po-paint cg::po-replace cg::po-invert cg::po-erase)
(ignore invisible?)) ; 28JUL2023
(with-focused-canvas canvas
(let ((mp (cg::frame-child canvas)))
;(cg::set-line-width mp width) 18oct05
(setf (cg::line-width mp) width) ;18oct05
;; (choose-mode canvas :erase? erase?)
(loop with h = (canvas-height canvas)
for (xs ys ) fixnum in coords by #'cddr
for (xe ye ) fixnum in (cdr coords) by #'cddr
for c in color
do
(cg::with-paint-operation
;(mp cg::replace) 19oct05
(mp cg::po-replace) ;19oct05
(cg::with-foreground-color (mp c)
(if erase?
(fast-erase-line canvas xs (- h ys) xe (- h ye))
(fast-draw-line canvas xs (- h ys) xe (- h ye)))
))
)))
)
(defun xor-move-multi-color-lines (canvas old-coords new-coords
&key (width 1) color
invisible? &allow-other-keys )
"Moves lines with varying color. ~
Results with color background are undefined."
(declare (special *host-xor-mode* cg::po-paint cg::po-replace cg::po-invert cg::po-erase)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(type fixnum width)
(ignore invisible?)) ; 28JUL2023
(with-focused-canvas canvas
(let ((mp (cg::frame-child canvas)))
(h-draw::set-pen-mode canvas *host-xor-mode*)
;(cg::set-line-width mp width) 18oct05
(setf (cg::line-width mp) width) ;18oct05
(loop with h = (canvas-height canvas)
for (sx1 sy1 ) fixnum in old-coords by #'cddr
for (ex1 ey1 ) fixnum in (cdr old-coords) by #'cddr
for (sx2 sy2 ) fixnum in new-coords by #'cddr
for (ex2 ey2 ) fixnum in (cdr new-coords) by #'cddr
for c in color
do
(cg::with-paint-operation
;(mp cg::erase) ;; Need this to avoid 19oct05
(mp cg::po-erase) ;19oct05
;; BLACK original lines
(fast-erase-line canvas sx1 (- h sy1) ex1 (- h ey1)))
(cg::with-foreground-color (canvas c)
(fast-draw-line canvas sx2 (- h sy2) ex2 (- h ey2)))
))
))
(defun move-multi-color-lines (canvas old-coords new-coords
&key (width 1)
color rgb-color? &allow-other-keys )
"Moves lines with varying color."
(declare (special *black-color* *host-or-mode* *host-bic-mode*
cg::po-paint cg::po-replace cg::po-invert cg::po-erase)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(type fixnum width))
(with-focused-canvas canvas
(let ((mp (cg::frame-child canvas)))
;(cg::set-line-width mp width) 18oct05
(setf (cg::line-width mp) width) ;18oct05
(loop with h = (canvas-height canvas)
for (sx1 sy1 ) fixnum in old-coords by #'cddr
for (ex1 ey1 ) fixnum in (cdr old-coords) by #'cddr
for (sx2 sy2 ) fixnum in new-coords by #'cddr
for (ex2 ey2 ) fixnum in (cdr new-coords) by #'cddr
for c in color
do
(if rgb-color?
(cc-set-rgb-color canvas c)
(cg::with-foreground-color (mp c)
(cg::with-paint-operation
;(mp cg::erase) 19oct05
(mp cg::po-erase) ;19oct05
(mode-erase-line canvas sx1 (- h sy1) ex1 (- h ey1) *host-bic-mode*))
(mode-draw-line canvas sx2 (- h sy2) ex2 (- h ey2) *host-or-mode*))
)))
))
(defun draw-multi-color-&-width-lines (canvas coords &key width color
invisible? erase? &allow-other-keys)
"Draws or erases lines with varying color and width."
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(ignore invisible?) ;;02OCT2023 as unused
(type fixnum width)
(special cg::po-paint cg::po-replace cg::po-invert cg::po-erase))
(with-focused-canvas canvas
(let ((mp (cg::frame-child canvas)))
;; (choose-mode canvas :erase? erase?)
(loop with h = (canvas-height canvas)
for (xs ys ) fixnum in coords by #'cddr
for (xe ye ) fixnum in (cdr coords) by #'cddr
for w in width for c in color
do
(cg::with-foreground-color (mp c)
;(cg::set-line-width mp w) 18oct05
(setf (cg::line-width mp) w) ;18oct05
(if erase?
(fast-erase-line canvas xs (- h ys) xe (- h ye))
(fast-draw-line canvas xs (- h ys) xe (- h ye))))))
))
(defun xor-move-multi-color-&-width-lines (canvas old-coords new-coords
&key width color &allow-other-keys )
"Moves lines with varying color and width~
Results with color background are undefined."
(declare (special *host-xor-mode* cg::po-paint cg::po-replace cg::po-invert cg::po-erase)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(type fixnum width))
(with-focused-canvas canvas
(let ((mp (cg::frame-child canvas)))
(h-draw::set-pen-mode canvas *host-xor-mode*)
(loop with h = (canvas-height canvas)
for (sx1 sy1 ) fixnum in old-coords by #'cddr
for (ex1 ey1 ) fixnum in (cdr old-coords) by #'cddr
for (sx2 sy2 ) fixnum in new-coords by #'cddr
for (ex2 ey2 ) fixnum in (cdr new-coords) by #'cddr
for w in width for c in color
do
;(cg::set-line-width mp w) 18oct05
(setf (cg::line-width mp) w) ;18oct05
(cg::with-paint-operation
;(mp cg::erase) 19oct05
(mp cg::po-erase) ;19oct05
(fast-erase-line canvas sx1 (- h sy1) ex1 (- h ey1)))
(cg::with-foreground-color (mp c)
(fast-draw-line canvas sx2 (- h sy2) ex2 (- h ey2)))
))
))
(defun move-multi-color-&-width-lines
(canvas old-coords new-coords &key width color rgb-color? &allow-other-keys )
"Moves lines with varying color and width"
(declare (special *black-color* *host-or-mode* *host-bic-mode*
cg::po-paint cg::po-replace cg::po-invert cg::po-erase)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(type fixnum width))
(with-focused-canvas canvas
(let ((mp (cg::frame-child canvas)))
(loop with h = (canvas-height canvas)
for (sx1 sy1 ) fixnum in old-coords by #'cddr
for (ex1 ey1 ) fixnum in (cdr old-coords) by #'cddr
for (sx2 sy2 ) fixnum in new-coords by #'cddr
for (ex2 ey2 ) fixnum in (cdr new-coords) by #'cddr
for w in width for c in color
do
; (format t "~%[1] width is ~a " w)
(if rgb-color?
(cc-set-rgb-color mp c)
(cg::with-foreground-color (mp c)
(cg::with-paint-operation
;(mp cg::erase) 19oct05
(mp cg::po-erase) ;19oct05
;(cg::set-line-width canvas w) 18oct05
(setf (cg::line-width canvas) w) ;18oct05
(mode-erase-line canvas sx1 (- h sy1) ex1 (- h ey1) *host-bic-mode*)
)
(mode-draw-line canvas sx2 (- h sy2) ex2 (- h ey2) *host-or-mode*)
)
)
))
))
(defun canvas-draw-lines (canvas coords
&key (width 1) (erase? nil)
color
invisible?
&allow-other-keys )
"Draws or erases lines "
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(type fixnum width)
(special cg::po-paint cg::po-replace cg::po-invert cg::po-erase))
(if (and color (listp color))
(if (and width (listp width))
(draw-multi-color-&-width-lines canvas coords :width width :color color :erase? erase?
:invisible? invisible?)
(draw-multi-color-lines canvas coords :width width :color color :erase? erase?
:invisible? invisible?))
(draw-fw-lines canvas coords
:width (if (listp width ) (car width))
:color (if (listp color ) (car color))
:erase? erase?
:invisible invisible?)
))
;;; Not done as of May 11, 1996 - see NOTES at the top of this file
(defun canvas-erase-lines (canvas coords
&key (width 1)
color
&allow-other-keys )
"Erases lines "
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(type fixnum width)
(inline canvas-draw-lines)
(special cg::po-paint cg::po-replace cg::po-invert cg::po-erase))
(canvas-draw-lines canvas coords :width width :color color :erase? t))
(defun canvas-move-lines (canvas old-coords new-coords
&key (width 1) (rgb-color? nil)
color
&allow-other-keys )
"Moves lines "
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(type fixnum width)
(special cg::po-paint cg::po-replace cg::po-invert cg::po-erase))
(if (and color (listp color))
(if (and width (listp width))
(move-multi-color-&-width-lines canvas old-coords new-coords
:width width
:color (if (and (colored-canvas-p canvas) (not rgb-color? ))
(rgb-colors color)
color))
(move-multi-color-lines canvas old-coords new-coords
:width width
:color (if (and (colored-canvas-p canvas) (not rgb-color? ))
(rgb-colors color)
color)))
(move-fw-lines canvas old-coords new-coords
:width (if (listp width ) (car width))
:color (if (listp color ) (car color)))
)
)
(defun canvas-draw-axes (canvas axes
&key (width 1) (erase? nil)
color)
"Draws or erases axes"
(declare (special *host-or-mode* *host-bic-mode*
cg::po-paint cg::po-replace cg::po-invert cg::po-erase)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(type fixnum width))
(when axes
(with-focused-canvas canvas
(let ((mp (cg::frame-child canvas)))
(cg::with-foreground-color (mp color)
;(cg::set-line-width mp width) 18oct05
(setf (cg::line-width mp) width) ;18oct05
(if erase?
(draw-fw-lines canvas axes :width width :erase? t)
(draw-fw-lines canvas axes :width width ))
)))
))
(defun canvas-erase-axes (canvas axes
&key (width 1)
color)
"Erases axes "
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(type fixnum width)
(inline canvas-draw-axes)
(special cg::po-paint cg::po-replace cg::po-invert cg::po-erase))
(canvas-draw-axes canvas axes :width width :color color :erase? t))
(defun canvas-move-axes (canvas old-axes new-axes
&key (width 1)
color
&allow-other-keys )
"Moves axes "
(declare (special *host-or-mode* *host-bic-mode*
cg::po-paint cg::po-replace cg::po-invert cg::po-erase)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(type fixnum width))
(when old-axes
(with-focused-canvas canvas
(let ((mp (cg::frame-child canvas)))
;(cg::set-line-width mp width) 18oct05
(setf (cg:line-width mp) width) ;18oct05
(cg::with-foreground-color (mp color)
(loop with h = (canvas-height canvas)
with xo = (caar new-axes)
with yo = (- h (cadar new-axes))
for (x-old y-old) fixnum in (cdr old-axes)
for (x y) fixnum in (cdr new-axes)
do
(mode-erase-line canvas xo yo x-old (- h y-old) *host-bic-mode*)
(mode-draw-line canvas xo yo x (- h y) *host-or-mode*)
))))
))
| 18,233 | Common Lisp | .l | 390 | 33.528205 | 124 | 0.514777 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 13832e63b14957235da76ef034ae7428ba7f70244c37399fb99f58036bfc22da | 33,693 | [
-1
] |
33,694 | symbols-sblx.lsp | rwoldford_Quail/source/window-basics/fast-graphics/symbols-sblx.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; symbols-sblx.lsp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;; This file is an addition to Window-basics for moving pointclouds
;;;
;;; Authors:
;;; H.A. Chipman 1991
;;; C.B. Hurley 1991 George Washington University
;;; N.G. Bennett 1993
;;; G.W. Bennett 1996
;;;
;;;
;;;----------------------------------------------------------------------------------
(in-package :wb)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(canvas-draw-symbol canvas-draw-symbols
canvas-erase-symbols canvas-move-symbols)))
(defun rgb-colors (colors &optional default)
;;(if default (setq default (get-rgb-color default))) it's an rgb anyway in ACL
(if *color-available*
(loop for c in colors collect (or (and c c)
default))))
#|
(defun rgb-colors (colors)
colors
(if *color-available*
(loop for c in colors
collect (if c
(get-rgb-color c))))
(defun choose-mode (canvas &key (erase? nil))
(declare
(special *host-or-mode* *host-bic-mode*
cg::po-erase cg::po-invert cg::po-replace cg::po-paint)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(if erase? (h-draw::set-pen-mode canvas *host-bic-mode*)
(h-draw::set-pen-mode canvas *host-or-mode*)))
|#
(defun draw-single-color-symbols
(canvas points
&key size symbol fill? color (erase? nil) invisible?
&allow-other-keys)
"Draws or erases colored symbols with varying size, symbol fill? invisible?."
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(let ((mp (get-frame-pane canvas 'host-pane)))
(loop
for (x y) fixnum in points
for sim in symbol
for fill in fill?
for s fixnum in size
for i in invisible?
unless i
do
(with-drawing-options (mp :ink color)
(if erase?
(fast-erase-symbol canvas sim x y s fill)
(fast-draw-symbol canvas sim x y s fill)
)
)
)
))
(defun xor-move-single-color-symbols
(canvas old new
&key size (old-size size) fill? (old-fill? fill?)
symbol (old-symbol symbol) color invisible?
&allow-other-keys)
"Moves colored (shaded) symbols with varying size, symbol fill? invisible?.~
Results with color background are undefined."
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(set-pen-color canvas color)
;(let ((mp (get-frame-pane canvas 'host-pane)))
(loop
for (xo yo ) fixnum in old
for (x y ) fixnum in new
for sim in symbol for simo in old-symbol
for fill in fill? for fillo in old-fill?
for s fixnum in size for so fixnum in old-size
for i in invisible?
unless i
do
(fast-erase-symbol canvas simo xo yo so fillo)
(fast-draw-symbol canvas sim x y s fill)
)
;)
)
;;; since clim has no dra3wing modes, move-single-color-symbols is just a call to xor-move-single-color-symbols
(defun move-single-color-symbols
(canvas old new
&key size (old-size size) fill? (old-fill? fill?)
symbol (old-symbol symbol) color invisible?
&allow-other-keys)
"Moves colored symbols with varying size, symbol fill? invisible?."
(xor-move-single-color-symbols canvas old new :size size :old-size old-size
:fill? fill? :old-fill? old-fill? :symbol symbol :old-symbol old-symbol
:color color :invisible? invisible?)
)
;;;
(defun draw-multi-color-symbols
(canvas points
&key size symbol erase? fill? color invisible?
&allow-other-keys)
"Draws or erases symbols with varying size, symbol fill? color invisible?."
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(let ((mp (get-frame-pane canvas 'host-pane)))
(loop
for (x y ) fixnum in points
for sim in symbol
for erase in erase?
for fill in fill?
for s fixnum in size
for c in color
for i in invisible?
unless i
do
(if erase
(fast-erase-symbol canvas sim x y s fill)
(with-drawing-options (mp :ink c)
(fast-draw-symbol canvas sim x y s fill)))
)
))
;;;
(defun xor-move-multi-color-symbols
(canvas old new
&key size (old-size size) fill? (old-fill? fill?)
invisible?
symbol (old-symbol symbol) color &allow-other-keys)
"Moves symbols with varying size, symbol fill? color invisible?.~
Results with color background are undefined."
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(let ((mp (get-frame-pane canvas 'host-pane)))
(loop
for (xo yo ) fixnum in old
for (x y ) fixnum in new
for sim in symbol for simo in old-symbol
for fill in fill? for fillo in old-fill?
for s fixnum in size for so fixnum in old-size
for c in color
for i in invisible?
unless i do
(fast-erase-symbol canvas simo xo yo so fillo)
(with-drawing-options (mp :ink c)
(fast-draw-symbol canvas sim x y s fill ))
)
))
;;;
;;; since clim does not have drawing modes, the following could be just a call to (test-)xor-move-multi-color-symbols
;;; were it not for :rgb-color?
;;; I cannot find cc-set-rgb-color or set-draw-color in source/**/*.lsp !!
(defun move-multi-color-symbols
(canvas old new
&key size (old-size size) fill? (old-fill? fill?) invisible?
symbol (old-symbol symbol) color rgb-color?
&allow-other-keys)
"Moves symbols with varying size, symbol fill? color invisible?."
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (ignorable rgb-color?)) ;09MAY2024
(let ((mp (get-frame-pane canvas 'host-pane)))
(loop
for (xo yo ) fixnum in old
for (x y ) fixnum in new
for sim in symbol for simo in old-symbol
for fill in fill? for fillo in old-fill?
for s fixnum in size for so fixnum in old-size
for c in color
for i in invisible?
unless i do
;(if rgb-color?
;(cc-set-rgb-color canvas c)
;(set-draw-color canvas c)) ;;; is all we are doing is setting (medium-foreground pane-of-canvas) to be c ?
; )
(fast-erase-symbol canvas simo xo yo so fillo)
(with-drawing-options (mp :ink c) ;;; if so, that's what happens here .. so I could (declare (ignore rgb-color?)) at the outset
(fast-draw-symbol canvas sim x y s fill ))
)
))
;;;
(defun canvas-draw-symbols (canvas points &key size symbol color fill?
invisible? (erase? nil) single-color?
&allow-other-keys)
"Draws or erases symbols with varying size, symbol fill? color invisible?."
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
;(let ((mp (get-frame-pane canvas 'host-pane)))
(if (or erase? single-color?)
(draw-single-color-symbols canvas points
:size size :symbol symbol
:color (car color)
:fill? fill?
:invisible? invisible?
:erase? erase?)
(draw-multi-color-symbols canvas points
:size size :symbol symbol
:color color
:fill? fill?
:invisible? invisible?
:erase? (coerce (make-array (length points) :initial-element erase?) 'list))
)
;)
)
;;;
(defun canvas-erase-symbols (canvas points
&key size symbol color fill? invisible? single-color?
&allow-other-keys)
"Erases symbols with varying size symbol fill? color invisible? and flag ~
single-color? identifying whether they are all of one colour or not."
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(canvas-draw-symbols canvas points :size size :symbol symbol
:color color :fill? fill? :invisible? invisible?
:single-color? single-color?
:erase? t))
;;;
(defun canvas-move-symbols (canvas old-points new-points
&key size symbol color fill? invisible?
(old-size size)
(old-symbol symbol)
old-color
rgb-color? single-color?
(old-fill? fill?)
&allow-other-keys)
"Moves symbols with varying size, symbol fill? color invisible?."
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(declare (ignore old-color))
(if single-color?
(move-single-color-symbols canvas old-points new-points
:size size :symbol symbol :fill? fill?
:old-size old-size :old-symbol old-symbol
:invisible? invisible?
:old-fill? old-fill? :color (first color))
(move-multi-color-symbols canvas old-points new-points
:size size :symbol symbol :fill? fill?
:old-size old-size :old-symbol old-symbol
:old-fill? old-fill?
:invisible? invisible?
:rgb-color? t
:color color
)
)
)
;;;
(defun canvas-draw-symbol
(canvas x y
&key size symbol fill? color erase?
&allow-other-keys)
"Draw/erase symbol using size symbol fill? color and erase?"
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(let* ((mp (get-frame-pane canvas 'host-pane))
(mpbg (medium-background (get-frame-pane canvas 'host-pane))))
;(if (colored-canvas-p canvas)
; (setq color color))
;(choose-mode canvas :erase? erase?)
;(set-draw-color canvas color)
(if erase?
(with-drawing-options (mp :ink mpbg)
(fast-erase-symbol canvas symbol x y size fill?))
(with-drawing-options (mp :ink color)
(fast-draw-symbol canvas symbol x y size fill?))
)
))
| 10,921 | Common Lisp | .l | 277 | 30.397112 | 135 | 0.565332 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 53660f813600a7d4e20229214a2b8ef561f189e783c0586726c0a86d7aa604a1 | 33,694 | [
-1
] |
33,696 | symbols-pc.lsp | rwoldford_Quail/source/window-basics/fast-graphics/symbols-pc.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; symbols-pc.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;; This file is an addition to Window-basics for moving pointclouds
;;;
;;; Authors:
;;; H.A. Chipman 1991
;;; C.B. Hurley 1991 George Washington University
;;; N.G. Bennett 1993
;;; G.W. Bennett 1996
;;;
;;;
;;;----------------------------------------------------------------------------------
(in-package :wb)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(canvas-draw-symbol canvas-draw-symbols
canvas-erase-symbols canvas-move-symbols)))
(defun rgb-colors (colors &optional default)
;;(if default (setq default (get-rgb-color default))) it's an rgb anyway in ACL
(if *color-available*
(loop for c in colors collect (or (and c c)
default))))
#|
(defun rgb-colors (colors)
colors
#|
(if *color-available*
(loop for c in colors
collect (if c
(get-rgb-color c))))
|#
)
|#
(defun choose-mode (canvas &key (erase? nil))
(declare
(special *host-or-mode* *host-bic-mode*
cg::po-erase cg::po-invert cg::po-replace cg::po-paint)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(if erase? (h-draw::set-pen-mode canvas *host-bic-mode*)
(h-draw::set-pen-mode canvas *host-or-mode*)))
(defun draw-single-color-symbols
(canvas points
&key size symbol fill? color (erase? nil) invisible?
&allow-other-keys)
"Draws or erases colored symbols with varying size, symbol fill? invisible?."
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
(let ((mp (cg::frame-child canvas)))
(with-focused-canvas canvas
(choose-mode canvas :erase? erase?)
;(set-draw-color canvas color)
(loop with h = (canvas-height canvas)
for (x y ) fixnum in points
for sim in symbol
for fill in fill?
for s fixnum in size
for i in invisible?
unless i
do
(if erase?
(fast-erase-symbol canvas sim x (- h y) s fill)
(cg::with-paint-operation
;(mp cg::replace) 19oct05
(mp cg::po-replace) ;19oct05
(cg::with-foreground-color (mp color)
(fast-draw-symbol canvas sim x (- h y) s fill))
)
))
)))
#|
(defun xor-move-single-color-symbols
(canvas old new
&key size (old-size size) fill? (old-fill? fill?)
symbol (old-symbol symbol) color invisible?
&allow-other-keys)
"Moves colored (shaded) symbols with varying size, symbol fill? invisible?.~
Results with color background are undefined."
(declare (special *host-xor-mode*
cg::po-erase cg::po-invert cg::po-replace cg::po-paint)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(set-pen-color canvas color)
(let ((mp (cg::frame-child canvas)))
(with-focused-canvas canvas
;; (h-draw::set-pen-mode canvas *host-xor-mode*)
(loop with h = (canvas-height canvas)
for (xo yo ) fixnum in old
for (x y ) fixnum in new
for sim in symbol for simo in old-symbol
for fill in fill? for fillo in old-fill?
for s fixnum in size for so fixnum in old-size
for i in invisible?
unless i
do
(fast-erase-symbol canvas simo xo (- h yo) so fillo)
(cg::with-foreground-color (mp color)
;; (fast-draw-symbol canvas simo xo (- h yo) so fillo)
(fast-draw-symbol canvas sim x (- h y) s fill)
)
))))
|#
(defun move-single-color-symbols
(canvas old new
&key size (old-size size) fill? (old-fill? fill?)
symbol (old-symbol symbol) color invisible?
&allow-other-keys)
"Moves colored symbols with varying size, symbol fill? invisible?."
(declare (special *host-or-mode* *host-bic-mode*
cg::po-erase cg::po-invert cg::po-replace cg::po-paint)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(let ((mp (cg::frame-child canvas)))
(with-focused-canvas canvas
(set-draw-color canvas color)
(loop with h = (canvas-height canvas)
for (xo yo ) fixnum in old
for (x y ) fixnum in new
for sim in symbol for simo in old-symbol
for fill in fill? for fillo in old-fill?
for s fixnum in size for so fixnum in old-size
for i in invisible?
unless i
do
(cg::with-foreground-color (mp color)
(mode-erase-symbol canvas
simo xo (- h yo) so fillo *host-bic-mode*)
(mode-draw-symbol canvas
sim x (- h y) s fill *host-or-mode*))
))))
(defun draw-multi-color-symbols
(canvas points
&key size symbol erase? fill? color invisible?
&allow-other-keys)
"Draws or erases symbols with varying size, symbol fill? color invisible?."
(declare (special *host-or-mode*
cg::po-erase cg::po-invert cg::po-replace cg::po-paint)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(let ((mp (cg::frame-child canvas)))
(with-focused-canvas canvas
;; (xlib::set-gcontext-function (gcontext canvas) *host-or-mode*)
(loop with h = (canvas-height canvas)
for (x y ) fixnum in points
for sim in symbol
for erase in erase?
for fill in fill?
for s fixnum in size
for c in color
for i in invisible?
unless i
do
;(set-draw-color canvas c)
(cg::with-foreground-color (mp c)
(if erase?
(fast-erase-symbol canvas sim x (- h y) s fill)
(cg::with-paint-operation
;(mp cg::replace) 19oct05
(mp cg::po-replace) ;19oct05
(cg::with-foreground-color (mp c)
(fast-draw-symbol canvas sim x (- h y) s fill)))))
))))
#|
(defun xor-move-multi-color-symbols
(canvas old new
&key size (old-size size) fill? (old-fill? fill?)
invisible?
symbol (old-symbol symbol) color &allow-other-keys)
"Moves symbols with varying size, symbol fill? color invisible?.~
Results with color background are undefined."
;; move symbols with varying
;; size, symbol fill?, color (shade), invisible?
;; results with color background are undefined
(declare (special *host-xor-mode* cg::po-erase cg::po-invert cg::po-replace cg::po-paint)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(let ((mp (cg::frame-child canvas)))
(with-focused-canvas canvas
;; (xlib::set-gcontext-function (gcontext canvas) *host-xor-mode*)
(loop with h = (canvas-height canvas)
for (xo yo ) fixnum in old
for (x y ) fixnum in new
for sim in symbol for simo in old-symbol
for fill in fill? for fillo in old-fill?
for s fixnum in size for so fixnum in old-size
for c in color
for i in invisible?
unless i do
(set-draw-color canvas c)
(fast-erase-symbol canvas simo xo (- h yo) so fillo )
(cg::with-foreground-color (mp c)
(fast-draw-symbol canvas sim x (- h y) s fill )))
)))
|#
(defun move-multi-color-symbols
(canvas old new
&key size (old-size size) fill? (old-fill? fill?) invisible?
symbol (old-symbol symbol) color rgb-color?
&allow-other-keys)
"Moves symbols with varying size, symbol fill? color invisible?."
(declare (special *host-or-mode* *host-bic-mode*
cg::po-erase cg::po-invert cg::po-replace cg::po-paint)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(let ((mp (cg::frame-child canvas)))
(with-focused-canvas canvas
(loop with h = (canvas-height canvas)
for (xo yo ) fixnum in old
for (x y ) fixnum in new
for sim in symbol for simo in old-symbol
for fill in fill? for fillo in old-fill?
for s fixnum in size for so fixnum in old-size
for c in color
for i in invisible?
unless i do
(if rgb-color?
(cc-set-rgb-color canvas c)
(set-draw-color canvas c))
(mode-erase-symbol canvas simo xo (- h yo) so fillo *host-bic-mode* )
(cg::with-foreground-color (mp c)
(mode-draw-symbol canvas sim x (- h y) s fill *host-or-mode* ))
))))
(defun canvas-draw-symbols (canvas points &key size symbol color fill?
invisible? (erase? nil) single-color?
&allow-other-keys)
"Draws or erases symbols with varying size, symbol fill? color invisible?."
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-invert cg::po-replace cg::po-paint)
)
(if (or erase? single-color?)
(draw-single-color-symbols canvas points
:size size :symbol symbol
:color (car color)
:fill? fill?
:invisible? invisible?
:erase? erase?)
(draw-multi-color-symbols canvas points
:size size :symbol symbol
:color color
:fill? fill?
:invisible? invisible?
:erase? (coerce (make-array (length points) :initial-element erase?) 'list))
))
(defun canvas-erase-symbols (canvas points
&key size symbol color fill? invisible? single-color?
&allow-other-keys)
"Erases symbols with varying size symbol fill? color invisible? and flag ~
single-color? identifying whether they are all of one colour or not."
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-invert cg::po-replace cg::po-paint)
)
(canvas-draw-symbols canvas points :size size :symbol symbol
:color color :fill? fill? :invisible? invisible?
:single-color? single-color?
:erase? t))
(defun canvas-move-symbols (canvas old-points new-points
&key size symbol color fill? invisible?
(old-size size)
(old-symbol symbol)
old-color
rgb-color? single-color?
(old-fill? fill?)
&allow-other-keys)
"Moves symbols with varying size, symbol fill? color invisible?."
(declare (ignore old-color rgb-color?) ;;02OCT2023 added rgb-color? as unused
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-invert cg::po-replace cg::po-paint)
)
(if single-color?
(move-single-color-symbols canvas old-points new-points
:size size :symbol symbol :fill? fill?
:old-size old-size :old-symbol old-symbol
:invisible? invisible?
:old-fill? old-fill? :color (car color ))
(move-multi-color-symbols canvas old-points new-points
:size size :symbol symbol :fill? fill?
:old-size old-size :old-symbol old-symbol
:old-fill? old-fill?
:invisible? invisible?
:rgb-color? t
:color color
))
)
#|
(defun canvas-draw-symbol
(canvas x y
&key size symbol fill? color erase?
&allow-other-keys)
"Draw/erase symbol using size symbol fill? color and erase?"
(declare (special *host-or-mode*
cg::po-erase cg::po-invert cg::po-replace cg::po-paint)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(let ((mp (cg::frame-child canvas)))
(with-focused-canvas canvas
(if (colored-canvas-p canvas)
(setq color color))
(choose-mode canvas :erase? erase?)
(set-draw-color canvas color)
(if erase?
(cg::with-paint-operation
;(mp cg::erase) 19oct05
(mp cg::po-erase) ;19oct05
(fast-erase-symbol canvas symbol x (- (canvas-height canvas) y)
size fill?))
(cg::with-paint-operation
;(mp cg::replace) 19oct05
(mp cg::po-replace) ;19oct05
(cg::with-foreground-color (mp color)
(fast-draw-symbol canvas symbol x (- (canvas-height canvas) y)
size fill?)))
)
)))
|#
| 13,592 | Common Lisp | .l | 320 | 31.696875 | 105 | 0.545633 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 874789c6d420e7885b9e3d23e3c2f18bb8364575cf7e3de355ee3d1efcaa15e2 | 33,696 | [
-1
] |
33,697 | point-defs-pc.lsp | rwoldford_Quail/source/window-basics/fast-graphics/point-defs-pc.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; point-defs-pc.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;; This file is an addition to Window-basics for moving pointclouds
;;;
;;; Authors:
;;; H.A. Chipman 1991
;;; C.B. Hurley 1991 George Washington University
;;; R.W. Oldford 1992.
;;; N.G. Bennett 1993
;;; G.W. Bennett 1996
;;;
;;;
;;;-------------------------------------------------------------------
(in-package :wb)
(defconstant *host-xor-mode* (boole-to-op :boole-xor))
(defconstant *host-or-mode* (boole-to-op :boole-1))
(defconstant *host-bic-mode* (boole-to-op :boole-1))
(defconstant *host-copy-mode* (boole-to-op :boole-1))
#|
(defvar *rgb-colors* )
(setq *rgb-colors* nil)
(defun get-rgb-colors ()
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-replace cg::po-invert cg::po-paint cg::po-erase))
(if *color-available*
(setq *rgb-colors*
(or *rgb-colors*
(loop for c in *colors* collect
(cons c (cond ( (eq-colors c *black-color*)
*black-rgb*)
( (eq-colors c *white-color*)
*white-rgb*)
(t (color-to-rgb c)))))
*colors*))))
(defmacro get-rgb-color (c)
(let ((pair (gensym))
(rgb-c (gensym)))
`(let ()
(declare (optimize (speed 3) (safety 0) (space 0)
(compilation-speed 0)))
(if ,*color-available*
(let ((,pair (assoc ,c (get-rgb-colors) :test #'=)))
(if ,pair
(cdr ,pair)
(let ((,rgb-c (color-to-rgb ,c)))
(push (cons ,c ,rgb-c) *rgb-colors*)
,rgb-c)))))))
|#
;; Takes x and y to be left and top respectively
;; Returns a SQUARE
;; Uses cg:: inside. Checked in gwbtests\expts-pointdefs-pc.lsp
;; March 25, 1996
;; Revised version of 15 Feb 1998 follows
;; it uses x, as CENTRE
;; old-parts-point-defs-pc.lsp
;; And now it is compatible with V/V-M/draw-macros.lsp form
;; with-point-symbol-bounds 17 Feb 1998 and with
;; h-draw::draw-inside-rectangle and ::erase-rect.
(defmacro fast-draw-box (canvas x y size fill? )
(declare (special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
(let ((s2 (gensym "fdbs2")) (lx (gensym "fdblx")) (ly (gensym "fdbly")) (mp (gensym "fdbmp")))
`(let* ((,s2 (truncate ,size 2))
(,lx (- ,x ,s2))
(,ly (- ,y ,s2))
(,mp (cg::frame-child ,canvas)))
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
(cond ((eq ,size 1)
;(cg::set-pixel-x-y ,mp ,x ,y 18oct05
(setf (cg::pixel-x-y ,mp) ,x ,y ;18oct05
(cg::foreground-color ,mp)))
(T
(if (= ,size 1)
(cg::fill-box ,mp
(cg::make-box ,x ,y (+ ,x ,size) (+ ,y ,size)))
(if ,fill?
(cg::fill-box ,mp
(cg::make-box ,lx ,ly
(+ ,lx ,size) (+ ,ly ,size )))
(cg::draw-box ,mp
(cg::make-box ,lx ,ly
(+ ,lx ,size)
(+ ,ly ,size)))
))
)
))))
;; Revised version of 15 Feb 1998 follows
;; which uses x,y as CENTRE
(defmacro fast-erase-box (canvas x y size fill? )
(declare (special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
(let ((s2 (gensym "febs2")) (lx (gensym "febs2")) (ly (gensym "febly")) (mp (gensym "febmp")))
`(let* ((,s2 (truncate ,size 2))
(,lx (- ,x ,s2))
(,ly (- ,y ,s2))
(,mp (cg::frame-child ,canvas)))
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg:po-invert cg::po-replace cg::po-paint))
(cg::with-paint-operation (,canvas cg::po-erase)
(if (= ,size 1)
(cg::erase-box ,mp
(cg::make-box ,x ,y (+ ,x ,size) (+ ,y ,size)))
(if ,fill?
(cg::erase-contents-box ,mp
(cg::make-box ,lx ,ly
(+ ,lx ,size) (+ ,ly ,size)))
(cg::erase-box ,mp
(cg::make-box ,lx ,ly
; (if (oddp ,size) (- ,ly 1) ,ly)
(+ ,lx ,size)
; (if (oddp ,size ) (+ ,ly ,size -1)
(+ ,ly ,size)))
))
))
))
;; Takes x and y as co-ordinates of the centre
;; size as the radius but it SHOULD use 1/2 size
;; Uses cg:: inside. Checked in gwbtests\expte-pointdefs-pc.lsp
;; March 25, 1996
(defun cg-draw-filled-circle (stream centre radius)
(declare (inline cg::fill-circle cg::draw-circle))
(let ((mp (cg::frame-child stream)))
(cg::fill-circle mp centre radius)
(cg::draw-circle mp centre radius)))
(defun cg-erase-filled-circle (stream centre radius)
(declare (inline cg::erase-contents-circle cg::erase-circle))
(let ((mp (cg::frame-child stream)))
(cg::erase-contents-circle mp centre radius)
(cg::erase-circle mp centre radius)))
(defmacro fast-draw-circle (canvas x y size fill? )
(declare (special cg::po-erase cg::po-paint cg::po-replace cg::po-invert)
(inline cg-draw-filled-circle cg::draw-circle))
(let ((s2 (gensym "fdcs2"))
(mp (gensym "fdcmp")))
;;; Check for size = 1 as special 05jan00
`(let ((,mp (cg::frame-child ,canvas)))
(cond ((eq 1 ,size)
(setf (cg:pixel-x-y ,mp ,x ,y)
(cg:foreground-color ,mp)))
(t
(let ((,s2 (if (oddp ,size) (1- (truncate (+ 1 ,size) 2))
(truncate (+ 1 ,size) 2)))) ;;; added + 1 24JNE99 oddp 11NOV99
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
(if ,fill?
(cg-draw-filled-circle canvas
(cg::make-position ,x ,y) ,s2)
(cg::draw-circle ,mp
(cg::make-position ,x ,y) ,s2 ))
))
))))
(defmacro fast-erase-circle (canvas x y size fill? )
(declare (special cg::po-erase cg::po-paint cg::po-replace cg::po-invert)
(inline cg-erase-filled-circle cg::erase-circle))
(let ((s2 (gensym "fecs2")) (mp (gensym "fecmp")))
;;; Check for size = 1 as special 05jan00
`(let ((,mp (cg::frame-child ,canvas)))
(cond ((eq 1 ,size)
(setf (cg:pixel-x-y ,mp ,x ,y)
(cg:background-color ,mp)))
(t
(let ((,s2 (if (oddp ,size) (1- (truncate (+ 1 ,size) 2))
(truncate (+ 1 ,size) 2)))) ;;; added + 1 24JNE99 oddp 11NOV99
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
(cg::with-paint-operation (,canvas cg::po-erase)
(if ,fill?
(cg-erase-filled-circle canvas
(cg::make-position ,x ,y) ,s2)
(cg::erase-circle ,mp
(cg::make-position ,x ,y) ,s2 )))
))
))))
;; May 28, 1996
;; Takes x and y as the centre
;; Uses cg:: inside it - checked in gwbtests\expts-poindefs-pc.lsp
;; March 25, 1996
(defmacro fast-draw-cross (canvas x y s fill? )
(declare (ignore fill?)
(special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
(let ((s2 (gensym "fdcrs2"))
(l (gensym "fdcrl"))
(mp (gensym "fdcrmp")))
`(let* ((,s2 (if (oddp ,s) (1- (truncate (+ 1 ,s) 2))
(truncate (+ 1 ,s) 2)))
(,l (list (cg::make-position (- ,x ,s2) ,y )
(cg::make-position (+ ,x ,s2 1) ,y )
(cg::make-position ,x (- ,y ,s2) )
(cg::make-position ,x (+ ,y ,s2 1))
))
(,mp (cg::frame-child ,canvas)))
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
(cg::move-to ,mp (first ,l))
(cg::draw-to ,mp (second ,l))
(cg::move-to ,mp (third ,l))
(cg::draw-to ,mp (fourth ,l))
)
)
)
(defmacro fast-erase-cross (canvas x y s fill? )
(declare (ignore fill?)
(special cg::po-paint cg::po-replace cg::po-invert cg::po-erase))
(let ((s2 (gensym "fecrs2"))
(l (gensym "fecrl"))
(mp (gensym "fecrmp")))
`(let* ((,s2 (if (oddp ,s) (1- (truncate (+ 1 ,s) 2))
(truncate (+ 1 ,s) 2)))
(,l (list (cg::make-position (- ,x ,s2) ,y )
(cg::make-position (+ ,x ,s2 1) ,y )
(cg::make-position ,x (- ,y ,s2) )
(cg::make-position ,x (+ ,y ,s2 1))
))
(,mp (cg::frame-child ,canvas)))
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
(cg::with-paint-operation (,canvas cg::po-erase)
(cg::move-to ,mp (first ,l))
(cg::erase-to ,mp (second ,l))
(cg::move-to ,mp (third ,l))
(cg::erase-to ,mp (fourth ,l))
))
)
)
;; Takes x and y as the centre
;; Does use cg:: inside it - checked in gwbtests\expts-poindefs-pc.lsp
;; March 25, 1996
(defmacro fast-draw-diamond (canvas x y s fill? )
(declare (special cg::po-erase cg::po-paint cg::po-replace cg::po-paint))
(let ((s2 (gensym "fdds2"))
(l (gensym "fddl"))
(mp (gensym "fddmp")))
;; Check for size off the top 07jan00
`(let ((,mp (cg::frame-child ,canvas)))
(cond ((= 1 ,s)
(setf (cg:pixel-x-y ,mp ,x ,y)
(cg:foreground-color ,mp)))
(T
(let* ((,s2 (if (oddp ,s) (1- (truncate (+ 1 ,s) 2))
(truncate (+ 1 ,s) 2))) ;; added +1 27Jne99 oddp 11nov99
(,l (list (cg::make-position (- ,x ,s2) ,y)
(cg::make-position ,x (+ ,y ,s2))
(cg::make-position (+ ,x ,s2) ,y)
(cg::make-position ,x (- ,y ,s2))
(cg::make-position (- ,x ,s2) ,y)
)
)
)
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
(if ,fill? (and (cg::fill-polygon ,mp ,l)
(cg::draw-polyline ,mp ,l))
(cg::draw-polyline ,mp ,l))
))))))
(defmacro fast-erase-diamond (canvas x y s fill? )
(declare (special cg::po-paint cg::po-replace cg::po-invert cg::po-erase))
(let ((s2 (gensym "feds2"))
(l (gensym "fedl"))
(mp (gensym "fedmp")))
;;; Check for size off the top 07jan00
`(let ((,mp (cg::frame-child ,canvas)))
(cond ((= 1 ,s)
(setf (cg:pixel-x-y ,mp ,x ,y)
(cg:background-color ,mp)))
(T
(let* ((,s2 (if (oddp ,s) (1- (truncate (+ 1 ,s) 2))
(truncate (+ 1 ,s) 2))) ;; added +1 27Jne99 oddp 11nov99
(,l (list (cg::make-position (- ,x ,s2) ,y)
(cg::make-position ,x (+ ,y ,s2))
(cg::make-position (+ ,x ,s2) ,y)
(cg::make-position ,x (- ,y ,s2))
(cg::make-position (- ,x ,s2) ,y)
)
)
)
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
;; (xlib:draw-lines (host-window ,canvas)
;; (gcontext ,canvas) ,l :fill-p ,fill?)
(cg::with-paint-operation (,canvas cg::po-erase)
(if ,fill? (and (cg::erase-contents-polygon ,mp ,l)
(cg::erase-polyline ,mp ,l))
(cg::erase-polyline ,mp ,l))
))))
)))
;; Takes x and y as the centre
;; Does use cg:: inside it - checked in gwbtests\expts-poindefs-pc.lsp
;; March 25, 1996
(defmacro fast-draw-triangle (canvas x y s fill? )
(declare (special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
(let ((s2 (gensym "fdts2"))
(l (gensym "fdtl")) ;(r (gensym)) ; 28JUL2023
;(tp (gensym)) ;(b (gensym)) 28JUL2023
;(poly (gensym)) ;28JUL2023
(mp (gensym "fdtmp")))
`(let* ((,s2 (if (oddp ,s) (1- (truncate (+ 1 ,s) 2))
(truncate (+ 1 ,s) 2))) ;; added +1 27Jne99
(,l (list (cg::make-position (- ,x ,s2) (+ ,y ,s2))
(cg::make-position ,x (- ,y ,s2))
(cg::make-position (+ ,x ,s2) (+ ,y ,s2))
(cg::make-position (- ,x ,s2) (+ ,y ,s2))
))
(,mp (cg::frame-child ,canvas))
)
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
;; (xlib:draw-lines (host-window ,canvas)
;; (gcontext ,canvas) ,l :fill-p ,fill?)
(if ,fill?
(and (cg::draw-polyline ,mp ,l)
(cg::fill-polygon ,mp ,l)) ;; 07dec99
(cg::draw-polyline ,mp ,l))
)
)
)
(defmacro fast-erase-triangle (canvas x y s fill? )
(declare (special cg::po-paint cg::po-replace cg::po-invert cg::po-erase))
(let ((s2 (gensym "fets2"))
(l (gensym "fetl")) ;(r (gensym)) ; 28JUL2023
;(tp (gensym)) ;(b (gensym)) ; 28JUL2023
;(poly (gensym)) ; 28JUL2023
(mp (gensym "fetmp")))
`(let* ((,s2 (if (oddp ,s) (1- (truncate (+ 1 ,s) 2))
(truncate (+ 1 ,s) 2))) ;; added +1 27Jne99
(,l (list (cg::make-position (- ,x ,s2) (+ ,y ,s2))
(cg::make-position ,x (- ,y ,s2))
(cg::make-position (+ ,x ,s2) (+ ,y ,s2))
(cg::make-position (- ,x ,s2) (+ ,y ,s2))
))
(,mp (cg::frame-child ,canvas))
)
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
;; (xlib:draw-lines (host-window ,canvas)
;; (gcontext ,canvas) ,l :fill-p ,fill?)
(cg::with-paint-operation (,canvas cg::po-erase)
(if ,fill?
(and (cg::erase-polyline ,mp ,l)
(cg::erase-contents-polygon ,mp ,l))
(cg::erase-polyline ,mp ,l))
))
)
)
(defconstant *cos-18* (cos (* pi 0.1)))
(defconstant *cos-54* (cos (* pi 0.3)))
(defconstant *sin-18* (sin (* pi 0.1)))
(defconstant *sin-54* (sin (* pi 0.3)))
;; Takes x and y as the centre
;; Does use cg:: inside it - checked in gwbtests\expts-poindefs-pc.lsp
;; March 25, 1996
(defmacro fast-draw-star (canvas x y s fill? )
(declare (ignore fill?)
(special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
(let ((r (gensym "fdsr")) (r*c18 (gensym "fdsrc18"))
(r*s18 (gensym "fdsrs18")) (r*c54 (gensym "fdsrc54")) (r*s54 (gensym "fdsrs54"))
(x1 (gensym "fdsx1")) (y1 (gensym "fdsy1"))
(x2 (gensym "fdsx2")) (y2 (gensym "fdsy2"))
(x3 (gensym "fdsx3"))
(x4 (gensym "fdsx4"))
(x5 (gensym)) (y5 (gensym "fdsy5"))
;(h (gensym)) ;(g (gensym)) ; 28JIL2023
(pt-list (gensym "fdsptl"))
(mp (gensym "fdsmp")))
;;; Check for size = 1 off the top
`(let ((,mp (cg::frame-child ,canvas)))
(cond ((= 1 ,s)
(setf (cg:pixel-x-y ,mp ,x ,y)
(cg:foreground-color ,mp))) ;; 3 lines 07jan00
(T
(let* ((,r (if (oddp ,s) (1- (truncate (+ 1 ,s) 2))
(truncate (+ 1 ,s) 2))) ;; added +1 27Jne99
(,r*c18 (round (* ,r *cos-18*)))
(,r*s18 (round (* ,r *sin-18*)))
(,r*c54 (round (* ,r *cos-54*)))
(,r*s54 (round (* ,r *sin-54*)))
(,x1 (+ (the fixnum ,x) (the fixnum ,r*c18)))
(,y1 (- (the fixnum ,y) (the fixnum ,r*s18)))
(,x2 (the fixnum ,x))
(,y2 (- (the fixnum ,y) (the fixnum ,r)))
(,x3 (- (the fixnum ,x) (the fixnum ,r*c18)))
(,x4 (- (the fixnum ,x) (the fixnum ,r*c54)))
(,x5 (+ (the fixnum ,x) (the fixnum ,r*c54)))
(,y5 (+ (the fixnum ,y) (the fixnum ,r*s54)))
(,pt-list (list
(cg::make-position ,x ,y)
(cg::make-position ,x1 ,y1)
(cg::make-position ,x ,y)
(cg::make-position ,x2 ,y2)
(cg::make-position ,x ,y)
(cg::make-position ,x3 ,y1)
(cg::make-position ,x ,y)
(cg::make-position ,x4 ,y5)
(cg::make-position ,x ,y)
(cg::make-position ,x5 ,y5)
(cg::make-position ,x ,y)
)
))
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
(cg::draw-polyline ,mp ,pt-list)
))))))
(defmacro fast-erase-star (canvas x y s fill? )
(declare (special cg::po-paint cg::po-replace cg::po-invert cg::po-erase))
(declare (ignore fill?)
(special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
(let ((r (gensym "fesr")) (r*c18 (gensym "fesrc18"))
(r*s18 (gensym "fesrs18")) (r*c54 (gensym "fesrc54")) (r*s54 (gensym "fesrs54"))
(x1 (gensym "fesx1")) (y1 (gensym "fesy1"))
(x2 (gensym "fesx2")) (y2 (gensym "fesy2"))
(x3 (gensym "fesx3"))
(x4 (gensym "fesx4"))
(x5 (gensym "fesx5")) (y5 (gensym "fesy5"))
;(h (gensym)) ;(g (gensym)) ; 28JUL2023
(pt-list (gensym "fesptl"))
(mp (gensym "fesmp")))
;; Check for size = 1 off the top
`(let ((,mp (cg::frame-child ,canvas)))
(cond ((= 1 ,s)
(setf (cg:pixel-x-y ,mp ,x ,y)
(cg:background-color ,mp))) ;; 3 lines 07jan00
(T
(let* ((,r (if (oddp ,s) (1- (truncate (+ 1 ,s) 2))
(truncate (+ 1 ,s) 2))) ;; added +1 27Jne99
(,r*c18 (round (* ,r *cos-18*)))
(,r*s18 (round (* ,r *sin-18*)))
(,r*c54 (round (* ,r *cos-54*)))
(,r*s54 (round (* ,r *sin-54*)))
(,x1 (+ (the fixnum ,x) (the fixnum ,r*c18)))
(,y1 (- (the fixnum ,y) (the fixnum ,r*s18)))
(,x2 (the fixnum ,x))
(,y2 (- (the fixnum ,y) (the fixnum ,r)))
(,x3 (- (the fixnum ,x) (the fixnum ,r*c18)))
(,x4 (- (the fixnum ,x) (the fixnum ,r*c54)))
(,x5 (+ (the fixnum ,x) (the fixnum ,r*c54)))
(,y5 (+ (the fixnum ,y) (the fixnum ,r*s54)))
(,pt-list (list
(cg::make-position ,x ,y)
(cg::make-position ,x1 ,y1)
(cg::make-position ,x ,y)
(cg::make-position ,x2 ,y2)
(cg::make-position ,x ,y)
(cg::make-position ,x3 ,y1)
(cg::make-position ,x ,y)
(cg::make-position ,x4 ,y5)
(cg::make-position ,x ,y)
(cg::make-position ,x5 ,y5)
(cg::make-position ,x ,y))
))
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
;; (xlib:draw-lines ,h ,g ,pt-list)
(cg::with-paint-operation (,canvas cg::po-erase)
(cg::erase-polyline ,mp ,pt-list)
)))))))
(defmacro fast-draw-symbol (canvas sim x y size fill )
(declare (special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
`(let ()
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
(case ,sim
(:box (fast-draw-box ,canvas ,x ,y ,size ,fill))
(:circle (fast-draw-circle ,canvas ,x ,y ,size ,fill ))
(:cross (fast-draw-cross ,canvas ,x ,y ,size ,fill ))
(:star (fast-draw-star ,canvas ,x ,y ,size ,fill ))
(:diamond (fast-draw-diamond ,canvas ,x ,y ,size ,fill ))
(:triangle (fast-draw-triangle ,canvas ,x ,y ,size ,fill ))
(t nil))))
(defmacro fast-erase-symbol (canvas sim x y size fill )
(declare (special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
`(let ()
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
(case ,sim
(:box (fast-erase-box ,canvas ,x ,y ,size ,fill))
(:circle (fast-erase-circle ,canvas ,x ,y ,size ,fill ))
(:cross (fast-erase-cross ,canvas ,x ,y ,size ,fill ))
(:star (fast-erase-star ,canvas ,x ,y ,size ,fill ))
(:diamond (fast-erase-diamond ,canvas ,x ,y ,size ,fill ))
(:triangle (fast-erase-triangle ,canvas ,x ,y ,size ,fill ))
(t nil))))
(defmacro mode-draw-symbol (canvas sim x y size fill mode)
(declare (special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
;(let ((mp (gensym "mdsmp"))) ;;02OCT2023 unused
`(let (;(,mp (cg::frame-child ,canvas)) ;;02OCT2023 unused
)
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
(cg::with-paint-operation (,canvas ,mode)
(fast-draw-symbol ,canvas ,sim ,x ,y ,size ,fill)
)
)
;)
)
(defmacro mode-erase-symbol (canvas sim x y size fill mode)
(declare (special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
`(let ()
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-paint cg::po-replace cg::po-invert))
(cg::with-paint-operation (,canvas ,mode)
(fast-erase-symbol ,canvas ,sim ,x ,y ,size ,fill)
)
))
(defmacro cc-set-rgb-color (canvas color)
(declare (special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
(let ((mp (gensym "ccsrcmp")))
`(let ((,mp (cg::frame-child ,canvas)))
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
(when ,color
;(cg::set-foreground-color ,mp ,color) 18oct05
(setf (cg::foreground-color ,mp) ,color) ;18oct05
))))
(defmacro bw-set-color (canvas color)
(declare (special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
`(let ()
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
(when ,color
(set-draw-color ,canvas ,color))))
(defmacro set-draw-color (canvas color)
(declare (special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
(let ((mp (gensym "sdcmp")))
`(let ((,mp (cg::frame-child ,canvas)))
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
(when ,color
(if (colored-canvas-p ,canvas)
(if (colorp ,color)
;(cg::set-foreground-color ,mp ,color) 18oct05
(setf (cg::foreground-color ,mp) ,color) ;18oct05
))))))
(defmacro set-fast-color (canvas color)
(declare (special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
(let ((mp (gensym "sfcmp")))
`(let ((,mp (cg::frame-child ,canvas)))
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
(if (colored-canvas-p ,canvas)
;(cg::set-foreground-color ,mp ,color) 18oct05
(setf (cg::foreground-color ,mp) ,color) ;18oct05
))))
(defmacro fast-move-to (canvas x y)
(let ((mp (gensym "fmvtmp")))
`(let ((,mp (cg::frame-child ,canvas)))
(setf (cg::current-position ,mp) (cg::make-position ,x ,y)))))
(defmacro fast-line-to (canvas x y)
(declare (special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
(let ((mp (gensym "flntmp")))
`(let ((,mp (cg::frame-child ,canvas)))
(cg::draw-line ,mp (cg::current-position ,mp)
(cg::make-position ,x ,y))
)))
(defmacro fast-erase-to (canvas x y)
(declare (special cg::po-paint cg::po-replace cg::po-invert cg::po-erase))
(let ((mp (gensym "fertmp")))
`(let ((,mp (cg::frame-child ,canvas)))
(cg::with-paint-operation (,canvas cg::po-erase)
(cg::erase-line ,mp (cg::current-position ,mp)
(cg::make-position ,x ,y))
))))
(defmacro fast-draw-line (canvas x1 y1 x2 y2 )
(declare (special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
(let ((mp (gensym "fdlmp")))
`(let ((,mp (cg::frame-child ,canvas)))
(cg::draw-line ,mp (cg::make-position ,x1 ,y1)
(cg::make-position ,x2 ,y2))
)))
;;; More mode clarification needed
;; Original version follows
;; We need the following form for lines-pc.lsp
(defmacro fast-erase-line (canvas x1 y1 x2 y2)
(declare (special cg::po-paint cg::po-replace cg::po-invert cg::po-erase))
(let ((mp (gensym "felmp")))
`(let ((,mp (cg::frame-child ,canvas)))
(cg::with-paint-operation (,canvas cg::po-erase)
(cg::erase-line ,mp (cg::make-position ,x1 ,y1)
(cg::make-position ,x2 ,y2))
))))
;; New version from f-g\gwbtests\expts-mode-draw.lsp
(defmacro mode-draw-line (canvas x1 y1 x2 y2 mode)
(declare (special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
;(let ((mp (gensym "mdlmp"))) ;;02OCT2023 unused
`(let (;(,mp (cg::frame-child ,canvas)) ;;02OCT2020 unused
)
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
(cg::with-paint-operation (,canvas ,mode)
(fast-draw-line ,canvas
(the fixnum ,x1)
(the fixnum ,y1)
(the fixnum ,x2)
(the fixnum ,y2))
)
)
;)
)
(defmacro mode-erase-line (canvas x1 y1 x2 y2 mode)
(declare (special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
`(let ()
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special cg::po-erase cg::po-invert cg::po-replace cg::po-paint))
(cg::with-paint-operation (,canvas ,mode)
(fast-erase-line ,canvas
(the fixnum ,x1)
(the fixnum ,y1)
(the fixnum ,x2)
(the fixnum ,y2))
)
))
;;; End of file point-defs-pc.lsp
| 30,218 | Common Lisp | .l | 636 | 33.988994 | 98 | 0.466895 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 05691fb711397f2eb8d4a369128903c796c764f27d76b7e42c7ba32dffe5b091 | 33,697 | [
-1
] |
33,699 | lines-sblx.lsp | rwoldford_Quail/source/window-basics/fast-graphics/lines-sblx.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; lines-sblx.lsp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;; This file is an addition to Window-basics for moving pointclouds
;;;
;;; Authors:
;;; H.A. Chipman 1991
;;; C.B. Hurley 1991 George Washington University
;;; R.W. Oldford 1992
;;; G.W. Bennett 1996
;;;
;;;
;;;--------------------------------------------------------------------
(in-package :wb)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(canvas-draw-lines canvas-erase-lines canvas-move-lines)))
;; coords are lists with even length (s1 e1 s2 e2...) where s1 and e1 are the start
;; and end of the first line
(defun draw-fw-lines (canvas coords &key (width 1)
invisible?
color
erase? &allow-other-keys)
"Draws or erases colored fixed width lines"
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (type fixnum width))
(let ((mp (clim:get-frame-pane canvas 'host-pane)))
(with-drawing-options (mp :ink color :line-thickness width)
(loop
for (xs ys) fixnum in coords by #'cddr
for (xe ye) fixnum in (cdr coords) by #'cddr
for i in invisible?
unless i
do
(if erase?
(fast-erase-line canvas xs ys xe ye)
(fast-draw-line canvas xs ys xe ye)))
)
))
;;;
(defun xor-move-fw-lines (canvas old-coords new-coords
&key (width 1) color &allow-other-keys )
"Moves colored fixed width lines~
Results with color background are undefined"
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
;(declare (type fixnum width))
(let* ((mp (clim:get-frame-pane canvas 'host-pane))
(mpbg (medium-background (clim:get-frame-pane canvas 'host-pane))))
(loop
for (sx1 sy1 ) fixnum in old-coords by #'cddr
for (ex1 ey1 ) fixnum in (cdr old-coords) by #'cddr
for (sx2 sy2 ) fixnum in new-coords by #'cddr
for (ex2 ey2 ) fixnum in (cdr new-coords) by #'cddr
do
(with-drawing-options (mp :ink mpbg :line-thickness width)
(fast-erase-line canvas sx1 sy1 ex1 ey1))
(with-drawing-options (mp :ink color :line-thickness width)
(fast-draw-line canvas sx2 sy2 ex2 ey2))
)
))
;;;
;;; Since clim has no xor (above) drawing mode or other drawing modes
;;; test-move-fw-lines is just a call to xor-move-fw-lines
(defun move-fw-lines (canvas old-coords new-coords
&key (width 1) color &allow-other-keys )
"Moves colored fixed width lines"
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
;(declare (type fixnum width))
(xor-move-fw-lines canvas old-coords new-coords :width width :color color))
;;;
(defun draw-multi-color-lines (canvas coords &key (width 1) color invisible?
erase? &allow-other-keys)
"Draws or erases lines with varying color."
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (type fixnum width) (ignorable invisible?))
(let* ((mp (clim:get-frame-pane canvas 'host-pane))
(mpbg (medium-background (clim:get-frame-pane canvas 'host-pane))))
(loop
for (xs ys ) fixnum in coords by #'cddr
for (xe ye ) fixnum in (cdr coords) by #'cddr
for c in color
do
(if erase?
(with-drawing-options (mp :ink mpbg :line-thickness width)
(fast-erase-line canvas xs ys xe ye))
(with-drawing-options (mp :ink c :line-thickness width)
(fast-draw-line canvas xs ys xe ye))
)
)
))
;;;
;;; There is no xor- in clim .. regular code
(defun xor-move-multi-color-lines (canvas old-coords new-coords
&key (width 1) color
invisible? &allow-other-keys )
"Moves lines with varying color. ~
Results with color background are undefined."
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (type fixnum width) (ignorable invisible?))
(let* ((mp (clim:get-frame-pane canvas 'host-pane))
(mpbg (medium-background (clim:get-frame-pane canvas 'host-pane))))
(loop
for (sx1 sy1 ) fixnum in old-coords by #'cddr
for (ex1 ey1 ) fixnum in (cdr old-coords) by #'cddr
for (sx2 sy2 ) fixnum in new-coords by #'cddr
for (ex2 ey2 ) fixnum in (cdr new-coords) by #'cddr
for c in color
do
(with-drawing-options (mp :ink mpbg :line-thickness width)
(fast-erase-line canvas sx1 sy1 ex1 ey1))
(with-drawing-options (mp :ink c :line-thickness width)
(fast-draw-line canvas sx2 sy2 ex2 ey2))
)
))
;;;
(defun move-multi-color-lines (canvas old-coords new-coords
&key (width 1)
color rgb-color? &allow-other-keys )
"Moves lines with varying color."
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (type fixnum width)
(ignore rgb-color?))
(let* ((mp (clim:get-frame-pane canvas 'host-pane))
(mpbg (medium-background (clim:get-frame-pane canvas 'host-pane))))
(loop
for (sx1 sy1 ) fixnum in old-coords by #'cddr
for (ex1 ey1 ) fixnum in (cdr old-coords) by #'cddr
for (sx2 sy2 ) fixnum in new-coords by #'cddr
for (ex2 ey2 ) fixnum in (cdr new-coords) by #'cddr
for c in color
do
(with-drawing-options (mp :ink mpbg :line-thickness width)
(fast-erase-line canvas sx1 sy1 ex1 ey1))
(with-drawing-options (mp :ink c :line-thickness width)
(fast-draw-line canvas sx2 sy2 ex2 ey2))
)
))
;;;
(defun draw-multi-color-&-width-lines (canvas coords &key width color
invisible? erase? &allow-other-keys)
"Draws or erases lines with varying color and width."
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
;(declare (type fixnum width)
(declare (ignorable invisible?))
(let ((mp (clim:get-frame-pane canvas 'host-pane))
(mpbg (medium-background (clim:get-frame-pane canvas 'host-pane))))
(loop
for (xs ys ) fixnum in coords by #'cddr
for (xe ye ) fixnum in (cdr coords) by #'cddr
for w in width
for c in color
do
(if erase?
(with-drawing-options (mp :ink mpbg :line-thickness w)
(fast-erase-line canvas xs ys xe ye))
(with-drawing-options (mp :ink c :line-thickness w)
(fast-draw-line canvas xs ys xe ye))
)
)
)
)
;;;
;;; Thers is no xor so regular code
(defun xor-move-multi-color-&-width-lines (canvas old-coords new-coords
&key width color &allow-other-keys )
"Moves lines with varying color and width~
Results with color background are undefined."
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
;(declare (type fixnum width))
(let* ((mp (clim:get-frame-pane canvas 'host-pane))
(mpbg (medium-background (clim:get-frame-pane canvas 'host-pane))))
(loop
for (sx1 sy1 ) fixnum in old-coords by #'cddr
for (ex1 ey1 ) fixnum in (cdr old-coords) by #'cddr
for (sx2 sy2 ) fixnum in new-coords by #'cddr
for (ex2 ey2 ) fixnum in (cdr new-coords) by #'cddr
for w in width
for c in color
do
(with-drawing-options (mp :ink mpbg :line-thickness w)
(fast-erase-line canvas sx1 sy1 ex1 ey1))
(with-drawing-options (mp :ink c :line-thickness w)
(fast-draw-line canvas sx2 sy2 ex2 ey2))
)
))
;;;
;;; the following is just a call to the previous
(defun move-multi-color-&-width-lines
(canvas old-coords new-coords &key width color rgb-color? &allow-other-keys )
"Moves lines with varying color and width"
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
;(declare (type fixnum width))
(declare (ignorable rgb-color?))
(xor-move-multi-color-&-width-lines canvas old-coords new-coords :width width
:color color))
;;;
(defun canvas-draw-lines (canvas coords
&key (width 1) (erase? nil)
color
invisible?
&allow-other-keys )
"Draws or erases lines "
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(declare (type fixnum width))
(if (and color (listp color))
(if (and width (listp width))
(draw-multi-color-&-width-lines canvas coords :width width :color color :erase? erase?
:invisible? invisible?)
(draw-multi-color-lines canvas coords :width width :color color :erase? erase?
:invisible? invisible?))
(draw-fw-lines canvas coords
:width (if (listp width ) (car width) width)
:color (if (listp color ) (car color) color)
:erase? erase?
:invisible invisible?)
))
;;;
(defun canvas-erase-lines (canvas coords
&key (width 1)
color
&allow-other-keys )
"Erases lines "
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)
(inline canvas-draw-lines)))
(declare (type fixnum width))
(canvas-draw-lines canvas coords :width width :color color :erase? t))
;;;
(defun canvas-move-lines (canvas old-coords new-coords
&key (width 1) (rgb-color? nil)
color
&allow-other-keys )
"Moves lines "
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
;(declare (type fixnum width))
(if (and color (listp color))
(if (and width (listp width))
(move-multi-color-&-width-lines canvas old-coords new-coords
:width width
:color (if (and (colored-canvas-p canvas) (not rgb-color? ))
(rgb-colors color)
color))
(move-multi-color-lines canvas old-coords new-coords
:width width
:color (if (and (colored-canvas-p canvas) (not rgb-color? ))
(rgb-colors color)
color)))
(move-fw-lines canvas old-coords new-coords
:width (if (listp width ) (car width))
:color (if (listp color ) (car color))) ;<<== compiler used clim:color
)
)
;;;
(defun canvas-draw-axes (canvas axes &key (width 1) (erase? nil)
color)
"Draws or erases axes"
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
;(declare (type fixnum width))
(when axes
;(let* ((mp (get-frame-pane canvas 'host-pane))
; (mpbg (medium-background (get-frame-pane canvas 'host-pane))))
(if erase?
(draw-fw-lines canvas axes :color color :width width :erase? t)
(draw-fw-lines canvas axes :color color :width width ))
;)
))
;;;
(defun canvas-erase-axes (canvas axes
&key (width 1)
color)
"Erases axes "
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0) (inline canvas-draw-axes)))
(declare (type fixnum width))
(canvas-draw-axes canvas axes :width width :color color :erase? t))
;;;
(defun canvas-move-axes (canvas old-axes new-axes
&key (width 1)
color
&allow-other-keys )
"Moves axes "
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
;(declare (type fixnum width))
(when old-axes
(let* ((mp (clim:get-frame-pane canvas 'host-pane))
(mpbg (medium-background (clim:get-frame-pane canvas 'host-pane))))
(loop
for (sx1 sy1 ) fixnum in old-axes by #'cddr
for (ex1 ey1 ) fixnum in (cdr old-axes) by #'cddr
for (sx2 sy2 ) fixnum in new-axes by #'cddr
for (ex2 ey2 ) fixnum in (cdr new-axes) by #'cddr
do
(with-drawing-options (mp :ink mpbg :line-thickness width)
(fast-erase-line canvas sx1 sy1 ex1 ey1))
(with-drawing-options (mp :ink color :line-thickness width)
(fast-draw-line canvas sx2 sy2 ex2 ey2))
)
)))
| 13,960 | Common Lisp | .l | 317 | 32.40694 | 123 | 0.536152 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 3a6c18bdce64cbe5c5ee37dd9b3a33faa7c99a86ce589fd26b524706f7200848 | 33,699 | [
-1
] |
33,704 | rotate.lsp | rwoldford_Quail/source/window-basics/fast-graphics/rotate.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; rotate.lsp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;;
;;; This file is an addition to Window-basics for moving pointclouds
;;;
;;;
;;; Authors:
;;; H.A. Chipman 1991
;;; C.B. Hurley 1991 George Washington University
;;;
;;;
;;;
;;;
;;;----------------------------------------------------------------------------------
(in-package :wb)
(export '(rotate-point-cloud draw-point-cloud scale-data-for-region
mapply-rotation! rotate-line-segments draw-line-segments
make-rotation-transform make-shift-transform))
(defun x-shift (region)
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(declare (inline + aref round /))
(round (+ (aref region 0) (/ (aref region 2) 2))))
(defun y-shift (region)
#-:sbcl(declare
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(declare (inline + aref round /))
(round (+ (aref region 1) (/ (aref region 3) 2))))
(defun make-shift-transform (region)
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(make-instance '2d-shift
:x-shift (x-shift region) :y-shift (y-shift region)))
(defun make-rotation-transform (region direction )
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(let* ((xhift (x-shift region))
(yshift (y-shift region)))
(ecase direction
(:x (make-instance '3d-x-rotate&2d-shift :angle 0
:x-shift xhift :y-shift yshift))
(:y (make-instance '3d-y-rotate&2d-shift :angle 0
:x-shift xhift :y-shift yshift))
(:z (make-instance '3d-z-rotate&2d-shift :angle 0
:x-shift xhift :y-shift yshift)))))
#| This version does not contain code used by views involving draw-rate
;;; see the version which follows this ;;14JUL2023
(defun rotate-point-cloud (c points
&key axes axis-color
(steps 100) (increment (/ pi 30)) (direction :y)
size fill? symbol color invisible?
( plot-rgn (canvas-region c) )
(standardize? nil) (center? nil) (viewport-coords? nil)
erase-points erase-axes
stop-fn)
"Rotates a point-cloud using plotting traps. The point cloud is in list form~
with each sublist an x,y,z observation. !!"
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(inline canvas-move-axes
canvas-move-symbols
mapply-transform-store
)
)
(declare (inline rotatef incf))
(let ((data (append points axes )))
(if viewport-coords?
(progn
(if (and (not standardize?) center?)
(setq data (center-data-lists data))
(if standardize?
(setq data (standardize-data-lists data))))
(setq data (scale-data-for-region data plot-rgn))))
(let* ((old-points (copy-tree points)) (old-axes (copy-tree axes))
(new-points (copy-tree points)) (new-axes (copy-tree axes))
(rot (make-rotation-transform plot-rgn direction ))
(single-color? (every #'(lambda(c) (eq-colors c (car color))) color)))
(if (and (colored-canvas-p c) (not single-color?))
(setq color (rgb-colors color)))
(mapply-transform-store rot data (append old-points old-axes))
(with-pen-values-restored c
(unless erase-points
(canvas-draw-symbols c old-points :symbol symbol
:color color :fill? fill? :size size
:invisible? invisible? :single-color? single-color? ))
(unless erase-axes
(canvas-draw-axes c old-axes :color axis-color))
(incf (angle-of rot) increment)
(mapply-transform-store rot data (append new-points new-axes))
(canvas-move-symbols c (or erase-points old-points) new-points
:symbol symbol :color color :fill? fill?
:size size :invisible? invisible?
:rgb-color? t :single-color? single-color? )
(canvas-move-axes c (or erase-axes old-axes) new-axes :color axis-color )
;;; loop with the do keyword - better than "loop". CW 03/1997.
; (loop for k from 1 below steps
; until (if (functionp stop-fn) (funcall stop-fn))
; do
(do ((k 1 (incf k)))
((or (= k steps) (if (functionp stop-fn) (funcall stop-fn))))
(incf (angle-of rot) increment)
(rotatef old-axes new-axes) (rotatef old-points new-points)
(mapply-transform-store rot data (append new-points new-axes))
(canvas-move-symbols c old-points new-points :symbol symbol
:color color :fill? fill? :size size
:invisible? invisible?
:rgb-color? t :single-color? single-color?)
(when axes
(canvas-move-axes c old-axes new-axes :color axis-color)))
)
(values rot new-points new-axes)
)))
|#
;;; Version from QUAIL-2009-ACER which does contain the draw-rate material
;;; 14JUL2023
(defun rotate-point-cloud (c points
&key axes axis-color
(steps 100) (increment (/ pi 30)) (direction :y)
size fill? symbol color invisible?
( plot-rgn (canvas-region c) )
(draw-rate nil)
(standardize? nil) (center? nil) (viewport-coords? nil)
erase-points erase-axes
stop-fn)
"Rotates a point-cloud using plotting traps. The point cloud is in list form~
with each sublist an x,y,z observation. !!"
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(inline canvas-move-axes
;rotatef
canvas-move-symbols
mapply-transform-store
;incf
)
)
(let ((data (append points axes )))
(if viewport-coords?
(progn
(if (and (not standardize?) center?)
(setq data (center-data-lists data))
(if standardize?
(setq data (standardize-data-lists data))))
(setq data (scale-data-for-region data plot-rgn))))
(let* ((old-points (copy-tree points)) (old-axes (copy-tree axes))
(new-points (copy-tree points)) (new-axes (copy-tree axes))
(rot (make-rotation-transform plot-rgn direction ))
(bg-color (canvas-background-color c))
(pen-color (pen-color-of c))
(single-color? (every #'(lambda(c) (eq-colors c (car color))) color))
(draw-time (if draw-rate (round (/ internal-time-units-per-second draw-rate))))
start-time step-time)
(if (and (colored-canvas-p c) (not single-color?))
(setq color (rgb-colors color pen-color )))
(mapply-transform-store rot data (append old-points old-axes))
(unless erase-points
(with-pen-values-restored c
(canvas-draw-symbols c old-points :symbol symbol
:color color :fill? fill? :size size
:invisible? invisible? :single-color? single-color? )
(canvas-set-pen c :color bg-color)))
(unless erase-axes
(with-pen-values-restored c
(canvas-draw-axes c old-axes :color axis-color)
(canvas-set-pen c :color bg-color)))
(incf (angle-of rot) increment)
(mapply-transform-store rot data (append new-points new-axes))
(with-pen-values-restored c
(canvas-move-symbols c (or erase-points old-points) new-points
:symbol symbol :color color :fill? fill?
:size size :invisible? invisible?
:rgb-color? t :single-color? single-color? )
(canvas-set-pen c :color bg-color))
(with-pen-values-restored c
(canvas-move-axes c (or erase-axes old-axes) new-axes :color axis-color )
(canvas-set-pen c :color bg-color))
;;; loop with the do keyword - better than "loop". CW 03/1997.
; (loop for k from 1 below steps
; until (if (functionp stop-fn) (funcall stop-fn))
; do
(do ((k 1 (incf k)))
((or (= k steps) (if (functionp stop-fn) (funcall stop-fn))))
(if draw-rate
(setq start-time (get-internal-real-time)))
(incf (angle-of rot) increment)
(rotatef old-axes new-axes) (rotatef old-points new-points)
(mapply-transform-store rot data (append new-points new-axes))
(with-pen-values-restored c
(canvas-move-symbols c old-points new-points :symbol symbol
:color color :fill? fill? :size size
:invisible? invisible?
:rgb-color? t :single-color? single-color?)
(canvas-set-pen c :color bg-color)
)
(when axes
(with-pen-values-restored c
(canvas-move-axes c old-axes new-axes :color axis-color)
(canvas-set-pen c :color bg-color)))
(when draw-rate
(setq step-time (- (get-internal-real-time) start-time))
(if (< step-time draw-time)
(sleep (min 1 (/ (- draw-time step-time) internal-time-units-per-second)))))
)
(values rot new-points new-axes)
)))
(defun draw-point-cloud (c points
&key axes
size fill? symbol color invisible?
( plot-rgn (canvas-region c) )
(standardize? nil) (center? nil)
(viewport-coords?))
"Draws a point-cloud using plotting traps. The point cloud is in list form~
with each sublist an x,y,z observation. !!"
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(let ((data (append points axes )))
(if viewport-coords?
(progn
(if (and (not standardize?) center?)
(setq data (center-data-lists data))
(if standardize?
(setq data (standardize-data-lists data))))
(setq data (scale-data-for-region data plot-rgn))))
(let* ((scaled-data (scale-data-for-region
data plot-rgn))
(shift (make-shift-transform plot-rgn ))
(scaled-points (subseq scaled-data 0 (length points)))
(scaled-axes (subseq scaled-data (length points) )))
(mapply-transform! shift scaled-data )
(with-pen-values-restored c
(canvas-draw-symbols c scaled-points :symbol symbol
:color color :fill? fill? :size size
:invisible? invisible?)
(canvas-draw-axes c scaled-axes )
)
)))
(defmethod mapply-rotation! ((rot 3d-rotate) (a list) &key (integer? t))
#-:sbcl(declare (optimize (speed 3) (safety 0) (space 0) (compilation-speed 0))
(inline mapply-transform! ))
(declare (inline elt round * / float))
(if integer?
(mapply-transform! rot a)
(let* ((big 10000)
(integer-coefs
(loop for c in a collect
(loop for ci in c collect
(round (* big ci))))))
(mapply-transform! rot integer-coefs)
(loop for cnew in integer-coefs
for cold in a do
(loop for ci in cnew
for i upfrom 0
do
(setf (elt cold i) (float (/ ci big))))))))
(defun scale-data-for-region (data region)
"scales data so that when rotated and shifted it will always fit in a window~
with minimum dimension SIZE ~
Data should already be centered at 0"
#-:sbcl(declare (optimize (speed 3) (safety 0) (space 0) (compilation-speed 0))) ; 29JUL2023 added last )
(declare (inline round *))
(let* ((size (min (aref region 2) (aref region 3)))
(d (/ size
(sqrt (loop for di in data
maximize (loop for dij in di
sum (* dij dij))))
2)))
(loop for di in data collect
(loop for dij in di collect (round (* dij d))))
)) ; 29JUL2023 deleted last ) .. see above
(defun standardize-data-lists (data )
"scales 3-d data so that each dimension has mean 0 and variance 1"
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0)))
(let* ((mean #'(lambda(i)
(/ (loop for di in data sum (elt di i)) (length data))))
(sd #'(lambda(i m)
(sqrt (/ (loop for di in data sum (expt (- (elt di i) m) 2))
(length data)))))
(m0 (funcall mean 0)) (sd0 (funcall sd 0 m0))
(m1 (funcall mean 1)) (sd1 (funcall sd 1 m1))
(m2 (funcall mean 2)) (sd2 (funcall sd 2 m2)))
(loop with means = (list m0 m1 m2)
with sds = (list sd0 sd1 sd2)
for d in data collect
(loop for di in d
for m in means
for sd in sds
collect (/ (- di m) sd)))))
(defun center-data-lists (data )
"center 3-d data so that each dimension has mean 0 "
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(let* (
(mean #'(lambda(i)
(/ (loop for di in data sum (elt di i)) (length data))))
(m0 (funcall mean 0))
(m1 (funcall mean 1))
(m2 (funcall mean 2)) )
(loop with means = (list m0 m1 m2)
for d in data collect
(loop for di in d
for m in means
collect (- di m)))))
(defun rotate-line-segments (c points
&key axes axis-color
(steps 100) (increment (/ pi 30)) (direction :y)
width color invisible?
( plot-rgn (canvas-region c) )
(standardize? nil) (center? nil) (viewport-coords? nil)
erase-points erase-axes
stop-fn)
"Rotates lines using plotting traps. points gives the lines coordinates,~
where points has even length, each pair giving the segment endpoints. "
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(inline canvas-move-axes
canvas-move-lines
mapply-transform-store
)
)
(declare (inline ;rotatef
;incf
))
(let ((data (append points axes )))
(if viewport-coords?
(progn
(if (and (not standardize?) center?)
(setq data (center-data-lists data))
(if standardize?
(setq data (standardize-data-lists data))))
(setq data (scale-data-for-region data plot-rgn))))
(let* ((old-points (copy-tree points)) (old-axes (copy-tree axes))
(new-points (copy-tree points)) (new-axes (copy-tree axes))
(rot (make-rotation-transform plot-rgn direction ))
(single-color? (every #'(lambda(c) (eq-colors c (car color))) color))
(single-width? (every #'(lambda(c) (= c (car width))) width))
)
(if (and (colored-canvas-p c) (not single-color?))
(setq color (rgb-colors color)))
(mapply-transform-store rot data (append old-points old-axes))
(if (and single-color? single-width?)
(setq color (car color)))
(if single-width?
(setq width (car width)))
(with-pen-values-restored c
(unless erase-points
(canvas-draw-lines c old-points
:color color :width width
:invisible? invisible?))
(unless erase-axes
(canvas-draw-axes c old-axes :color axis-color))
(incf (angle-of rot) increment)
(mapply-transform-store rot data (append new-points new-axes))
(canvas-move-lines c (or erase-points old-points) new-points
:color color
:width width :invisible? invisible?
:rgb-color? t )
(canvas-move-axes c (or erase-axes old-axes) new-axes :color axis-color )
; (loop for k from 1 below steps
; until (if (functionp stop-fn) (funcall stop-fn))
; do
(do ((k 1 (incf k)))
((or (= k steps) (if (functionp stop-fn) (funcall stop-fn))))
(incf (angle-of rot) increment)
(rotatef old-axes new-axes) (rotatef old-points new-points)
(mapply-transform-store rot data (append new-points new-axes))
(canvas-move-lines c old-points new-points
:color color :width width
:invisible? invisible?
:rgb-color? t :single-color? single-color?)
(when axes
(canvas-move-axes c old-axes new-axes :color axis-color))) )
(values rot new-points new-axes)
)))
(defun draw-line-segments (c points
&key axes
width color invisible?
( plot-rgn (canvas-region c) )
(standardize? nil) (center? nil)
(viewport-coords?))
"Draws lines using plotting traps. points gives the lines coordinates,~
where points has even length, each pair giving the segment endpoints. "
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(let ((data (append points axes )))
(if viewport-coords?
(progn
(if (and (not standardize?) center?)
(setq data (center-data-lists data))
(if standardize?
(setq data (standardize-data-lists data))))
(setq data (scale-data-for-region data plot-rgn))))
(let* ((scaled-data (scale-data-for-region
data plot-rgn))
(shift (make-shift-transform plot-rgn ))
(scaled-points (subseq scaled-data 0 (length points)))
(scaled-axes (subseq scaled-data (length points) )))
(mapply-transform! shift scaled-data )
(with-pen-values-restored c
(canvas-draw-lines c scaled-points
:color color :width width
:invisible? invisible?)
(canvas-draw-axes c scaled-axes )
)
)))
(defun rotate-line-segments-points (c points
&key axes axis-color
(steps 100) (increment (/ pi 30)) (direction :y)
width color invisible?
psize psymbol pfill?
pcolor pinvisible?
(draw-rate nil)
( plot-rgn (canvas-region c) )
(standardize? nil) (center? nil) (viewport-coords? nil)
erase-points erase-axes
stop-fn)
"Rotates lines using plotting traps. points gives the lines coordinates,~
where points has even length, each pair giving the segment endpoints. "
#-:sbcl(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(inline canvas-move-axes
canvas-move-lines
mapply-transform-store
)
)
(declare (inline ;rotatef
;incf
))
(let ((data (append points axes )))
(if viewport-coords?
(progn
(if (and (not standardize?) center?)
(setq data (center-data-lists data))
(if standardize?
(setq data (standardize-data-lists data))))
(setq data (scale-data-for-region data plot-rgn))))
(let* ((old-points (copy-tree points)) (old-axes (copy-tree axes))
(new-points (copy-tree points)) (new-axes (copy-tree axes))
(rot (make-rotation-transform plot-rgn direction ))
(single-pcolor? (every #'(lambda(c) (eq-colors c (car pcolor))) pcolor))
(single-color? (every #'(lambda(c) (eq-colors c (car color))) color))
(single-width? (every #'(lambda(c) (= c (car width))) width))
(bg-color (canvas-background-color c))
(draw-time (if draw-rate (round (/ internal-time-units-per-second draw-rate))))
start-time step-time)
(if (and (colored-canvas-p c) (not single-color?))
(setq color (rgb-colors color (pen-color-of c))))
(if (and (colored-canvas-p c) (not single-pcolor?))
(setq pcolor (rgb-colors pcolor (pen-color-of c))))
(mapply-transform-store rot data (append old-points old-axes))
(if (and single-color? single-width?)
(setq color (car color)))
(if single-width?
(setq width (car width)))
(unless erase-points
(with-pen-values-restored c
(canvas-draw-lines c old-points
:color color :width width
:invisible? invisible?)
(canvas-set-pen c :color bg-color))
(with-pen-values-restored c
(canvas-draw-symbols c old-points :symbol psymbol
:color pcolor :fill? pfill? :size psize
:invisible? pinvisible?
:single-color? single-pcolor? )
(canvas-set-pen c :color bg-color)))
(unless erase-axes
(with-pen-values-restored c
(canvas-draw-axes c old-axes :color axis-color)
(canvas-set-pen c :color bg-color)))
(incf (angle-of rot) increment)
(mapply-transform-store rot data (append new-points new-axes))
(with-pen-values-restored c
(canvas-move-lines c (or erase-points old-points) new-points
:color color
:width width :invisible? invisible?
:rgb-color? t )
(canvas-set-pen c :color bg-color))
(with-pen-values-restored c
(canvas-move-symbols c (or erase-points old-points) new-points
:symbol psymbol :color pcolor :fill? pfill?
:size psize :invisible? pinvisible?
:rgb-color? t :single-color? single-pcolor? )
(canvas-set-pen c :color bg-color))
(with-pen-values-restored c
(canvas-move-axes c (or erase-axes old-axes) new-axes :color axis-color )
(canvas-set-pen c :color bg-color))
; (loop for k from 1 below steps
; until (if (functionp stop-fn) (funcall stop-fn))
; do
(do ((k 1 (incf k)))
((or (= k steps) (if (functionp stop-fn) (funcall stop-fn))))
(if draw-rate
(setq start-time (get-internal-real-time)))
(incf (angle-of rot) increment)
(rotatef old-axes new-axes) (rotatef old-points new-points)
(mapply-transform-store rot data (append new-points new-axes))
(with-pen-values-restored c
(canvas-move-lines c old-points new-points
:color color :width width
:invisible? invisible?
:rgb-color? t :single-color? single-color?)
(canvas-set-pen c :color bg-color))
(with-pen-values-restored c
(canvas-move-symbols c old-points new-points :symbol psymbol
:color pcolor :fill? pfill? :size psize
:invisible? pinvisible?
:rgb-color? t :single-color? single-pcolor?)
(canvas-set-pen c :color bg-color)
)
(when axes
(with-pen-values-restored c
(canvas-move-axes c old-axes new-axes :color axis-color)
(canvas-set-pen c :color bg-color)))
(when draw-rate
(setq step-time (- (get-internal-real-time) start-time))
(if (< step-time draw-time)
(sleep (min 1 (/ (- draw-time step-time) internal-time-units-per-second))))))
(values rot new-points new-axes)
))) | 26,131 | Common Lisp | .l | 535 | 34.229907 | 107 | 0.525239 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | c1aff5a09faf6f1b95d7ddfe9dcf5e57631e8f68e42935383bd311e09700c1ea | 33,704 | [
-1
] |
33,705 | points-pc.lsp | rwoldford_Quail/source/window-basics/fast-graphics/points-pc.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; points-pc.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;; This file is an addition to Window-basics for moving pointclouds
;;;
;;; Authors:
;;; H.A. Chipman 1991
;;; C.B. Hurley 1991 George Washington University
;;; G.W. Bennett 1996
;;;
;;;
;;;----------------------------------------------------------------------------------
(in-package :wb)
(defun xor-draw-points (canvas points &key erase? &allow-other-keys)
"Draws or erases single pixel points ~
Results with color background are undefined."
(declare (special *black-color* *host-xor-mode*
cg::po-paint cg::po-replace cg::po-invert cg::po-erase)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(ignore erase? ))
(with-focused-canvas canvas
(h-draw::set-pen-mode canvas *host-xor-mode*)
(loop with h fixnum = (canvas-height canvas)
for (x y1) fixnum in points
for y fixnum = (- h y1)
do
(fast-draw-line canvas x y x y))))
(defun xor-move-points (canvas old new &key none &allow-other-keys )
"Moves single pixel points.~
Results with color background are undefined."
(declare (ignore none)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(special *host-xor-mode* cg::po-paint cg::po-replace cg::po-invert cg::po-erase))
(with-focused-canvas canvas
(h-draw::set-pen-mode canvas *host-xor-mode*)
(loop with h fixnum = (canvas-height canvas)
for (xo yo1 ) fixnum in old
for (x y1 ) fixnum in new
for yo fixnum = (- h yo1)
for y fixnum = (- h y1)
do
(cg::with-paint-operation
;(canvas cg::erase) 19oct05
(canvas cg::po-erase) ;19oct05
(cg::erase-line canvas (cg::make-position xo yo)
(cg::make-position xo yo))
)
;; (fast-draw-line canvas xo yo xo yo)
(fast-draw-line canvas x y x y)
)
))
(defun xor-draw-boxes (canvas points &key size erase?
&allow-other-keys)
"Draws or erases filled squares with varying size.~
Results with color background are undefined."
(declare (special *host-xor-mode*
cg::po-paint cg::po-replace cg::po-invert cg::po-erase)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(ignore erase? ))
(let* ((h (canvas-height canvas)))
(with-focused-canvas canvas
(h-draw::set-pen-mode canvas *host-xor-mode*)
(loop
for (x y ) fixnum in points for s fixnum in size
do
(cg::draw-box canvas (cg::make-box-from-corners
(cg::make-position x (- h y))
(cg::make-position (+ x s) (- h (- y s)))))
))))
(defun xor-move-boxes (canvas old new &key size (old-size size)
&allow-other-keys)
"Moves filled squares with varying size.~
Results with color background are undefined."
(declare (special *host-xor-mode*
cg::po-paint cg::po-replace cg::po-invert cg::po-erase)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(let* ((h (canvas-height canvas)))
;; (h-draw::with-rectangle-arg (r 0 0 1 1)
(with-focused-canvas canvas
(h-draw::set-pen-mode canvas *host-xor-mode*)
(loop for (xo yo ) fixnum in old
for (x y ) fixnum in new
for so fixnum in old-size
for s fixnum in size
do
(cg::with-paint-operation
;(canvas cg::erase )19oct05
(canvas cg::po-erase) ;19oct05
(cg::erase-box canvas (cg::make-box-from-corners
(cg::make-position xo (- h yo))
(cg::make-position (+ xo so) (- h (- yo so)))))
)
(cg::draw-box canvas (cg::make-box-from-corners
(cg::make-position x (- h y))
(cg::make-position (+ x s) (- h (- y s)))))
))))
(defun xor-draw-circles (canvas points &key size erase?
&allow-other-keys)
"Draws or erases filled circles with varying size.~
Results with color background are undefined."
(declare (special *host-xor-mode* fill?
cg::po-paint cg::po-replace cg::po-invert cg::po-erase)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(ignore erase? ))
(let* ((h (canvas-height canvas)))
(with-focused-canvas canvas
(h-draw::set-pen-mode canvas *host-xor-mode*)
(loop
for (x y ) fixnum in points for s fixnum in size
do
(fast-draw-circle canvas x (- h y) s fill?)
))))
(defun xor-move-circles (canvas old new &key size (old-size size)
&allow-other-keys)
"Moves filled circles with varying size.~
Results with color background are undefined."
(declare (special *host-xor-mode* fill?
cg::po-paint cg::po-replace cg::po-invert cg::po-erase)
(optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(let* ((h (canvas-height canvas)))
(h-draw::set-pen-mode canvas *host-xor-mode*)
(loop for (xo yo ) fixnum in old
for (x y ) fixnum in new
for so fixnum in old-size
for s fixnum in size
do
(cg::with-paint-operation
;(canvas cg::erase)19oct05
(canvas cg::po-erase) ;19oct05
(fast-erase-circle canvas xo (- h yo) so fill?)
)
(fast-draw-circle canvas x (- h y) s fill?)
)))
;; END of points-pc.lsp | 6,173 | Common Lisp | .l | 145 | 32.524138 | 88 | 0.523033 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 5531b00b2f37bf008f4ae4433f1798d2e5464669264f0d4f84af3d01b9182ba2 | 33,705 | [
-1
] |
33,707 | canvas-export-pc.lsp | rwoldford_Quail/source/window-basics/hardcopy/canvas-export-pc.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; canvas-export-pc.lsp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;;
;;; This file is part of the Window-Basics package intended to provide a uniform
;;; window environment for Common Lisp programming.
;;;
;;; For copyright information and history, see window-basics-copyright.lisp
;;;
;;; Authors:
;;; R.W. Oldford 1989-1991
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :wb)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(canvas-export)))
(defmethod canvas-export ((self canvas) &key left top width height filetype )
"Exports the canvas contents to a file of type filetype"
(declare (special the-array the-tex) ;28JUL2023
(ignore left top width height)) ; 07AUG2023
(unless filetype
(setf filetype (pick-one (list :postscript :bitmap))))
(case
filetype
(:postscript
(canvas-to-ps self))
(:bitmap
(let ((image-loc
(cg::ask-user-for-new-pathname
"Choose location for BITMAP image file:"
:initial-name "canvas.bmp"))
)
(cond (image-loc
(multiple-value-setq (the-array the-tex)
(cg::get-pixels self (cg::visible-box self)))
(apply #'cg::save-texture (list the-array the-tex image-loc))
)
(T
(format *terminal-io* "~&~%No bitmap image saved.~%"))
)))))
| 1,821 | Common Lisp | .l | 46 | 32.304348 | 87 | 0.481084 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 77a9cad7f3bf9fcc8cb64d155c1c1886f6b761da78f0022af41ed8e6c3ce2384 | 33,707 | [
-1
] |
33,709 | hardcopy-pc.lsp | rwoldford_Quail/source/window-basics/hardcopy/hardcopy-pc.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; hardcopy-pc.lsp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :wb)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(canvas-hardcopy hardcopy-bitmap)))
(defgeneric hardcopy-bitmap (bitmap &key left top width height)
(:documentation "Produces a hardcopy of the bitmap."))
(defgeneric canvas-hardcopy (canvas &key left top width height)
(:documentation "Produces a hardcopy of the canvas,~
or a selected region in canvas coordinates"))
(defmethod canvas-hardcopy ((self canvas) &key left top width height)
(case
(pick-one (list :postscript :printer))
(:postscript
(canvas-to-ps self))
(:printer
(if (or left top width height)
(hardcopy-bitmap self
:left left
:top top
:width width
:height height)
;; a mclism
(print-canvas self)))))
;;; For printing a selected rectangle of the canvas as a bitmap.
(defmethod hardcopy-bitmap ((w canvas) &key left top width height)
(setq left (or left 72))
(setq top (or top 72))
(setq width (or width (canvas-width w)))
(setq height (or height (canvas-height w)))
)
(defvar the-array nil) ; 07AUG2023
(defvar the-tex nil) ; 07AUG2923
(defun print-canvas (stuff)
"stuff is assumed to be a bitmap-window~
this merges output-to-window-or-printer and printer-test"
(declare (special cg::*screen*)) ;26SEP2023
(multiple-value-setq (the-array the-tex)
(cg::get-pixels stuff (cg::visible-box stuff)))
(setf (cg::texture-info-invert-p the-tex) T) ;; NOTE
(setf the-array (cg::reflect-pixel-map-in-y the-array)) ;; Added 100598 -- SEEMS OK
(let* ((printer-stream (cg::open-stream 'cg::printer 'cg::null-location :output))
(left-margin 20)
(top-margin 20)
(width (cg::texture-info-width the-tex))
(height (cg::texture-info-height the-tex))
)
(if printer-stream
(with-open-stream (stream printer-stream)
(setf (cg::stream-units-per-inch stream)
(round (* 0.85 (cg::stream-units-per-inch cg::*screen*))))
(cg::draw-box stream (cg::make-box left-margin
top-margin
(+ left-margin width)
(+ top-margin height)))
(setf (cg::stream-origin stream)
(cg::make-position (cg::left-margin stream t) (cg::top-margin stream t)))
(cg::copy-pixels-to-stream stream the-array
the-tex
(cg::make-box left-margin top-margin
(+ left-margin width)
(+ top-margin height))
(cg::make-box 0 0 width height)
cg::po-replace)
)
(error "Could not open printer")))
)
| 3,434 | Common Lisp | .l | 70 | 35.6 | 101 | 0.483562 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 59b69aa9c17df76ab5599f32c6b238c60cd781331a2607b4c60319a2cf80a0ba | 33,709 | [
-1
] |
33,710 | hardcopy-sblx.lsp | rwoldford_Quail/source/window-basics/hardcopy/hardcopy-sblx.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; hardcopy-sblx.lsp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :wb)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(canvas-hardcopy hardcopy-bitmap)))
(defgeneric hardcopy-bitmap (bitmap &key left top width height)
(:documentation "Produces a hardcopy of the bitmap."))
(defgeneric canvas-hardcopy (canvas &key left top width height)
(:documentation "Produces a hardcopy of the canvas,~
or a selected region in canvas coordinates"))
;;; These are called in menu-canvas.lsp
;;; right now they interfere with my attempts to make a canvas at all
;;; so I shall replace the method with stubs
(defmethod canvas-hardcopy ((self canvas) &key left top width height)
(declare (ignorable left top width height)) ;10MAY2024
NIL)
;;; In what follows I would have to write (pick-one (list (cons :ps nil) (cons :pr nil)))
;;; because of the way pick-one expects to get things and to return things
#|
(defmethod canvas-hardcopy ((self canvas) &key left top width height)
(case
(pick-one (list :postscript :printer))
(:postscript
(canvas-to-ps self))
(:printer
(if (or left top width height)
(hardcopy-bitmap self
:left left
:top top
:width width
:height height)
;; a mclism
(print-canvas self)))))
;;; For printing a selected rectangle of the canvas as a bitmap.
(defmethod hardcopy-bitmap ((w canvas) &key left top width height)
(setq left (or left 72))
(setq top (or top 72))
(setq width (or width (canvas-width w)))
(setq height (or height (canvas-height w)))
)
(defun print-canvas (stuff)
"stuff is assumed to be a bitmap-window~
this merges output-to-window-or-printer and printer-test"
(multiple-value-setq (the-array the-tex)
(cg::get-pixels stuff (cg::visible-box stuff)))
(setf (cg::texture-info-invert-p the-tex) T) ;; NOTE
(setf the-array (cg::reflect-pixel-map-in-y the-array)) ;; Added 100598 -- SEEMS OK
(let* ((printer-stream (cg::open-stream 'cg::printer 'cg::null-location :output))
(left-margin 20)
(top-margin 20)
(width (cg::texture-info-width the-tex))
(height (cg::texture-info-height the-tex))
)
(if printer-stream
(with-open-stream (stream printer-stream)
(setf (cg::stream-units-per-inch stream)
(round (* 0.85 (cg::stream-units-per-inch cg::*screen*))))
(cg::draw-box stream (cg::make-box left-margin
top-margin
(+ left-margin width)
(+ top-margin height)))
(setf (cg::stream-origin stream)
(cg::make-position (cg::left-margin stream t) (cg::top-margin stream t)))
(cg::copy-pixels-to-stream stream the-array
the-tex
(cg::make-box left-margin top-margin
(+ left-margin width)
(+ top-margin height))
(cg::make-box 0 0 width height)
cg::po-replace)
)
(error "Could not open printer")))
)
|#
| 3,708 | Common Lisp | .l | 77 | 36.766234 | 100 | 0.516147 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 6f79ca09e95800b79e94e19e5598f5cae64c4f7ba65bf22c65a6c5da25b4afa2 | 33,710 | [
-1
] |
33,711 | canvas-export-sblx.lsp | rwoldford_Quail/source/window-basics/hardcopy/canvas-export-sblx.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; canvas-export-sblx.lsp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;;
;;; This file is part of the Window-Basics package intended to provide a uniform
;;; window environment for Common Lisp programming.
;;;
;;; For copyright information and history, see window-basics-copyright.lisp
;;;
;;; Authors:
;;; R.W. Oldford 1989-1991
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :wb)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(canvas-export)))
;;; Until I get a handle on making a canvas,
;;; the call to this in menu-canvas messes things up.
;;; Hence the stub
(defmethod canvas-export ((self canvas) &key left top width height filetype)
(declare (ignorable self left top width height filetype)) ;10MAY2024
NIL)
#|
(defmethod canvas-export ((self canvas) &key left top width height filetype )
"Exports the canvas contents to a file of type filetype"
(unless filetype
(setf filetype (pick-one (list :postscript :bitmap))))
(case
filetype
(:postscript
(canvas-to-ps self))
(:bitmap
(let ((image-loc
(cg::ask-user-for-new-pathname
"Choose location for BITMAP image file:"
:initial-name "canvas.bmp"))
)
(cond (image-loc
(multiple-value-setq (the-array the-tex)
(cg::get-pixels self (cg::visible-box self)))
(apply #'cg::save-texture (list the-array the-tex image-loc))
)
(T
(format *terminal-io* "~&~%No bitmap image saved.~%"))
)))))
|# | 1,947 | Common Lisp | .l | 52 | 32.019231 | 86 | 0.51981 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 2f91532f138b6904f185c56d3428e89455b7d93b34990047844be43a4c8edd8d | 33,711 | [
-1
] |
33,714 | window-basics-copyright.lsp | rwoldford_Quail/source/window-basics/startup/window-basics-copyright.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; window-basics-copyright.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Window-basics package
;;; Copyright (c) 1988-1991 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; This file is part of the Window-Basics package intended to provide a uniform
;;; window environment for Common Lisp programming.
;;;
;;; The basic window is called a canvas here and most functions are prefixed with
;;; canvas- to distinguish them from underlying CL vendor names.
;;;
;;; The system is intended to be replaced at some future date when a windowing
;;; standard for Common Lisp systems is agreed upon. Until that happy time,
;;; window-basics exists.
;;;
;;; The first instantiation of canvases et cetera was done at
;;; the University of Washington - UW - and Xerox PARC by John McDonald and
;;; Jan Pedersen (respectively). Ports included Coral CL on Macs, CL on Symbolics
;;; and Connection Machines.
;;;
;;; In May 1989, a copy of the code was moved to the University of Waterloo - U(W)
;;; where it was turned into the window-basics package and further extended by
;;; Wayne Oldford and Catherine Hurley.
;;;
;;; Since then, the window-basics packages has undergone continuous development
;;; and extension. The author list is therefore quite long.
;;;
;;; Rather than attribute specific files and code to different people, all names
;;; are mentioned on all files. (At this late juncture it would be impossible
;;; to do otherwise.)
;;;
;;; For the window-basics system the copyright at the top of this file is meant
;;; to simplify contact with a central "authority". Feel free to use the system
;;; at your leisure. No warranty, etc., expressed or implied.
;;;
;;; Authors:
;;; C.B. Hurley 1989-1991
;;; J.A. McDonald 1988-89
;;; R.W. Oldford 1989-1991
;;; J.O. Pedersen 1988-89
;;;
;;;
;;;
;;;---------------------------------------------------------------------------------- | 2,168 | Common Lisp | .l | 49 | 42.020408 | 86 | 0.607075 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 5239507e68c73514ac4c6efaf0adcd6fd7ae726bdf71a749456c9d4c2afdfa93 | 33,714 | [
-1
] |
33,715 | debug.lsp | rwoldford_Quail/source/window-basics/startup/debug.lsp | (in-package :wb)
(defvar *debug-print-flag* NIL)
(defmacro *debug-print* (string)
(declare (special *debug-print-flag*))
(if *debug-print-flag*
`(quail-print ,string)))
#|
(defun *debug-print* (string)
(declare (special *debug-print-flag*))
(if *debug-print-flag*
(quail-print string)))
|#
| 324 | Common Lisp | .l | 12 | 23.166667 | 41 | 0.641935 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | efff6386bc67e090ce61f52e2e6eea644b9b37eb5536d1f53394ac24daddb72f | 33,715 | [
-1
] |
33,716 | restore.lsp | rwoldford_Quail/source/window-basics/startup/restore.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; restore.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1990 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1991.
;;;
;;;
;;;--------------------------------------------------------------------------------
(in-package :window-basics)
(eval-when (:compile-toplevel :load-toplevel :execute)
(import '(quail-kernel:add-restore-lisp-functions)))
;--------------------------------------------------------------------------------
#| Following is unnecessary unless the quail-kernel package is not loaded.
(defparameter *window-basics-restore-lisp-functions* nil)
(defun window-basics-restore ()
(mapcar #'funcall *window-basics-restore-lisp-functions*))
(defun add-restore-lisp-functions (&rest functions)
"Adds the given quail lisp functions to the set that will be ~
restored when the current image is restarted."
(setf *window-basics-restore-lisp-functions*
(append *window-basics-restore-lisp-functions* functions)))
|#
| 1,258 | Common Lisp | .l | 29 | 39.137931 | 84 | 0.481451 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 3413f632ca3d6ff945ffd2144c493082f335248098a592bf6ce39f05f1fed615 | 33,716 | [
-1
] |
33,717 | new-math-package.lsp | rwoldford_Quail/source/new-math/new-math-package.lsp | ;;; -*- MODE: LISP; SYNTAX: COMMON-LISP -*-
;;; NEW-MATH-PACKAGE.LISP
;;; COPYRIGHT, 1991, STATISTICAL COMPUTING LABORATORY, UNIVERSITY OF WATERLOO
(DEFPACKAGE "NEW-MATH"
#+:sbcl-linux (:USE :clim :clim-lisp :clim-extensions) ;"COMMON-LISP") ;19November 2019
#+:aclpc-linix (:USE :common-lisp)
(:SHADOWING-IMPORT-FROM "QUAIL-KERNEL"
"ARRAY-ELEMENT-TYPE"
"ARRAY-RANK"
"ARRAY-DIMENSION"
"ARRAY-DIMENSIONS"
"ARRAY-TOTAL-SIZE"
"ARRAY-IN-BOUNDS-P"
"ADJUSTABLE-ARRAY-P"
"ARRAY-ROW-MAJOR-INDEX"
"SORT")
(:IMPORT-FROM "QUAIL-KERNEL"
"DIMENSIONED-REF-OBJECT" ;;22JAN2020
"MATRIX" ;;22JAN2020
"SEQ-DIFFERENCE" ;;22JAN2020
"DEFMETHOD-MULTI"
"EXT_+"
"EXT_*"
"EXT_-"
"EXT_/"
"EXT_>"
"EXT_<"
"EXT_="
"EXT_<="
"EXT_>="
"EXT_MAX"
"EXT_MIN"
"EXT_EXP"
"EXT_SQRT"
"EXT_EXP"
"EXT_SQRT"
"EXT_ISQRT"
"EXT_ABS"
"EXT_PHASE"
"EXT_SIGNUM"
"EXT_SIN"
"EXT_COS"
"EXT_TAN"
"EXT_CIS"
"EXT_ASIN"
"EXT_ACOS"
"EXT_ATAN"
"EXT_SINH"
"EXT_COSH"
"EXT_TANH"
"EXT_ASINH"
"EXT_ACOSH"
"EXT_ATANH"
;; "EXT_RATIONALIZE"
;; "EXT_RATIONAL"
;; "EXT_FLOAT"
"EXT_NUMERATOR"
"EXT_DENOMINATOR"
"EXT_REALPART"
"EXT_IMAGPART"
"EXT_FLOOR"
"EXT_CEILING"
"EXT_TRUNCATE"
"EXT_ROUND"
"EXT_FFLOOR"
"EXT_FCEILING"
"EXT_FTRUNCATE"
"EXT_FROUND"
;; "EXT_COMPLEX"
"EXT_EXPT"
"EXT_LOG"
"EXT_REM"
"EXT_MOD"
"EXT_GCD"
"EXT_LCM"
"EXT_CONJUGATE"
;;"GET-LAMBDA-LIST"
"MAP-ELEMENT" ;; 03FEB2020
"+INFINITY" ;;07APR2020
"INFINITY" ;;07APR2020
"-INFINITY" ;; 07APR2020
"EREF" ;; 12JAN2021
"MATRIX-DIMENSIONS-OF" ;; 12JAN2021
"MISSING-METHOD" ;; 12JAN2021
"NUMBER-OF-ELEMENTS" ;; 12JAN2021
"REDUCE-SLICES" ;; 12JAN2021
)
(:SHADOW
"+" "-" "*" "/"
"FLOAT" "RATIONAL"
"RATIONALIZE"
"<" "<=" "=" ">" ">=" "MIN" "MAX" "EXP" "SQRT" "ISQRT"
"ABS" "PHASE" "SIGNUM" "SIN" "COS" "TAN" "CIS" "ASIN" "ACOS" "ATAN"
"SINH" "COSH" "TANH" "ASINH" "ACOSH" "ATANH"
"NUMERATOR"
"DENOMINATOR" "REALPART" "IMAGPART" "FLOOR" "CEILING" "TRUNCATE" "ROUND"
"FFLOOR" "FCEILING" "FTRUNCATE" "FROUND" "COMPLEX" "EXPT" "LOG" "REM" "MOD"
"GCD" "LCM" "CONJUGATE"
"LOGIOR" "LOGXOR" "LOGAND" "LOGEQV" "LOGNAND" "LOGNOR" "LOGANDC1" "LOGANDC2"
"LOGORC1""LOGORC2" "LOGNOT" "LOGTEST" "LOGBITP" "ASH" "LOGCOUNT" "INTEGER-LENGTH"
"BOOLE")
(:EXPORT
"+" "-" "*" "/"
"FLOAT" "RATIONAL"
"RATIONALIZE"
"<" "<=" "=" ">" ">=" "MIN" "MAX" "EXP" "SQRT" "ISQRT"
"ABS" "PHASE" "SIGNUM" "SIN" "COS" "TAN" "CIS" "ASIN" "ACOS" "ATAN"
"SINH" "COSH" "TANH" "ASINH" "ACOSH" "ATANH" "NUMERATOR"
"DENOMINATOR" "REALPART" "IMAGPART" "FLOOR" "CEILING" "TRUNCATE" "ROUND"
"FFLOOR" "FCEILING" "FTRUNCATE" "FROUND" "COMPLEX" "EXPT" "LOG" "REM" "MOD"
"GCD" "LCM" "CONJUGATE"
"LOGIOR" "LOGXOR" "LOGAND" "LOGEQV" "LOGNAND" "LOGNOR" "LOGANDC1" "LOGANDC2"
"LOGORC1""LOGORC2" "LOGNOT" "LOGTEST" "LOGBITP" "ASH" "LOGCOUNT" "INTEGER-LENGTH"
"BOOLE"))
| 4,123 | Common Lisp | .l | 114 | 22.824561 | 89 | 0.441243 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 3801bfc35216283158ebcbd90d0078612e9bf3839f9f95a3084811f06db85f67 | 33,717 | [
-1
] |
33,718 | num-array-math.lsp | rwoldford_Quail/source/new-math/num-array-math.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; num-array-math.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1990 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; Greg Anglin 1989, 1990, 1991.
;;;
;;;
;;;--------------------------------------------------------------------------------
;;;
;;; Includes:
;;; (see export)
;;;
(in-package :quail-kernel)
;;; This file creates methods for num-arrays which call extended ops directly
;;; when we are sure that both arguments are numeric.
;------------------------------------------------------------------------------
#|
;;; All of these operators used to have a method like this. They differ from
;;; the ones for specialization of b as dimensioned-ref-object by doing
;;;
;;; (setf (ref result) (sel b))
;;;
;;; rather than just
;;;
;;; (setf (ref result) b).
;;;
;;; I can't figure why the sel was there, so I just left these methods out,
;;; thereby inheriting from dimensioned-ref-object ... dga 91 07 16
(defmethod plus-object ((a (eql :identity)) (b num-array))
(let ((result (make-dimensioned-result (dimensions-of b) b)))
(setf (ref result) (sel b)).
result))
|#
;------------------------------------------------------------------------------
(defmethod-multi plus-object ((a (symbol number num-array))
(b num-array))
(map-element #'ext_+ nil a b))
(defmethod-multi plus-object ((a num-array)
(b (symbol number)))
(map-element #'ext_+ nil a b))
;------------------------------------------------------------------------------
(defmethod-multi minus-object ((a (symbol number num-array))
(b num-array))
(map-element #'ext_- nil a b))
(defmethod-multi minus-object ((a num-array)
(b (symbol number)))
(map-element #'ext_- nil a b))
;------------------------------------------------------------------------------
(defmethod-multi times-object ((a (symbol number num-array))
(b num-array))
(map-element #'ext_* nil a b))
(defmethod-multi times-object ((a num-array)
(b (symbol number)))
(map-element #'ext_* nil a b))
;------------------------------------------------------------------------------
(defmethod-multi divides-object ((a (symbol number num-array))
(b num-array))
(map-element #'ext_/ nil a b))
(defmethod-multi divides-object ((a num-array)
(b (symbol number)))
(map-element #'ext_/ nil a b))
| 3,084 | Common Lisp | .l | 68 | 35.235294 | 85 | 0.434396 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 39df34d2c2ed530fc1319abd75b4c932ac948082e074dfbf8d1c6202c81a7c92 | 33,718 | [
-1
] |
33,719 | init-new-math.lsp | rwoldford_Quail/source/new-math/init-new-math.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; init-new-math.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (C) 1990 Statistical Computing Laboratory, University Of Waterloo
;;;
;;;
;;; Authors:
;;; Greg Anglin 1989, 1990.
;;; R.W. Oldford 1989, 1990, 1994
;;; M.E. Lewis 1991.
;;;
;;;--------------------------------------------------------------------------------
(in-package :new-math)
;;;-----------------------------------------------------------------------
;;; Gives the "Quail meaning" to all those Common Lisp functions
;;; reimplemented using map-element. They are listed in new-math.lisp.
(defmacro make-extended-quail-function (function-name)
"Generalizes the function named, using map-element."
(let* ((cl-function-name (find-symbol (string function-name)
(string-upcase "cl")))
(lambda-list (qk::get-lambda-list cl-function-name))
(pruned-lambda-list
(seq-difference lambda-list
'(&OTHER-LAMBDA-KEYS
&ENVIRONMENT
&BODY
&WHOLE
&ALLOW-OTHER-KEYS
&AUX
&OPTIONAL
&KEY
&REST
&REQUIRED))))
;(format t "~%cl-function-name is ~s of type ~s " cl-function-name (type-of cl-function-name))
(if (intersection '(&REST &BODY) lambda-list)
`(defun ,function-name ,lambda-list
(apply #'map-element
#',(make-name "ext_" function-name)
nil
,@pruned-lambda-list) )
`(defun ,function-name ,lambda-list
(map-element
#',(make-name "ext_" function-name)
nil
,@pruned-lambda-list)))))
(defmacro make-simple-quail-function (function-name)
"Generalizes the function named, using map-element."
(let* ((cl-function-name (find-symbol (string function-name)
(string-upcase "cl")))
(lambda-list (qk::get-lambda-list cl-function-name))
(pruned-lambda-list
(seq-difference lambda-list
'(&OTHER-LAMBDA-KEYS
&ENVIRONMENT
&BODY
&WHOLE
&ALLOW-OTHER-KEYS
&AUX
&OPTIONAL
&KEY
&REST
&REQUIRED))))
(cond
((intersection '(&REST &BODY) lambda-list)
`(defun ,function-name ,lambda-list
(apply #'map-element
#',cl-function-name
nil
,@pruned-lambda-list))
)
((intersection '(&OPTIONAL) lambda-list)
(let ((optional (second (member '&OPTIONAL lambda-list)))
(required-args (butlast pruned-lambda-list)))
`(defun ,function-name ,lambda-list
(if ,optional
(map-element
#',cl-function-name
nil
,@pruned-lambda-list)
(map-element
#',cl-function-name
nil
,@required-args)))))
(T
`(defun ,function-name ,lambda-list
(map-element
#',cl-function-name
nil
,@pruned-lambda-list))))))
(eval-when (:load-toplevel :execute);(eval load) 12JAN2021
"Redefines all the *logical-numerical-ops*."
(dolist (fn *logical-numerical-ops*)
(eval `(make-simple-quail-function ,fn))
(setf (documentation fn 'function)
(documentation
(find-symbol (symbol-name fn)
:cl)
'function))
)
(dolist (fn *numerical-type-coercion-functions*)
(eval `(make-simple-quail-function ,fn))
(setf (documentation fn 'function)
(documentation
(find-symbol (symbol-name fn)
:cl)
'function))
)
(dolist (fn *extended-simple-functions*)
(eval `(make-extended-quail-function ,fn))
(setf (documentation fn 'function)
(documentation
(find-symbol (symbol-name fn)
:cl)
'function))
)
;; the functions float and rational must
;; preserve their meaning as data types.
(deftype float ()
`(satisfies cl:floatp))
(deftype rational ()
`(satisfies cl:rationalp)))
| 4,911 | Common Lisp | .l | 125 | 25.6 | 97 | 0.45034 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 83d9109f6c0d8382a8b800ec2132c9b954799682aa6a8727622d88705db14c7e | 33,719 | [
-1
] |
33,720 | eg-glm-car.lsp | rwoldford_Quail/source/statistics/models/eg-glm-car.lsp | (in-package q-user)
;; *********** GAMMA FAMILY with RECIPROCAL LINK ***********
;; See McCullagh and Nelder, Generalized Linear Models, 2nd ed.
;; This dataset and an analysis is given in section 8.4.1.
(set-quail-data-directory (probe-file "q:examples;statistics;models;"))
;; to undo: (set-quail-data-directory nil :reset t)
(load (quail-file-pathname "full-factorial-design.lisp"))
;; car insurance data
;; column 0 is the average amount of claims
;; column 1 is the corresponding number of claims
(setf cars-data (array (scan "car insurance data")
:dimensions '(t 2)))
(setf vehicle-age '("0-3" "4-7" "8-9" "10+"))
(setf policy-holder-age '("17-20" "21-24" "25-29" "30-34"
"35-39" "40-49" "50-59" "60+"))
(setf car-group '(a b c d))
(setf car-cov (full-factorial-design vehicle-age
policy-holder-age
car-group))
;; when the number of claims, which are used as weights, is zero, then
;; the term will be automatically dropped from the likelihood
(setf cars-dat (data-frame (list (array (ref car-cov t 0)
:class 'factor-array
:levels vehicle-age)
(array (ref car-cov t 1)
:class 'factor-array
:levels policy-holder-age)
(array (ref car-cov t 2)
:class 'factor-array
:levels car-group)
(ref cars-data t 0)
(ref cars-data t 1))
(list "v_age"
"ph_age"
"group"
"amount"
"number")))
(setf c0 (glm "amount ~ 1"
cars-dat
:family :gamma
:link :reciprocal
:weight (eref cars-dat "number")
:tolerance 1e-3))
(display c0)
(setf c1 (glm "amount ~ v_age + ph_age + group"
cars-dat
:family :gamma
:link :reciprocal
:weight (eref cars-dat "number")
:tolerance 1e-3))
(display c1)
;; next is a lengthy process if you've got less than about 16 Meg
;; of real RAM ... enjoy your coffee.
;;
;; [ We haven't exactly optimized any code, yet. :-) ]
(setf c2 (glm "amount ~ v_age * ph_age * group - v_age . ph_age . group"
cars-dat
:family :gamma
:link :reciprocal
:weight (eref cars-dat "number")
:tolerance 1e-3))
| 2,858 | Common Lisp | .l | 61 | 30.163934 | 73 | 0.469801 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | c8b4fb6ba6edf78ef2b9b677130ac30de41833d9abf443c762a9587b100d58ae | 33,720 | [
-1
] |
33,721 | contrasts.lsp | rwoldford_Quail/source/statistics/models/contrasts.lsp | (in-package :quail)
(defun contrasts (x &optional (method :default))
(calc-contrasts x method))
(defmethod calc-contrasts ((x matrix) (method (eql :default)))
x)
(defmethod calc-contrasts ((x factor-object) (method (eql :default)))
(calc-contrasts x :helmert))
(defmethod calc-contrasts ((x factor-object) (method (eql :helmert)))
(let* ((num-levels (first (dimensions-of (levels-of x))))
(contrasts (array :empty
:dimensions (list num-levels (- num-levels 1)))))
; (loop for i from 0 to (- num-levels 1) do
(do ((i 0 (incf i)))
((= i num-levels))
(progn
; (loop for j from 0 to (- i 2) do
(do ((j 0 (incf j)))
((> j (- i 2)))
(setf (eref contrasts i j) 0))
(if (> i 0) (setf (eref contrasts i (- i 1)) i))
; (loop for j from i to (- num-levels 2) do
(do ((j i (incf j)))
((> j (- num-levels 2)))
(setf (eref contrasts i j) -1))))
contrasts))
(defmethod calc-contrasts ((x ordinal-factor) (method (eql :default)))
(calc-contrasts x :poly))
(defmethod calc-contrasts ((x ordinal-factor) (method (eql :poly)))
(warn "calc-contrasts :poly not implemented yet ... using :helmert")
(calc-contrasts x :helmert))
| 1,345 | Common Lisp | .l | 30 | 35.866667 | 78 | 0.56985 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 302e6527bb327a9fa5fb0691900efede76d7475c1312601ad1a8fb90d6079a87 | 33,721 | [
-1
] |
33,722 | linear-model.lsp | rwoldford_Quail/source/statistics/models/linear-model.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; linear-model.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1992 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; Greg Anglin 1992.
;;; R.W. Oldford 1993, 1995
;;;
;;;--------------------------------------------------------------------------------
;;;
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(linear-model linear-model-fit
gaussian-linear-model gaussian-linear-model-fit
lm)))
(defclass linear-model (generalized-linear-model additive-model)
()
(:documentation
"As a subclass of both generalized-linear-model and additive-model, ~
this class has the link restricted to be the identity and the formula ~
restricted to be linear."))
(defclass gaussian-linear-model (linear-model)
((family :accessor family-of
:initarg :family
:initform gaussian-family
:allocation :class))
(:documentation
"In this class the family is restricted to be Gaussian (Normal)."))
(defclass linear-model-fit (generalized-linear-model-fit
additive-model-fit)
())
(defclass gaussian-linear-model-fit (linear-model-fit)
((qr-solution :accessor qr-solution-of
:initarg qr-solution
:initform NIL
:documentation "Contains an instance of a qr-solution ~
which in turn contains all the qr decomposition ~
information relevant to the least-squares fit.")
)
(:documentation "The result of fitting a Gausian linear model."))
(defmethod fit-class ((model linear-model)
(data data-frame)
(method (eql :maximum-likelihood)))
'linear-model-fit)
(defmethod-multi fit-class ((model gaussian-linear-model)
(data data-frame)
(method ((eql :least-squares)
(eql :maximum-likelihood))))
'gaussian-linear-model-fit)
(defun lm (model-formula
data-frame
&rest keys
&key
(family gaussian-family)
(methodology :least-squares)
weight
(tolerance 1e-7)
&allow-other-keys)
(declare (ignore tolerance weight methodology))
;; the following is now handled in fit ... rwo
;;(when (not (typep data-frame 'data-frame))
;; (setf data-frame (data-frame data-frame
;; (copy-list (list-variates data-frame))))
(let (model)
(setf model (if (eq family gaussian-family)
(model 'gaussian-linear-model
model-formula)
(model 'linear-model
model-formula)))
(apply #'fit
model
data-frame
:resid t
:coef t
:pred t
:qy t
:qty t
keys
)
;; returns fit
))
(defmethod fit-using-methodology ((model gaussian-linear-model)
(data data-frame)
(methodology (eql :least-squares))
&rest keys
&key
fit-object
weight
tolerance coef resid pred qy qty
&allow-other-keys)
(declare (ignore weight tolerance coef resid pred qy qty))
(if (not fit-object)
(setf fit-object (apply #'fit-instantiate
model
data
methodology
keys)))
(apply #'lsfit fit-object :pivot t :resid t keys)
;;
;; cheat here and dodge the overhead of #'deviance
;;
(with-slots (deviance resid weight) fit-object
(setf deviance (.* (tp resid) (* weight resid))))
fit-object)
(defmethod fit-using-methodology ((model gaussian-linear-model)
(data data-frame)
(methodology (eql :maximum-likelihood))
&rest keys
&key
&allow-other-keys)
(apply #'fit-using-methodology model data :least-squares keys))
(defmethod-multi compute-residuals ((fit-obj gaussian-linear-model-fit)
(type ((eql :default)
(eql :response)))
&key)
;; the fit method for these fit-objs is assumed to have filled resid ...
(with-slots
(resid)
fit-obj
resid))
| 5,068 | Common Lisp | .l | 125 | 27.024 | 96 | 0.480757 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 9af9b89b6cc7919541870cf6f1f01a7295f7d8ff4e58d1811844eb5411998886 | 33,722 | [
-1
] |
33,723 | fit.lsp | rwoldford_Quail/source/statistics/models/fit.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; fit.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1992 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; Greg Anglin 1992-94.
;;; ... rwo 95
;;;
;;;--------------------------------------------------------------------------------
;;;
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(fit-object response-model-fit fit
fit-using-methodology fit-instantiate fit-class)))
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(model-of data-frame-of model-frame-of model-matrix-of response-matrix-of
model-degrees-of-freedom-of weight-of coef-of resid-of pred-of deviance-of)))
(defclass fit-object (quail-object)
((model :accessor model-of :initarg :model
:documentation "The model-object which was fitted.")
(data :accessor data-of :initarg :data
:documentation "The data to which the model was fitted"))
(:documentation
"The abstract class at the top of the hierarchy of fitted model ~
objects. ~
(:see-also ~
(fit-object :class) ~
(fit :generic-function) ~
(fit-class :generic-function) ~
(fit-instantiate :generic-function) ~
) ~
")
)
(defmethod formula-of ((self fit-object))
(formula-of (model-of self)))
;;; there's probably too much junk on this class.
(defclass response-model-fit (fit-object)
((model-frame :accessor model-frame-of :initarg :model-frame
:documentation
"A model-frame built from the model and data ~
which were given to fit.")
(model-matrix :accessor model-matrix-of :initform nil
:documentation
"A numerical model-matrix of predictors built from model-frame.")
(response-matrix :accessor response-matrix-of :initform nil
:documentation
"A numerical matrix of the response built from model-frame.")
;;(rank ;; see defmethods below :accessor rank-of
;; :documentation "The rank of model-matrix")
(model-degrees-of-freedom
:accessor model-degrees-of-freedom-of
:documentation "The degrees of freedom for the model ~
(i.e. the column rank of the model-matrix).")
(weight :accessor weight-of :initarg :weight
:documentation "Vector of initial weights for observations.")
(coef :initform nil :accessor coef-of
:documentation "Vector of fitted coefficients.")
(resid :initform nil :accessor resid-of
:documentation "Residual vector.")
(pred :initform nil :accessor pred-of
:documentation "The fitted values of the response at each ~
predictor-vector under the model.")
(deviance :accessor deviance-of
:documentation "The deviance of the fitted model."))
(:documentation
"The class of fitted model objects for models ~
which have a response separable from predictors. ~
In practice, only particular subclasses of response-model-fit ~
are instantiated."))
#|
(defmethod rank-of ((thing response-model-fit) &key &allow-other-keys)
"The rank of the model-matrix."
(slot-value thing 'rank))
(defmethod (setf rank-of) (new-value
(thing response-model-fit)
&key &allow-other-keys)
"Set the rank of the model-matrix."
(setf (slot-value thing 'rank) new-value))
|#
(defmethod data-frame-of ((fit response-model-fit))
"An alternative accessor to the data on a fitted response model object, ~
for which objects the data is usually of class data-frame."
(data-of fit))
(defmethod (setf data-frame-of) (new-value (fit response-model-fit))
"An alternative accessor to the data on a fitted response model object, ~
for which objects the data is usually of class data-frame."
(setf (data-of fit) new-value))
(defgeneric fit-class (model data methodology)
(:documentation
"Returns the class of a fitted model object ~
suitable for use with model when fitting by technique specified by methodology. ~
The class may be returned as a class or a symbol naming a class. ~
(:required ~
(:arg model An instance of a subclass of model-object) ~
(:arg data An instance of a subclass of data-object) ~
(:arg methodology A specification of a methodology for fitting ~
(usually a keyword such as :maximum-likelihood or :least-squares)) ~
)~
(:see-also ~
(fit-object :class) ~
(fit :generic-function) ~
(fit-using-methodology :generic-function) ~
(fit-instantiate :generic-function) ~
) ~
")
)
(defmethod fit-class ((model model-object) (data data-object) (methodology t))
"The default fit-class method ... should never really be used in practice."
'fit-object)
(defmethod fit-class ((model response-model) (data data-object) (methodology t))
"The fit-class method for response-model in general ... probably will never ~
be used in practice."
'response-model-fit)
(defgeneric fit-instantiate (model
data
methodology
&rest keys
&key
&allow-other-keys)
(:documentation
"Makes and initializes an instance of a subclass ~
of fit-object to represent the fit of ~
model to data by methodology. ~
fit-instantiate is usually called by fit-using-methodology, but may also ~
be called in advance of fit-using-methodology. ~
(:required ~
(:arg model An instance of a subclass of model-object) ~
(:arg data An instance of a subclass of data-object) ~
(:arg methodology A specification of a methodology for fitting ~
(usually a keyword such as :maximum-likelihood or :least-squares)) ~
) ~
(:see-also ~
(fit-object :class) ~
(fit :generic-function) ~
(fit-using-methodology :generic-function) ~
(fit-class :generic-function) ~
) ~
")
)
(defmethod fit-instantiate ((model response-model)
(data data-frame)
(methodology t)
&rest keys
&key
(model-matrix nil model-matrix-provided-p)
(model-frame nil model-frame-provided-p)
relevant-model-matrix
&allow-other-keys)
"fit-instantiate method for (response-model data-frame t). ~
(:elaboration Calls fit-class to obtain the ~
appropriate subclass of fit-object, ~
makes an instance of it using model, data, and initargs, ~
and then calls compute-model-matrix ~
to initialize.) ~
(:required ~
(:arg model An instance of a subclass of model-object) ~
(:arg data An instance of a subclass of data-object) ~
(:arg methodology A specification of a methodology for fitting ~
(usually a keyword such as :maximum-likelihood or :least-squares)) ~
)"
(setf model-frame (if model-frame-provided-p
model-frame
(model-frame (formula-of model)
data)))
(let* ((class (fit-class model data methodology))
(fit
(apply #'make-instance
class
:model model
:data data
:model-frame model-frame
(qk::remove-illegal-make-instance-initargs class keys))))
(if model-matrix-provided-p
(setf (model-matrix-of fit) model-matrix)
(compute-model-matrix fit relevant-model-matrix) ;; do degrees of freedom, too.
)
fit))
(defgeneric fit (model data
&rest keys
&key methodology tolerance fit-object
&allow-other-keys)
(:documentation
"Performs a fit of model to data, producing a fit-object. ~
(:elaboration ~
Usually implemented as a call to fit-using-methodology, viz. ~
(apply #'fit-using-methodology model data methodology keys). ~
The default for methodology is :default, which must be handled by ~
fit-using-methodology.) ~
(:required ~
(:arg model An instance of a subclass of model-object) ~
(:arg data An instance of a subclass of data-object) ~
) ~
(:keys ~
(:arg methodology :default A specification of a methodology for fitting ~
(usually a keyword such as :maximum-likelihood or :least-squares)) ~
(:arg tolerance nil The tolerance to use in assessing convergence) ~
(:arg fit-object nil If present, a previously created fit-object for ~
(these specific instances of) model and data) ~
) ~
(:allow-other-keys)
(:see-also ~
(fit-object :class) ~
(fit-using-methodology :generic-function) ~
(fit-class :generic-function) ~
(fit-instantiate :generic-function) ~
) ~
")
)
(defmethod fit ((model model-object) (data T)
&rest keys
&key (methodology :default)
&allow-other-keys)
"The method for fit to be used when the data is not of class data-object."
(let* ((variates (list-variates data))
(data-frame (data-frame data (copy-list variates)))
)
(dataset data-frame :variates variates :identifiers (list-identifiers data))
(apply #'fit-using-methodology model data-frame methodology keys))
)
(defmethod fit ((model model-object) (data data-object)
&rest keys
&key (methodology :default)
&allow-other-keys)
"The default method for fit which simply does ~
(apply #'fit-using-methodology model data methodology keys)."
(apply #'fit-using-methodology model data methodology keys))
(defmethod fit ((model (eql t)) (data (eql t))
&rest keys
&key fit-object
&allow-other-keys)
"A method for fit which allows fit to be called with model==T and ~
data==T, so long as fit-object is provided."
(if fit-object
(apply #'fit
(model-of fit-object)
(data-of fit-object)
keys)
(error "Can't fit model ~S to data ~S with fit-object ~S."
model data fit-object)))
(defgeneric fit-using-methodology
(model data methodology &rest keys
&key tolerance fit-object &allow-other-keys)
(:documentation
"Performs a fit of model to data by methodology, producing a fit-object. ~
(:elaboration ~
Implementors may need to provide a method for a specific model and data ~
class and (methodology (eql :default)), which redispatches to ~
fit-using-methodology with a default appropriate for that model and data. ~
The default is to redispatch with methodology set to :maximum-likelihood. ~
If fit-object is NIL or not provided, a new fit-object instance is ~
created by fit-instantiate, and will have class as returned by fit-class. ~
If fit-object is provided, it must be an instance previously created by fit-instantiate ~
called with these specific instances of model, data, and methodology (where ~
methodology is by now something other than :default).) ~
(:required ~
(:arg model An instance of a subclass of model-object) ~
(:arg data An instance of a subclass of data-object) ~
(:arg methodology A specification of a methodology for fitting ~
(usually a keyword such as :maximum-likelihood or :least-squares)) ~
) ~
(:keys ~
(:arg methodology :ignored This keyword is often passed from fit, ~
but is ignored by fit-using-methodology) ~
(:arg tolerance nil The tolerance to use in assessing convergence) ~
(:arg fit-object nil If present, a previously created fit-object for ~
(these specific instances of) model and data) ~
) ~
(:allow-other-keys) ~
(:see-also ~
(fit-object :class) ~
(fit :generic-function) ~
(fit-class :generic-function) ~
(fit-instantiate :generic-function) ~
) ~
")
)
(defmethod fit-using-methodology ((model model-object)
(data data-object)
(methodology (eql :default))
&rest keys
&key
&allow-other-keys)
"The default method for fit which simply does ~
(apply #'fit-using-methodology model data :maximum-likelihood keys)."
(apply #'fit-using-methodology model data :maximum-likelihood keys))
| 12,976 | Common Lisp | .l | 289 | 35.899654 | 138 | 0.61261 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 62f6e1cc629b34b28a349cd4ba9d474a0e9ebb0a236d0e425ed25e5fa9f91e07 | 33,723 | [
-1
] |
33,724 | model-matrix.lsp | rwoldford_Quail/source/statistics/models/model-matrix.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; model-matrix.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1992 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; Greg Anglin 1992.
;;; R.W. Oldford 1995.
;;;
;;;--------------------------------------------------------------------------------
;;;
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(model-matrix)))
;; a first shot at creating a model matrix from the model frame
(defclass model-matrix (matrix)
((formula :accessor formula-of :initarg :formula
:documentation "an object of class formula.")
(predictor-columns :accessor predictor-columns-of
:initform nil)
(factor-contrasts :accessor factor-contrasts-of :initform nil)))
(defmethod compute-model-matrix ((fit response-model-fit) relevant-model-matrix)
(with-slots
(model model-frame model-matrix response-matrix)
fit
(let ((identifiers (list-identifiers model-frame)))
(with-slots (formula) model
(setf response-matrix (eref model-frame (response-of formula)))
(dataset response-matrix
:identifiers identifiers
:variates (list (response-of formula)))
(setf model-matrix (make-instance 'model-matrix :formula formula))
(with-slots (predictor-columns
factor-contrasts
(dimensions qk::dimensions)
(contents qk::ref-contents)) model-matrix
(setf factor-contrasts (make-sequence 'list
(second
(dimensions-of
(coding-of formula)))))
(setf predictor-columns (compute-predictor-columns (coding-of formula)
factor-contrasts
model-frame))
(setf dimensions (list (data-size model-frame)
(apply #'cl:+
(mapcar #'(lambda (x)
(apply #'cl:* x))
predictor-columns))))
(setf contents (make-array dimensions :initial-element nan))
(fill-model-matrix fit relevant-model-matrix))
)
(dataset model-matrix :identifiers identifiers)
)
model-matrix))
(defun compute-predictor-columns (coding factor-contrasts model-frame)
;; Here I rely on the columns of the coding corresponding exactly
;; to those on the model-matrix ... this should be the case right now.
(let ((dims (dimensions-of coding))
(data (data-of model-frame)))
(loop for i from 0 to (cl:- (first dims) 1)
collect
(loop for j from 0 to (cl:- (second dims) 1)
collect
(prog1
(coding-columns (eref coding i j)
(eref data j)
factor-contrasts j)
;;(format *terminal-io* "~&Matrix for i=~S j=~S:~%" i j)
;;(qk::print-2d factor-contrasts)
)))))
(defun dummy-delta (ii jj)
(if (eq ii jj)
1
0))
#|
(defun coding-columns (coding-ij data-j factor-contrasts j)
"Used when determining the dimensions of the model-matrix. ~
Produces the number of columns this variable (j) will contribute (multiplicatively) ~
to the columns for the current predictor (i) . As a side effect, calculates and ~
caches the factor-contrasts for variables which appear in the model as factors."
(cond ((null coding-ij) 1)
((typep data-j 'factor-object)
(case coding-ij
(:contrasts
(progn
(or (elt factor-contrasts j)
(setf (elt factor-contrasts j) (contrasts data-j)))
(cl:- (num-levels data-j) 1)))
(:dummies
(num-levels data-j))))
(t (second (matrix-dimensions-of data-j)))))
|#
;;;
(defgeneric coding-columns (coding-ij data-j &optional factor-contrasts j)
(:documentation
"Used when determining the dimensions of the model-matrix. ~
Produces the number of columns this variable (j) will contribute (multiplicatively) ~
to the columns for the current predictor (i). A very important side effect is the coding ~
of a predictor (eg 'A.B') when bothe 'A' and 'B' are factors (ie. factor-arrays)."
))
(defmethod coding-columns ((coding-ij null) data-j &optional factor-contrasts j)
"This method represents the case where the variate does not contribute to the predictor."
(declare (ignore data-j factor-contrasts j))
1)
(defmethod coding-columns ((coding-ij (eql :contrasts)) (data-j t) &optional factor-contrasts j)
"This is the most common method for contribution of continuous covariates to the predictor."
(declare (ignore factor-contrasts j))
(second (matrix-dimensions-of data-j)))
(defmethod coding-columns ((coding-ij (eql :contrasts)) (data-j factor-array) &optional factor-contrasts j)
"This method, as a side-effect, calculates and ~
caches the factor-contrasts for variables which appear in the model as factors. ~
Applies to cases of coding-ij = 'A.B' and data-j = 'A' or 'B'."
(or (elt factor-contrasts j)
(setf (elt factor-contrasts j) (contrasts data-j)))
(cl:- (num-levels data-j) 1))
(defmethod coding-columns ((coding-ij (eql :dummies)) (data-j factor-array) &optional factor-contrasts j)
"This method handles the case for 'B within A', where 'B' is coded separately for each level of 'A'. ~
Here the argument coding-ij will refer to 'B within A', and data-j will be 'A'."
(declare (ignore factor-contrasts j))
(num-levels data-j))
;;;
#|
(defun encode-the-observation (coding-ij
data-j
obsnum
variable-coding-index
factor-contrasts-j)
"Used when filling the model matrix. Returns a multiplicative ~
contribution of observation obsnum of this variable (j) to that column of the ~
current predictor (i) conceptually indexed by variable-coding-index."
(cond ((null coding-ij) 1)
((typep data-j 'factor-object)
(with-slots (levels) data-j
(let ((level (position (eref data-j obsnum) levels :test #'equal)))
(case coding-ij
(:contrasts
(eref factor-contrasts-j level variable-coding-index))
(:dummies
(dummy-delta level variable-coding-index))))))
(t (eref data-j obsnum variable-coding-index))))
|#
(defgeneric encode-the-observation (coding-ij
data-j
obsnum
variable-coding-index
factor-contrasts-j)
(:documentation
"Used when filling the model matrix. Returns a multiplicative ~
contribution of observation obsnum of this variable (j) to that column of the ~
current predictor (i) conceptually indexed by variable-coding-index."
))
(defmethod encode-the-observation ((coding-ij null)
data-j
obsnum
variable-coding-index
factor-contrasts-j)
(declare (ignore data-j obsnum variable-coding-index factor-contrasts-j))
1)
(defmethod encode-the-observation ((coding-ij (eql :contrasts))
(data-j t)
obsnum
variable-coding-index
factor-contrasts-j)
(declare (ignore factor-contrasts-j))
(eref data-j obsnum variable-coding-index))
(defmethod encode-the-observation ((coding-ij (eql :contrasts))
(data-j factor-array)
obsnum
variable-coding-index
factor-contrasts-j)
(with-slots (levels) data-j
(let ((level (position (eref data-j obsnum) levels :test #'equal)))
(eref factor-contrasts-j level variable-coding-index))))
(defmethod encode-the-observation ((coding-ij (eql :dummies))
(data-j factor-array)
obsnum
variable-coding-index
factor-contrasts-j)
(declare (ignore factor-contrasts-j))
(with-slots (levels) data-j
(let ((level (position (eref data-j obsnum) levels :test #'equal)))
(dummy-delta level variable-coding-index))))
(defun fill-model-matrix (fit &optional relevant-model-matrix)
;;
;; egad !! But I couldn't see a way to split it up ...
;;
;; NOTE: the "relevant-model-matrix" must have a formula with variables sorted in the
;; same order as in model-matrix's formula. This'll happen OK with drop/add.
;;
(with-slots (model-frame model-matrix) fit
(with-slots (data) model-frame
(with-slots (factor-contrasts
predictor-columns
formula
(mm-dims qk::dimensions)) model-matrix
(with-slots (coding reduced-predictors) formula
(let
((numobs (first mm-dims))
(numpreds (first (dimensions-of coding)))
(numvars (second (dimensions-of coding)))
(first-contributing-var
;; Hop over the response and the intercept; they only
;; contribute a multiplicative factor of 1.
;; Relies on model-frame having response in pos 0,
;; and intercept in pos 1, if present.
(if (typep (elt data 1) 'ones-array) 2 1))
(current-column 0)
variable-coding-max-indices
variable-coding-indices
relevant-predictors
relevant-predictor-columns
relevant-formula
rpos
)
(when relevant-model-matrix
(setq relevant-formula (formula-of relevant-model-matrix)
relevant-predictors (rest (reduced-predictors-of relevant-formula))
relevant-predictor-columns (predictor-columns-of relevant-model-matrix)))
(loop
for prednum from 0 to (cl:- numpreds 1)
as pred in (rest reduced-predictors)
do
(if (and relevant-model-matrix
(setq rpos (position pred relevant-predictors :test #'equal))
(or (not (dotted-term-p pred))
(same-coding-p pred formula relevant-formula prednum rpos)))
;;
;; in this case, the relevant-model-matrix has an identically coded predictor as
;; model-matrix will have. So, copy it verbatim from there.
;;
;; NOTE: This code relies on (eq (elt relevant-predictor-columns rpos)
;; (elt predictor-columns prednum))
;;
(let* ((relevant-start-column (loop for i upto (- rpos 1)
sum (elt relevant-predictor-columns i)))
(relevant-end-column (+ relevant-start-column (elt relevant-predictor-columns rpos) -1))
end-column)
;; (format T "~&BINGO: ~S" pred)
(setf (elt predictor-columns prednum)
(apply #'cl:*
(elt predictor-columns prednum)))
(setq end-column (+ current-column
(elt predictor-columns prednum)
-1))
(setf (ref model-matrix T (iseq current-column end-column))
(ref relevant-model-matrix T (iseq relevant-start-column relevant-end-column)))
(setq current-column (1+ end-column)))
(progn
(setf variable-coding-max-indices
(elt predictor-columns prednum))
(setf (elt predictor-columns prednum)
(apply #'cl:*
(elt predictor-columns prednum)))
(setf variable-coding-indices
(make-sequence 'list
(length variable-coding-max-indices)
:initial-element 0))
; (loop for count from 1 to (elt predictor-columns prednum) do
(do ((count 1 (incf count)))
((> count (elt predictor-columns prednum)))
(progn
; (loop for obsnum from 0 to (cl:- numobs 1) do
(do ((obsnum 0 (incf obsnum)))
((> obsnum (cl:- numobs 1)))
(setf
(eref model-matrix obsnum current-column)
(apply #'*
(loop for var
from first-contributing-var
to (cl:- numvars 1)
collect
(encode-the-observation
(eref coding prednum var)
(eref data var)
obsnum
(eref variable-coding-indices var)
(eref factor-contrasts var)
)))))
(setf
variable-coding-indices
(qk::column-major-next-subscript
variable-coding-indices
variable-coding-max-indices
))
(incf current-column))))))))))))
| 14,762 | Common Lisp | .l | 289 | 34.314879 | 112 | 0.509604 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 8013936a1752f1be544b95d94e59dc4422f85e326cd46425029b9649d35e7b40 | 33,724 | [
-1
] |
33,725 | model-frame.lsp | rwoldford_Quail/source/statistics/models/model-frame.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; model-frame.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1992 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; Greg Anglin 1992.
;;; R.W. Oldford 1995
;;;
;;;
;;;--------------------------------------------------------------------------------
;;;
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(model-frame special-formula-operator-handler)))
;;; see the comments in additive-formula-semantics about VREF1, etc.
(defclass model-frame (data-frame)
((aux-frame :accessor aux-frame-of :initarg :aux-frame)))
(defun empty-model-frame (&optional (aux t))
(make-instance 'model-frame
:data nil
:data-names nil
:data-types nil
:aux-frame (if aux (empty-model-frame nil))))
(defmethod model-frame ((formula additive-formula)
(raw-data data-frame)
&optional model-frame)
(let ((model-frame (or model-frame (empty-model-frame))))
(with-slots (reduced-variables) formula
(loop for v in reduced-variables
do (ensure-variable v model-frame raw-data
formula)))
(dataset model-frame :identifiers (list-identifiers raw-data))
model-frame))
(defmethod aux-eref ((r model-frame) &rest args)
(with-slots (aux-frame) r
(let ((item (apply #'eref r args)))
(if (and aux-frame (eq :none item))
(apply #'eref aux-frame args)
item))))
(defmethod ref-kernel ((ref-r model-frame) r args)
(with-slots ((r-aux-frame aux-frame)) r
(with-slots ((ref-r-aux-frame aux-frame)) ref-r
(setf ref-r-aux-frame r-aux-frame)))
(call-next-method ref-r r args))
;; I'll cheat here and use the internals of data frames
(defun ensure-variable (v new-frame old-frame formula)
(with-slots (variable-table) formula
(multiple-value-bind (vcalc vnames)
(vfind v variable-table)
(with-slots (data-names) new-frame
(let ((pos (position (first (last vnames))
data-names
:key #'(lambda (x) (first (last x)))
:test #'equal)))
(if pos
(if (> (length vnames) (length (elt data-names pos)))
(setf (elt data-names pos) vnames))
(multiple-value-bind (new-data new-type)
(calculate-variable vnames
vcalc
new-frame
old-frame
formula)
(add-data new-frame new-data (first vnames)
:type new-type
:nicknames (rest vnames))))))
vnames)))
(defun calculate-variable (vnames vcalc new-frame old-frame
formula)
(let ((aux-frame (or (aux-frame-of new-frame) new-frame))
(canonical-name (first (last vnames))))
(multiple-value-bind (datum type)
(eref aux-frame canonical-name)
(if (eq datum :none)
(apply (symbol-function (vget vcalc))
old-frame
new-frame
formula
(vargs vcalc))
(values datum type)))))
(defun ensure-args (args old-frame new-frame formula)
(loop for arg in args
collect (cond ((not (stringp arg))
arg)
;; cond returns the value of a non-nil predicate
;; when there are no forms ... ie. foo if it's not :none
((let ((foo (aux-eref new-frame arg)))
(if (eq foo :none) nil foo)))
(t
(let ((aux-frame (or (aux-frame-of new-frame) new-frame)))
(ensure-variable arg aux-frame old-frame
formula)
(eref aux-frame arg))))))
;;; Here is the implementation of VINTERCEPT, VREF1, VREF2, VREF3, and VREF4
;;; I suppose these really should be generic functions, specializing on
;;; the class of formula and maybe even old-frame.
#|
"Each of the VREFs has a different meaning when it comes to building a
model frame from a dataset; the intent is
VINTERCEPT just provide a column of 1's
VREF1 a variable, say \"x\"
VREF2 an indexed variable, say \"z[t 3]\"
VREF3 a function of variable(s), say \"foo(x, z[t 3])\"
VREF4 a lisp operation on the variable(s) \"{(/ z[t 2] z[t 1])}\"
Sometimes the function for VREF3 will be special, and refer to a process
rather than a fixed function. For example, for generalized additive
models, \"s(x)\" will mean an adaptive smoothing spline fit of the
partial residuals of the response and other fitted terms to x.
(See Hastie and Tibshirani, Generalized Additive Models,
Chapman and Hall, 1990).
Each of these is implemented as a function which returns at most 2 values:
0: the variable to be put in the model frame
1: the type of the variable (the class of return value 0).
"
|#
(defun vintercept (old-frame new-frame formula)
(declare (ignore old-frame formula))
;; since the response is already in new-frame, we can cheat and
;; use data-size on it to get the dimensions right.
(make-instance 'ones-array :dimensions (list (data-size new-frame))))
(defun vref1 (old-frame new-frame formula variable)
(declare (ignore new-frame formula))
(eref old-frame variable))
(defun vref2 (old-frame new-frame formula variable &rest ref-args)
(declare (ignore new-frame formula))
(multiple-value-bind (data type)
(eref old-frame variable)
(values (apply #'ref data ref-args)
type)))
(defun vref3 (old-frame new-frame formula operator-name &rest args)
(let ((ensured-args (ensure-args args old-frame
new-frame formula))
(operator-symbol (intern (string-upcase operator-name) :keyword)))
(apply #'special-formula-operator-handler
;; use the operator-symbol so we can write (eql ...) methods
operator-symbol
formula
operator-name
ensured-args)))
(defun vref-function-or-macro-dispatch (function-symbol ensured-args)
(let ((func (symbol-function function-symbol)))
(if (functionp func)
(apply func
ensured-args)
(eval `(,function-symbol ,@ensured-args)))))
#|
(defun vref4 (old-frame new-frame formula function-symbol &rest args)
(let ((the-value (apply (symbol-function function-symbol)
(ensure-args args old-frame
new-frame formula))))
(values the-value (class-of the-value))))
|#
(defun vref4 (old-frame new-frame formula function-symbol &rest args)
(let ((the-value
(vref-function-or-macro-dispatch function-symbol
(ensure-args args old-frame
new-frame formula))))
(values the-value (class-of the-value))))
(defgeneric special-formula-operator-handler
(operator-symbol formula operator-name &rest ensured-args)
(:documentation
"Handles special operators in model formulae. Usually specializes on ~
(operator-symbol (eql ...)) and (formula ...), and manipulates ~
ensured-args. For example, for GAMs ~
we have a method for (operator-symbol (eql :s)) and ~
(formula additive-formula) to handle s(...), meaning spline smooth to ~
the fit method. If there is no (eql ...) method, the function given by ~
(read-from-string operator-name) is called on ensured-args."
))
#|
(defmethod special-formula-operator-handler
((operator-symbol t) formula operator-name &rest ensured-args)
"This is the default case ... treat the operator-name as a lisp function ~
on the ensured-args ie. no special behavior"
(declare (ignore formula))
(let ((the-value (apply (symbol-function (read-from-string operator-name))
ensured-args)))
(values the-value (class-of the-value))))
|#
(defmethod special-formula-operator-handler
((operator-symbol t) formula operator-name &rest ensured-args)
"This is the default case ... treat the operator-name as a lisp function ~
on the ensured-args ie. no special behavior"
(declare (ignore formula))
(let ((the-value
(vref-function-or-macro-dispatch (read-from-string operator-name)
ensured-args)))
(values the-value (class-of the-value))))
| 9,254 | Common Lisp | .l | 193 | 36.435233 | 113 | 0.56551 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | a976be3c7ca1fb158dd2e37889e8a9e924d3fd922fed6530f0dc9a61a6cde45b | 33,725 | [
-1
] |
33,726 | new-terms.lsp | rwoldford_Quail/source/statistics/models/new-terms.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; new-terms.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1993 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1993.
;;; Greg Anglin 1995.
;;;
;;;
;;;--------------------------------------------------------------------------------
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(drop add
;; fit-nested-models
)))
(defgeneric drop (object-with-formula formula-fragment
&rest keys &key &allow-other-keys))
(defgeneric add (object-with-formula formula-fragment
&rest keys &key &allow-other-keys))
;; Add do-nothing primary on drop FEB 04 1998
(defmethod drop (thing formula-fragment &rest keys &key &allow-other-keys)
(declare (ignore thing formula-fragment keys))
(call-next-method))
(defmethod drop :around (thing formula-fragment &rest keys &key &allow-other-keys)
(declare (ignore keys))
(if (null formula-fragment)
thing
(call-next-method)))
#|
;; a version somewhere between rwo's and dga's (current) version
;;
(defmethod drop ((formula linear-formula) formula-fragment &key)
(let*
((variable-order< (make-careful-variable-order< formula))
(old-preds (reduced-predictors-of formula))
(response (response-of formula))
(formula-class-name (class-name (class-of formula)))
(temp-formula
(make-instance formula-class-name
:literal
(concatenate 'string response " ~ " formula-fragment)))
(dropped-preds (f-reduce (reduced-predictors-of temp-formula)
:f< variable-order<))
(new-preds
(cons (first old-preds)
(cl::sort
(set-difference
old-preds dropped-preds
:test #'equal)
variable-order<)))
(new-formula-string
(concatenate 'string response " ~ "
(let
((result (gather-reduced-predictors new-preds)))
(if (string-equal "" result)
"1"
result)))))
(make-instance 'linear-formula :literal new-formula-string)
)
)
|#
;; a less intuitive but more direct version of drop for linear-formula
;; (relative to commented one above)
;; also fixes some bugs
;;
;; won't handle e.g. dropping "x[t 3]" from "y ~ x",
;; since formula-reducing code can't deal with "y ~ x - x[t 3]".
;;
(defmethod drop ((formula linear-formula) formula-fragment
&rest keys &key (semantics-warning T) &allow-other-keys)
(declare (ignore keys))
(let*
((remove-intercept NIL)
(variable-table (variable-table-of formula))
(variable-order< (make-careful-variable-order< formula))
(old-preds (reduced-predictors-of formula))
(response (response-of formula))
(dropped-preds (f-reduce (list 'f+
(additive-formula-semantics-1
(parse :infix formula-fragment 0)
variable-table))
:f< variable-order<))
(new-preds
(cons 'f+
(let ((new-preds (copy-list (rest old-preds))))
(loop for dp in (rest dropped-preds)
do
(when (equal dp "1")
(setq remove-intercept T))
(if (find dp new-preds :test #'equal)
(setq new-preds (delete dp new-preds :test #'equal))
(error "Can't find dropped predictor ~S in formula ~S."
dp formula)))
new-preds)))
(new-formula-string
(concatenate 'string response " ~ "
(let ((result (gather-reduced-predictors new-preds)))
(if (string-equal "" result)
(if remove-intercept
(error "Null formula results from dropping intercept in formula ~S."
formula)
"1")
(if remove-intercept
(concatenate 'string "-1 + " result)
result)))))
(new-formula
(make-instance 'linear-formula
:literal new-formula-string
:variable-table variable-table)))
(values new-formula
(compare-dotted-terms-semantics formula new-formula :warn semantics-warning))
)
)
(defmethod drop ((model generalized-linear-model) formula-fragment
&rest keys &key &allow-other-keys)
(multiple-value-bind (new-formula semantics-ok)
(apply #'drop (formula-of model) formula-fragment keys)
(values
(model (class-of model)
new-formula
:link (link-of model)
:family (family-of model)
:weight-fn (weight-fn-of model)
:offset (offset-of model))
semantics-ok)))
(defmethod drop ((fit generalized-linear-model-fit) formula-fragment
&rest keys &key &allow-other-keys)
(multiple-value-bind (new-model semantics-ok)
(apply #'drop (model-of fit) formula-fragment keys)
(values
(fit new-model
(data-frame-of fit)
:weight (weight-of fit)
:relevant-model-matrix (model-matrix-of fit))
semantics-ok)))
;;; Add do-nothing primary on add FEB 04 1998
(defmethod add (thing formula-fragment &rest keys &key &allow-other-keys)
(declare (ignore thing formula-fragment keys))
(call-next-method))
(defmethod add :around (thing formula-fragment &rest keys &key &allow-other-keys)
(declare (ignore keys))
(if (null formula-fragment)
thing
(call-next-method)))
(defmethod add ((formula linear-formula) formula-fragment &rest keys
&key (semantics-warning T) &allow-other-keys)
(declare (ignore keys))
(let*
((new-variable-table (loop with new-variable-table = (make-hash-table :test #'equal)
for key being each hash-key of (variable-table-of formula)
using (hash-value value)
do (setf (gethash key new-variable-table) value)
finally (return new-variable-table)))
(old-preds (reduced-predictors-of formula))
(response (response-of formula))
(added-preds (additive-formula-semantics-1
(parse :infix formula-fragment 0)
new-variable-table))
(variable-order< #'(lambda (x y)
(< (vcount (vfind x new-variable-table))
(vcount (vfind y new-variable-table)))))
(new-preds (f-reduce (append old-preds ;; old-preds includes leading 'f+.
(list added-preds))
:f< variable-order<))
(new-formula-string
(concatenate 'string response " ~ " (gather-reduced-predictors new-preds)))
(new-formula
(make-instance 'linear-formula
:literal new-formula-string
:variable-table new-variable-table)))
(values new-formula
(compare-dotted-terms-semantics formula new-formula :warn semantics-warning))
)
)
(defmethod add ((model generalized-linear-model) formula-fragment
&rest keys &key &allow-other-keys)
(multiple-value-bind (new-formula semantics-ok)
(apply #'add (formula-of model) formula-fragment keys)
(values
(model (class-of model)
new-formula
:link (link-of model)
:family (family-of model)
:weight-fn (weight-fn-of model)
:offset (offset-of model))
semantics-ok)))
(defmethod add ((fit generalized-linear-model-fit) formula-fragment
&rest keys &key &allow-other-keys)
(multiple-value-bind (new-model semantics-ok)
(apply #'add (model-of fit) formula-fragment keys)
(values
(fit new-model
(data-frame-of fit)
:weight (weight-of fit)
:relevant-model-matrix (model-matrix-of fit))
semantics-ok)))
(defun gather-reduced-predictors (preds)
(if (listp preds)
(cond
((= (length preds) 1) "")
((= (length preds) 2) (gather-reduced-predictors (cadr preds)))
((eq (first preds) 'F+)
(concatenate 'string (gather-reduced-predictors (cadr preds))
" + " (gather-reduced-predictors (cons 'F+ (cddr preds)))))
((eq (first preds) 'F.)
(concatenate 'string
(gather-reduced-predictors (cadr preds))
"."
(gather-reduced-predictors (cons 'F. (cddr preds)))))
((eq (first preds) 'F-)
(concatenate 'string (gather-reduced-predictors (cadr preds))
" - " (gather-reduced-predictors (cons 'F- (cddr preds)))))
(preds (format NIL "~a" preds))
(T ""))
(string preds)))
#|
;; rwo code which I haven't looked at since modifying drop/add ... dga 950704
(defgeneric list-nested-terms (modelling-thing)
(:documentation "Returns a list of dotted pairs. ~
The list is ordered from smallest to largest nested model. ~
Not all possible nested models are included. Rather the ~
ordering depends on that found in the given argument. ~
The first of each pair is a description of the terms included ~
in that nested model. The second describes ~
the term that was dropped from the next largest model to ~
arrive at the associated nested model."))
(defmethod list-nested-terms ((fit fit-object))
(list-nested-terms (model-of fit)))
(defmethod list-nested-terms ((model response-model))
(list-nested-terms (formula-of model)))
(defmethod list-nested-terms ((formula linear-formula))
(let*
((preds (reduced-predictors-of formula))
(full-model (gather-reduced-predictors preds))
(nested-models (list (cons full-model NIL)))
)
(loop while (not (equal preds '(F+)))
do
(push (cons (gather-reduced-predictors (butlast preds))
(gather-reduced-predictors (car (last preds))))
nested-models)
(setf preds (butlast preds))
)
(rest nested-models)))
(defmethod fit-nested-models ((fit generalized-linear-model-fit))
(let ((nested-models (cdr (reverse (list-nested-terms fit))))
(current-fit fit))
(loop for model in nested-models
collect
(let ((model-formula (car model))
(term (cdr model)))
(inform-user (format NIL "Now fitting ~a ~%Patience please ..." model-formula))
(setf current-fit (drop current-fit term))
(list term model-formula current-fit)))))
|#
| 11,414 | Common Lisp | .l | 260 | 32.388462 | 94 | 0.552153 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | e8f68e06307b59fc2866dd14a20de645e580d96732ed848039472fd1e835f526 | 33,726 | [
-1
] |
33,727 | parse.lsp | rwoldford_Quail/source/statistics/models/parse.lsp | (in-package :quail)
;;; these are macros so that we can setf them.
(defmacro kind-of (pt) `(first ,pt))
(defmacro node-of (pt) `(second ,pt))
(defmacro start-of (pt) `(third ,pt))
(defmacro end-of (pt) `(fourth ,pt))
(defmacro subtrees-of (pt) `(fifth ,pt))
(defun make-parse (kind node start end &optional (subtrees nil))
(list kind node start end subtrees))
(defun build-tree (kind super-node subtrees)
(let ((start (apply #'min (mapcar #'third subtrees)))
(end (apply #'max (mapcar #'fourth subtrees))))
(list kind (subseq super-node start end) start end subtrees)))
(defun find-next (char string &optional (start 0) (end (length string)))
(let (found)
; (loop for i from start to (cl:- end 1)
; until found do
(do ((i start (incf i)))
((or (= i end) found))
(if (eq char (char string i))
(setf found i)))
(if found
found
nil)))
(defun find-end (str pred &optional (start 0) (max-end (length str)))
(let (end)
; (loop for i from start to max-end
; until end do
(do ((i start (incf i)))
((or (> i max-end) end))
(if (< i max-end)
(if (not (funcall pred (char str i)))
(setf end i))
(setf end i)))
end))
(defun whitespace-p (x)
(member x (list #\Space #\Newline)))
(defun skip-whitespace (str &optional (start 0))
(find-end str #'whitespace-p start))
(defmethod parse ((kind (eql :whole-number)) parse-string
start &optional (end (length parse-string)))
(let (local-end)
(setf local-end (find-end parse-string #'digit-char-p start end))
(if (eq local-end start)
nil
(make-parse :whole-number
(read-from-string
(subseq parse-string start local-end))
start
local-end))))
(defvar *special-chars* (list #\( #\) #\~ #\[ #\] #\{ #\} #\Space #\Newline))
(defun special-char-p (x)
(declare (special *special-chars*))
(member x *special-chars*))
(defun variable-char-p (x)
(declare (special *special-chars*))
(not (member x *special-chars*)))
(defmethod parse ((kind (eql :variable)) parse-string
start &optional (end (length parse-string)))
(if (eq start end)
(make-parse :null "" start start)
(let (local-end
variable
kind)
(if (eq (char parse-string start) #\")
(progn
(setf local-end (find-next #\" parse-string (cl:+ start 1)))
(if local-end
(incf local-end)
(error "Unmatched '\"' in ~S." parse-string)))
(setf local-end (find-end parse-string #'variable-char-p start end)))
(setf kind :variable)
(setf variable (subseq parse-string start local-end))
(let ((vble-read (read-from-string variable)))
(when (numberp vble-read)
(setf kind :number)
(setf variable vble-read))
(when (keywordp vble-read)
(setf kind :keyword)
(setf variable vble-read))
(when (stringp vble-read)
(setf variable vble-read)))
(make-parse kind
variable
start
local-end))))
(defmethod parse ((kind (eql :selector-left)) masked-parse-string
start &optional (end (length masked-parse-string)))
(declare (ignore end))
(if (and (> (length masked-parse-string) start)
(eq (char masked-parse-string start) #\[))
(make-parse :selector-left "[" start (cl:+ start 1))
nil))
(defmethod parse ((kind (eql :selector-right)) masked-parse-string
start &optional (end (length masked-parse-string)))
(declare (ignore end))
(let ((close (find-next #\] masked-parse-string start)))
(if (not close)
(error "Unmatched '[' in ~S." masked-parse-string))
(make-parse :selector-right "]" close (cl:+ close 1))))
(defmethod parse ((kind (eql :selector)) parse-string
start &optional (end (length parse-string)))
(if (eq start end)
nil
(let* ((masked-parse-string (mask-quotes parse-string start end))
(tree0 (parse :selector-left masked-parse-string start end)))
(if tree0
(let* ((tree1 (parse :selector-right
masked-parse-string
(end-of tree0)
end))
(selector (parse :select-lisp-args
parse-string
(end-of tree0)
(start-of tree1))))
;; don't need tree0 or tree1 after this ...
(setf (start-of selector) (start-of tree0))
(setf (end-of selector) (end-of tree1))
selector)
nil))))
(defmethod parse ((kind (eql :vble-select)) parse-string
start &optional (end (length parse-string)))
(setf start (skip-whitespace parse-string start))
(let ((tree0 (parse :variable parse-string start end)))
(if tree0
(let* ((start1 (end-of tree0))
(tree1 (parse :selector parse-string start1 end)))
(if (and (eq (kind-of tree0) :variable) tree1)
(build-tree :vble-select parse-string (list tree0 tree1))
tree0))
nil)))
(defvar *infix-table* (make-hash-table :test #'equal))
(defun put-infix (infix type &optional (precedence 0) (action nil))
(setf (gethash infix *infix-table*) (list type precedence action)))
(defun infix-type (infix)
(first (gethash infix *infix-table*)))
(defmacro infix-op (infix)
`(first (infix-type ,infix)))
(defmacro infix-left (infix)
`(second (infix-type ,infix)))
(defmacro infix-right (infix)
`(third (infix-type ,infix)))
(defun infix-precedence (infix)
(second (gethash infix *infix-table*)))
(progn
(put-infix "**" '(:expstar :infix :whole-number) 4)
(put-infix "^" '(:expstar :infix :whole-number) 4)
(put-infix "*" '(:star :infix :infix) 3)
(put-infix "/" '(:slash :infix :infix) 2.5)
(put-infix "." '(:dot :infix :infix) 2)
(put-infix "+" '(:terms :infix :infix) 1)
(put-infix "-" '(:remove :infix :infix) 1)
(put-infix "-/" '(:remove-slash :infix :infix) 1)
(put-infix "-*" '(:remove-star :infix :infix) 1)
(put-infix "~" '(:formula :flv :infix) 0)
t)
(defvar *max-infix-length*)
(defun remaximize-infix ()
(declare (special *max-infix-length* *infix-table*))
(setf *max-infix-length* -1)
(maphash #'(lambda (key value)
(declare (ignore value) (special *max-infix-length*))
(if (> (length key) *max-infix-length*)
(setf *max-infix-length* (length key))))
*infix-table*)
*max-infix-length*)
(remaximize-infix)
(defun infix-here (str pos)
(declare (special *max-infix-length*))
(let ((len (length str))
infix
done)
; (loop for local-end
; from (min len (cl:+ pos *max-infix-length*))
; downto (cl:+ pos 1)
; until done
; do
(do ((local-end (min len (cl:+ pos *max-infix-length*)) (decf local-end)))
((or (= local-end pos) done))
(progn
(setf infix (subseq str pos local-end))
(setf done (infix-type infix))))
(if done
infix
nil)))
(defun mask-quotes (str &optional (start 0) (end (length str)))
(mask-quotes-recurs (subseq str 0) start end))
(defun mask-quotes-recurs (str start end)
(let* ((begin (find-next #\" str start))
(local-end (if begin (find-next #\" str (cl:+ begin 1)))))
(cond ((and begin local-end)
(progn
; (loop for i
; from (cl:+ begin 1)
; to (cl:- local-end 1) do
(do ((i (cl:+ begin 1) (incf i)))
((= i local-end))
(setf (char str i) #\"))
(mask-quotes-recurs str
(cl:+ local-end 1)
end)))
(begin (error "Unmatched '\"' in ~S." str))
(t str))))
(defun find-close-paren (str &optional (start 0))
"Finds closing paren for open paren in str appearing at position start."
(let ((open (find-next #\( str (cl:+ start 1)))
(close (find-next #\) str (cl:+ start 1))))
(if (not open)
(setf open (length str)))
(cond ((not close)
(error "Unmatched '(' in ~S." str))
((< open close)
(find-close-paren str
(find-close-paren str open)))
(t close))))
(defun find-close (open-char close-char str &optional (start 0))
"Finds close-char for open-char in str appearing at position start.
Assumes there is no nesting of open-char/close-char."
(let ((close (find-next close-char str (cl:+ start 1))))
(cond ((not close)
(error "Unmatched '~A' in ~S." open-char str))
(t close))))
(defun find-infixes (str start end)
(setf str (mask-quotes str start))
(let* (infixes)
(setf infixes
(loop for i from start to (cl:- end 1)
collect (cond
((eq (char str i) #\()
(setf i (find-close-paren str i))
nil)
((eq (char str i) #\{)
(setf i (find-close #\{ #\} str i))
nil)
((eq (char str i) #\[)
(setf i (find-close #\[ #\] str i))
nil)
(t
(let ((infix (infix-here str i)))
(when infix
(prog1 (list i
(infix-precedence infix)
(length infix))
(setf i (min
(cl:+ i (length infix) -1)
(cl:- end 1))))))))))
(setf infixes (delete nil infixes))
(sort infixes #'(lambda (x y)
(or (< (second x) (second y))
(and (= (second x) (second y))
(> (first x) (first y))))))))
(defmacro infix-position (x) `(first ,x))
(defun infix-parse-recurs (parse-string infixes start end)
(if infixes
(let* ((infix-info (first infixes))
(rest-infixes (rest infixes))
(end0 (infix-position infix-info))
(start1 (cl:+ end0 (third infix-info)))
(infix (subseq parse-string end0 start1))
(tree0 (infix-subtree infix rest-infixes
:left parse-string start end0 end0))
(tree1 (infix-subtree infix rest-infixes
:right parse-string start1 start1 end)))
(build-tree (infix-op infix)
parse-string
(list tree0
tree1)))
(parse :flv parse-string start end)))
(defun infix-subtree (infix rest-infixes side str start pivot end)
(let* ((pred (case side
(:left #'(lambda (x)
(>= (infix-position x) pivot)))
(:right #'(lambda (x)
(< (infix-position x) pivot)))))
(subtree (remove-if pred rest-infixes))
(infix-type (case side
(:left (infix-left infix))
(:right (infix-right infix)))))
(case infix-type
(:infix
(if subtree
(infix-parse-recurs str subtree start end)
(parse :flv str start end)))
(t
(if subtree
(error "~S does not parse to a component of type ~S"
(subseq str start end)
infix-type)
(parse infix-type str start end))))))
(defmethod parse ((kind (eql :infix)) parse-string
start &optional (end (length parse-string)))
(setf start (skip-whitespace parse-string start))
(infix-parse-recurs parse-string
(find-infixes parse-string start end)
start
end))
(defmethod parse ((kind (eql :function-left)) masked-parse-string
start &optional (end (length masked-parse-string)))
(declare (ignore end))
(let ((open (find-next #\( masked-parse-string start)))
(if open
(make-parse :function-left "(" open (cl:+ 1 open))
nil)))
(defmethod parse ((kind (eql :function-right)) masked-parse-string
start &optional (end (length masked-parse-string)))
(declare (ignore end))
;; Here start is known to be on the open paren.
;; find-close-paren will signal an error if there's a problem.
(let ((close (find-close-paren masked-parse-string start)))
(make-parse :function-right ")" close (cl:+ 1 close))))
(defmethod parse ((kind (eql :function-name)) parse-string
start &optional (end (length parse-string)))
(let* ((tree (parse :variable parse-string start end))
(null-name (eq :null (kind-of tree))))
(cond ((and tree null-name) nil)
;;
;; read-from-string is used instead of intern so that one can
;; use, say, my-package::foo(x) in a formula
;;
((and tree (eq :variable (kind-of tree)))
(setf (kind-of tree) :function-name))
(t (error "Semantic error during formula parsing. ~
~&~S(...) is not a legitimate functional operator."
(node-of tree))))
tree))
(defmethod parse ((kind (eql :lisp-op)) parse-string
start &optional (end (length parse-string)))
(setf start (skip-whitespace parse-string start))
(let ((masked-parse-string (mask-quotes parse-string start end))
(first-char (char parse-string start)))
(cond ((eq start end)
nil)
((eq first-char #\()
(let* ((close (find-close-paren masked-parse-string
start))
(op (parse :lisp-read parse-string (cl:+ start 1) end)))
(if (eq (node-of op) 'quote)
(parse :lisp-read parse-string start end)
(let ((args (parse :lisp-args
parse-string
(end-of op)
close)))
(make-parse :lisp-op
(subseq parse-string start (cl:+ close 1))
start
(cl:+ close 1)
(list op args))))))
((eq first-char #\')
(parse :lisp-read parse-string start end))
((eq first-char #\`)
(error "This parser can't handle backquotes."))
(t
(parse :vble-select parse-string start end)))))
(defun parse-args (arg-kind parse-string
start &optional (end (length parse-string)))
(if (eq start end)
nil
(let* (arg
args)
(setf args
(loop for i from start to (cl:- end 1)
collect (prog1
(setf arg (parse arg-kind parse-string i end))
(setf i (- (end-of arg) 1)))))
(build-tree :args
parse-string
args))))
(defmethod parse ((kind (eql :lisp-args)) parse-string
start &optional (end (length parse-string)))
(parse-args :lisp-op parse-string start end))
(defmethod parse ((kind (eql :select-lisp-args)) parse-string
start &optional (end (length parse-string)))
(parse-args :lisp-read parse-string start end))
(defmethod parse ((kind (eql :args)) parse-string
start &optional (end (length parse-string)))
(parse-args :flv parse-string start end))
(defmethod parse ((kind (eql :lisp-op-left)) masked-parse-string
start &optional (end (length masked-parse-string)))
(declare (ignore end))
(let ((open (find-next #\{ masked-parse-string start)))
(if open
(make-parse :lisp-op-left "{" open (cl:+ 1 open))
nil)))
(defmethod parse ((kind (eql :lisp-op-right)) masked-parse-string
start &optional (end (length masked-parse-string)))
(declare (ignore end))
(let ((close (find-next #\} masked-parse-string start)))
(if (not close)
(error "Unmatched '{' in ~S." masked-parse-string))
(make-parse :lisp-op-right "}" close (cl:+ close 1))))
(defmethod parse ((kind (eql :flv)) parse-string
start &optional (end (length parse-string)))
(setf start (skip-whitespace parse-string start))
(let* ((mask-parse-string (mask-quotes parse-string start end))
(critical (position-if #'special-char-p mask-parse-string :start start)))
(if critical
(case (char parse-string critical)
(#\( (parse :function parse-string start end))
(#\[ (parse :vble-select parse-string start end))
(#\{ (parse :lisp parse-string start end))
(t (parse :variable parse-string start end)))
(parse :variable parse-string start end))))
(defmethod parse ((kind (eql :function)) parse-string
start &optional (end (length parse-string)))
(setf start (skip-whitespace parse-string start))
(let ((mask-parse-string (mask-quotes parse-string start end))
tree0 tree1 tree2 tree3)
(setf tree1 (parse :function-left mask-parse-string start end))
;; we use (start-of tree1) here to help find-close-paren
(setf tree3 (parse :function-right
mask-parse-string
(start-of tree1)
end))
(setf tree0 (parse :function-name
parse-string
start
(start-of tree1)))
(if (eq (kind-of tree0) :null)
;; this is the case when the parens mark an infix subexpression
(progn
(setf tree2 (parse :infix parse-string (end-of tree1) (start-of tree3)))
(decf (start-of tree2))
(incf (end-of tree2))
tree2)
;; this is the usual function case
(progn
(setf tree2 (parse :args
parse-string
(end-of tree1)
(start-of tree3)))
(if (not tree2)
(error "Null argument list to ~A(..)" (node-of tree0)))
;; don't need tree1 and tree3 after this ...
(make-parse :function
(subseq parse-string (start-of tree0) (end-of tree3))
(start-of tree0)
(end-of tree3)
(list tree0 tree2))))))
(defmethod parse ((kind (eql :lisp)) parse-string
start &optional (end (length parse-string)))
(setf start (skip-whitespace parse-string start))
(let ((mask-parse-string (mask-quotes parse-string start end))
tree0 tree1 tree2 tree3)
(setf tree1 (parse :lisp-op-left mask-parse-string start end))
(setf tree3 (parse :lisp-op-right mask-parse-string (end-of tree1) end))
(setf tree0 (parse :variable
parse-string
start
(start-of tree1)))
(setf tree2 (parse :lisp-op parse-string (end-of tree1) end))
(make-parse :lisp
(subseq parse-string (start-of tree0) (end-of tree3))
(start-of tree0)
(end-of tree3)
(list tree0 tree2))))
(defmethod parse ((kind (eql :lisp-read)) parse-string
start &optional (end (length parse-string)))
(let ((lisp-string (subseq parse-string start end)))
;;
;; read-from-string is used instead of intern so that one can
;; use, say, {(my-package::foo x)} in a formula
;;
(multiple-value-bind (lisp-object local-end)
(read-from-string lisp-string)
(make-parse :lisp-read
lisp-object
start
(+ start local-end)))))
#|
;;; this is conceptually what's going on, but it's slow so use it only for
;;; development and debugging.
;;; node contains current parse-string when subtrees is non-nil, else
;;; the value for that terminal tree.
(defclass parse-tree ()
((kind :accessor kind-of :initarg :kind)
(node :accessor node-of :initarg :node)
;; start of this node in parent's node
(start :accessor start-of :initarg :start)
;; end (points to first char beyond)
(end :accessor end-of :initarg :end)
(subtrees :accessor subtrees-of :initarg :subtrees :initform nil)))
(defmethod print-object ((pt parse-tree) stream)
(if (slot-boundp pt 'node)
(format stream "#<~S ~S ~S>"
(class-name (class-of pt))
(kind-of pt)
(node-of pt))
(format stream "#<~S ~S>"
(class-name (class-of pt))
(qk::system-get-pointer pt)))
pt)
(defmethod print-object ((pt parse-tree) stream)
(cond
((eq stream *terminal-io*) (inspect pt))
((eq stream *standard-output*) (inspect pt))
((eq stream *query-io*) (inspect pt))
((eq stream *debug-io*) nil)
((eq stream *error-output*) nil)
((eq stream *trace-output*) nil)
((eq stream *quail-terminal-io*) (inspect pt))
((eq stream *quail-standard-output*) (inspect pt))
((eq stream *quail-query-io*) (inspect pt))
((eq stream *quail-debug-io*) nil)
((eq stream *quail-error-output*) nil)
((eq stream *quail-trace-output*) nil)
(T nil))
(if (slot-boundp pt 'node)
(format stream "#<~S ~S ~S>"
(class-name (class-of pt))
(kind-of pt)
(node-of pt))
(format stream "#<~S ~S>"
(class-name (class-of pt))
(qk::system-get-pointer pt)))
pt)
(defun make-parse (kind node start end &optional (subtrees nil))
(make-instance 'parse-tree
:kind kind
:node node
:start start
:end end
:subtrees subtrees))
(defun build-tree (kind super-node subtrees)
(let ((start (apply #'min (mapcar #'start-of subtrees)))
(end (apply #'max (mapcar #'end-of subtrees))))
(make-instance 'parse-tree
:kind kind
:node (subseq super-node start end)
:start start
:end end
:subtrees subtrees)))
|#
| 23,303 | Common Lisp | .l | 532 | 31.853383 | 84 | 0.526281 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 4c642bf3d22c0c5de0fe59d4c90eb1dd9671a12436f3c2c993413c3b666848fa | 33,727 | [
-1
] |
33,728 | gam.lsp | rwoldford_Quail/source/statistics/models/gam.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; gam.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1992 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; Greg Anglin 1992.
;;;
;;;--------------------------------------------------------------------------------
;;;
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(generalized-additive-model additive-model
generalized-additive-model-fit additive-model-fit
formula-of family-of link-of weight-fn-of)))
(defclass generalized-additive-model (response-model)
((formula :accessor formula-of :initarg :formula :type additive-formula
:documentation "An object of class additive-formula.")
(link :accessor link-of :initarg :link :initform identity-link
:documentation
"A link-object providing the link function info. ~
Defaults to identity link.")
(family :accessor family-of :initarg :family :initform gaussian-family
:documentation
"A family object containing family info such as ~
variance function, deviance function, etc. ~
Defaults to gaussian family.")
(weight-fn :accessor weight-fn-of :initarg :weight-fn
:documentation
"The weight function; if not provided, is calculated from ~
variance function and derivative of link.")
(offset :accessor offset-of :initarg :offset :initform 0
:documentation
"see McCullagh & Nelder"))
(:documentation
"Generalized additive models of Tibshirani & Hastie (1991). ~
FITTING CURRENTLY UNIMPLEMENTED. ~
(:elaboration In this class, the formula is restricted to be of class ~
additive-formula) ~
"))
(defmethod-multi link-of ((link-identifier (symbol string)))
(link-of (find-link link-identifier)))
(defmethod-multi family-of ((family-identifier (symbol string)))
(family-of (find-family family-identifier)))
(defmethod model ((model generalized-additive-model)
(formula string)
&rest initargs)
(apply #'model
model
(make-instance 'additive-formula :literal formula)
initargs))
(defmethod model ((model generalized-additive-model)
(formula additive-formula)
&rest initargs)
(apply #'reinitialize-instance model :formula formula initargs)
model)
(defmethod reinitialize-instance :after ((model generalized-additive-model)
&rest initargs)
(declare (ignore initargs))
(if (slot-boundp model 'family)
(setf (slot-value model 'family) (find-family (slot-value model 'family))))
(if (slot-boundp model 'link)
(setf (slot-value model 'link) (find-link (slot-value model 'link))))
(if (and (not (slot-boundp model 'weight-fn))
(slot-boundp model 'family)
(slot-boundp model 'link))
(setf (weight-fn-of model)
(find-weight-fn (slot-value model 'family)
(slot-value model 'link))))
)
(defclass generalized-additive-model-fit (response-model-fit)
()
(:documentation "The class of fits of generalized additive models. ~
Fits of generalized additive models are CURRENTLY UNIMPLEMENTED."))
(defmethod link-of ((fit-obj generalized-additive-model-fit))
(link-of (model-of fit-obj)))
(defmethod family-of ((fit-obj generalized-additive-model-fit))
(family-of (model-of fit-obj)))
(defclass additive-model (generalized-additive-model)
((link :accessor link-of
:initarg :link
:initform identity-link
:allocation :class))
(:documentation
"This class has the link restricted to be the identity."))
(defclass additive-model-fit (generalized-additive-model-fit)
()
(:documentation "The class of fits of additive models. ~
Fits of additive models are CURRENTLY UNIMPLEMENTED."))
| 4,230 | Common Lisp | .l | 93 | 37.236559 | 107 | 0.603746 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | abd9e122cbe66abe3cd8a83677fd915605e9ba1fbbe4618438fedd207eb8c6ed | 33,728 | [
-1
] |
33,729 | deviance.lsp | rwoldford_Quail/source/statistics/models/deviance.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; deviance.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; (c) Copyright Statistical Computing Laboratory
;;; University of Waterloo
;;; 1995
;;;
;;; Authors:
;;; D.G. Anglin 1992
;;; R.W. Oldford 1995
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(deviance)))
(defgeneric deviance (family-or-fit &rest initargs &key &allow-other-keys))
(defmethod-multi deviance ((family (string symbol)) &rest initargs)
(apply #'deviance (find-family family) initargs))
(defmethod deviance ((family gaussian-family) &rest initargs &key mu y w)
(declare (ignore initargs))
(with-slots (deviances-fn) family
(.* (tp w) (expt (fn-call deviances-fn mu y) 2))))
(defmethod-multi deviance ((family (binomial-family
inverse-gaussian-family))
&rest initargs &key mu y w)
(declare (ignore initargs))
(with-slots (deviances-fn) family
(.* (tp w) (fn-call deviances-fn mu y))))
(defmethod-multi deviance ((family (poisson-family
gamma-family)) &rest initargs &key mu y w)
(declare (ignore initargs))
(with-slots (deviances-fn) family
(* 2 (.* (tp w) (fn-call deviances-fn mu y)))))
| 1,544 | Common Lisp | .l | 35 | 38.028571 | 81 | 0.503018 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 83719bee192ef0b321fe6ad608274cda961160db7acdeb3cd9eca8d57da24667 | 33,729 | [
-1
] |
33,730 | weight-fn.lsp | rwoldford_Quail/source/statistics/models/weight-fn.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; weight-fn.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; (c) Copyright Statistical Computing Laboratory
;;; University of Waterloo
;;; 1995
;;;
;;; Authors:
;;; D.G. Anglin 1992
;;; R.W. Oldford 1995
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(def-weight-fn find-weight-fn)))
(defvar *weight-fn-table* (make-hash-table :test #'equal))
(defun def-weight-fn (family link weight-fn)
(declare (special *weight-fn-table*))
(setf (gethash (list family link) *weight-fn-table*) weight-fn))
(defun find-weight-fn (family link)
(declare (special *weight-fn-table*))
(let ((weight-fn
(gethash (list family link) *weight-fn-table*)))
(or weight-fn
(let* ((link-deriv (find-deriv (link-of link)))
(family-variance (variance-fn-of family))
(result
(eval `(fn (mu w)
(/ w (* (^ (fn-call ,link-deriv mu) 2)
(fn-call ,family-variance mu))))))
)
(def-weight-fn family link result)))))
;;; some basic ones below ... most others are complicated and just as easily
;;; handled in the general code above.
(def-weight-fn gaussian-family identity-link (fn (mu w) w))
(def-weight-fn binomial-family logit-link (fn (mu w) (* w mu (- 1 mu))))
(def-weight-fn poisson-family log-link (fn (mu w) (* w mu)))
(def-weight-fn gamma-family reciprocal-link (fn (mu w) (* w mu mu)))
(def-weight-fn gamma-family log-link (fn (mu w) w))
| 1,845 | Common Lisp | .l | 41 | 38.390244 | 97 | 0.5 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 21c423ad02c13922636328a2197d525b27cf4083307ab71fb70d9fb9a7cb22bc | 33,730 | [
-1
] |
33,731 | response-matrix.lsp | rwoldford_Quail/source/statistics/models/response-matrix.lsp | (in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(response-matrix
multinomial-categorical-counts binomial-categorical-counts
categorical-proportion-matrix
multinomial-cumulative-counts binomial-cumulative-counts
cumulative-proportion-matrix
binary-response-vector)))
(defclass response-matrix (matrix)
()
(:documentation
"Subclasses of response-matrix represent response data in generalized ~
linear/additive models. Each is a matrix, with rows as observations ~
and multinomial categories as columns. Covariates are assumed to be in ~
separate storage, associated with each row.")
)
;;; Classes for nominal data
(defclass multinomial-categorical-counts (response-matrix)
()
(:documentation
"multinomial-categorical-counts are n x m matrices with n observations of ~
m-nomial variables. This subclass of response-matrix is used primarily to ~
represent nominal (as opposed to ordinal) polytomous responses. ~
The representation is that column i contains ~
the count for category i, i = 0, ... , m-1.")
)
(defclass binomial-categorical-counts (multinomial-categorical-counts)
()
(:documentation
"binomial-categorical-counts are the special case of ~
multinomial-categorical-counts for m=2.")
)
#|
;; I don't think we really need these ... use binary-response-vector
(defclass bernoulli-categorical-counts (binomial-categorical-counts)
()
(:documentation
"bernoulli-categorical-counts are a special case of binomial-categorical-counts. ~
in which there are only two possible values ~
in column 0 of any row: 0 or 1. Column 1 is therefore constrained to have ~
value 1 - column 0, and accordingly is optional.")
)
|#
(defclass categorical-proportion-matrix (response-matrix)
()
(:documentation
"categorical-proportion-matrix is a numerical representation of the proportion of ~
observations in each category of a nominal polytomous response. ~
For m categories, this matrix has (m-1) columns representing the proportion in ~
category i, i=0, ..., m-2; 1 - (sum of all columns) gives ~
the proportion in category (m-1)"
)
)
;;; Classes for ordinal data
(defclass multinomial-cumulative-counts (response-matrix)
()
(:documentation
"multinomial-cumulative-counts are n x m matrices with n observations of ~
m-nomial variables. This subclass of response-matrix is used primarily to ~
represent ordinal (as opposed to nominal) polytomous responses. ~
The representation is that column i contains ~
the number of observations which are in categories <= i, i = 0, ... , m-1. ~
Accordingly, column (m-1) contains the total number of individuals for that ~
row.")
)
(defclass binomial-cumulative-counts (multinomial-cumulative-counts)
()
(:documentation
"binomial-cumulative-counts are the special case of ~
multinomial-cumulative-counts for m=2.")
)
#|
;; I don't think we really need these ... use binary-response-vector
(defclass bernoulli-cumulative-counts (binomial-cumulative-counts)
()
(:documentation
"bernoulli-cumulative-counts are a special case of binomial-counts. ~
bernoulli-cumulative-counts ~
are special in that there are only two possible values ~
in column 0 of any row: 0 or 1. Column 1 is therefore constrained to have ~
value 1, and accordingly is optional.")
)
|#
(defclass cumulative-proportion-matrix (response-matrix)
()
(:documentation
"cumulative-proportion-matrix is a numerical representation of the proportion of ~
observations in category of an ordinal polytomous response. ~
For m categories, this matrix has (m-1) columns representing the proportion in ~
categories <= i, i=0, ..., m-2; the proportion in categories <= (m-1) is 1."
)
)
;;; Class for categorical and binary data
(defclass categorical-response-vector (factor-array response-matrix)
())
(defclass binary-response-vector (categorical-response-vector)
()
(:documentation
"binary-response-vector is used to represent a univariate bernoulli ~
(binary) response variable. Since it is a subclass of factor-array, ~
specification of the two 'levels' of the variable is can be made with arbitrary ~
strings, symbols, or numbers. If x is a binary-response-vector, ~
(first (levels-of x)) is coded as 0.")
)
(defmethod make-ref-array ((self binary-response-vector) dimensions &rest rest)
(multiple-value-bind (levels extra)
(qk::interpret-keys-only rest
'(:levels)
'make-ref-array
t)
(if (> (length levels) 2)
(error "Binary response vectors may have at most two levels, hence ~S ~
is an illegal levels specifier." levels))
(setf (levels-of self) levels)
(apply #'call-next-method self dimensions extra)))
(defmethod update-instance-for-different-class :before
((old matrix)
(new binary-response-vector)
&rest initargs)
(declare (ignore initargs))
(setf (slot-value new 'levels) '(0 1)))
(defmethod print-object ((brv binary-response-vector) stream)
(qk::print-dim-ref-object brv 'B stream)
brv)
;;; Conversions to (c/c)-proportion-matrix
(defgeneric convert-to-proportion-matrix (response-matrix)
(:documentation
"Converts response-matrix to a categorical-proportion-matrix, a ~
cumulative-proportion-matrix, or a 0/1 (only) binary-response-vector ~
for use by fitting procedures. Returns two ~
values: the proportion-matrix and the weight for each row (ie. total ~
counts.")
)
(defmethod convert-to-proportion-matrix ((y t))
(missing-method 'convert-to-proportion-matrix y))
(defmethod-multi convert-to-proportion-matrix ((y (multinomial-categorical-counts
matrix)))
(let* ((dims (dimensions-of y))
(num-categories (first (last dims)))
(weight (.* y (make-list num-categories :initial-element 1)))
(proportion-matrix (/ (ref y t (iseq 0 (- num-categories 2))) weight)))
(change-class proportion-matrix 'categorical-proportion-matrix)
(values proportion-matrix weight)))
(defmethod convert-to-proportion-matrix ((y multinomial-cumulative-counts))
(let* ((dims (dimensions-of y))
(num-categories (first (last dims)))
(weight (ref y t (- num-categories 1)))
(proportion-matrix (/ (ref y t (iseq 0 (- num-categories 2))) weight)))
(change-class proportion-matrix 'cumulative-proportion-matrix)
(values proportion-matrix weight)))
(defmethod convert-to-proportion-matrix ((y binary-response-vector))
(let* ((dims (dimensions-of y))
(levels (levels-of y))
(num-obs (first dims))
(weight (array 1 :dimensions (list num-obs) :class 'ones-array))
(proportion-matrix (sel y)))
(if (eq (length dims) 1)
; (loop for i from 0 to (1- num-obs) do
(do ((i 0 (incf i)))
((= i num-obs))
(setf (eref proportion-matrix i)
(position (eref y i) levels :test #'equal)))
; (loop for i from 0 to (1- num-obs) do
(do ((i 0 (incf i)))
((= i num-obs))
(setf (eref proportion-matrix i)
(position (eref y i 0) levels :test #'equal))))
(values proportion-matrix weight)))
| 7,704 | Common Lisp | .l | 167 | 38.922156 | 87 | 0.672116 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 1abb098fbc158a2d48c7c1dcbf6ea4b9ae534d4ea669b4139cb52acc28b6d229 | 33,731 | [
-1
] |
33,732 | models-topic-doc.lsp | rwoldford_Quail/source/statistics/models/models-topic-doc.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; models-topic-doc.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1992 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; Greg Anglin 1992.
;;;
;;;
;;;--------------------------------------------------------------------------------
;;;
(setf (doc 'models :topic)
(make-instance 'quail-kernel::topic-documentation
:name
"models"
:doc-capsule
"Statistical Models in Quail"
:doc-elaboration
"Quail provides natural software representations of ~
statistical models through CLOS hierarchies of model, ~
formula, data, and fitted-model classes."
:examples
nil
:references
'("Chambers & Hastie (1991) ~
Statistical Models in S"
"Anglin & Oldford (1993) ~
'Modelling Response Models in Software', ~
4th Intl. Workshop on AI and Statistics"
)
:see-also
nil
:sub-topics
'(
(response-models :topic)
(model :generic-function)
(model-object :class)
(formula-object :class)
(data-frame :generic-function)
(data-frame :class)
(fit :generic-function)
(fit-object :class)
)
:super-topics
NIL
))
(setf (doc 'model-formulae :topic)
(make-instance
'quail-kernel::topic-documentation
:name
"model-formulae"
:doc-capsule
"Formulae for statistical models"
:doc-elaboration
"Quail provides a rich syntax of model formulae. ~
Important special cases are
additive formulae, which represent adaptive predictor functions ~
which are additive in individual predictors, ~
and their subclass of linear formulae for non-adaptive predictor functions."
:examples
nil
:references
'("Chambers & Hastie (1991) ~
Statistical Models in S")
:see-also
'((formula-object :class))
:sub-topics
'((additive-formulae :topic)
(linear-formulae :topic))
:super-topics
NIL
))
(setf (doc 'linear-formulae :topic)
(make-instance
'quail-kernel::topic-documentation
:name
"linear-formulae"
:doc-capsule
"Formulae for additive, non-adaptive response models"
:doc-elaboration
"Linear formulae represent only non-adaptive predictor functions ~
which are additive in individual predictors. Each predictor enters ~
the formula as the predictor ~
multiplied by a parameter. The parameters are not specified ~
explicitly, rather there is implicitly one associated with each ~
additive term."
:examples
nil
:references
'("Chambers & Hastie (1991) ~
Statistical Models in S")
:see-also
'((linear-formula :class))
:sub-topics
nil
:super-topics
NIL
))
(setf (doc 'additive-formulae :topic)
(make-instance
'quail-kernel::topic-documentation
:name
"additive-formulae"
:doc-capsule
"Formulae for additive, adaptive response models"
:doc-elaboration
"Additive formulae represent adaptive predictor functions ~
which are additive in individual predictors. Predictors are ~
permitted to enter the formula as (conceptually) arguments to some class of ~
functions for which non-parametric estimates can be obtained from the ~
predictor and a response. Usually the specification of each additive term ~
indicates which estimator is to be used; for example, for smoothing spline ~
estimates of a predictor x with approximately 3 degrees of freedom, one would ~
use s(x,3)."
:examples
nil
:references
'("Chambers & Hastie (1991) ~
Statistical Models in S"
"Tibshirani & Hastie (1991) ~
Generalized Additive Models")
:see-also
'((additive-formula :class))
:sub-topics
nil
:super-topics
NIL
))
(setf (doc 'response-models :topic)
(make-instance 'quail-kernel::topic-documentation
:name
"response-models"
:doc-capsule
"Models for which a response variable is ~
separable from the predictor variables."
:doc-elaboration
nil
:examples
nil
:references
nil
:see-also
'((generalized-additive-models :topic)
(additive-model :class)
(generalized-linear-models :topic)
(linear-model :class)
(gaussian-linear-model :class))
:sub-topics
'((response-model :class)
(response-formula :class))
:super-topics
NIL
))
(setf (doc 'generalized-additive-models :topic)
(make-instance 'quail-kernel::topic-documentation
:name
"generalized-additive-models"
:doc-capsule
"Generalized Additive Models"
:doc-elaboration
"Generalized Additive Models are CURRENTLY UNIMPLEMENTED."
:examples
nil
:references
'(("Tibshirani & Hastie (1991) ~
Generalized Additive Models"))
:see-also
nil
:sub-topics
'((generalized-additive-model :class)
(additive-formula :class)
(family-object :class)
(link-object :class))
:super-topics
NIL
))
(setf (doc 'generalized-linear-models :topic)
(make-instance 'quail-kernel::topic-documentation
:name
"generalized-linear-models"
:doc-capsule
"Generalized Linear Models"
:doc-elaboration
nil
:examples
nil
:references
'(("McCullagh & Nelder (1983, 1989) ~
Generalized Linear Models"))
:see-also
nil
:sub-topics
'((generalized-linear-model :class)
(linear-formula :class)
(family-object :class)
(link-object :class))
:super-topics
NIL
))
| 7,875 | Common Lisp | .l | 204 | 22.95098 | 88 | 0.458873 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 09c79904386c39795677c4c3bdcad83290fc0b0bc8bbbeae56ae865e99381816 | 33,732 | [
-1
] |
33,733 | formula-object.lsp | rwoldford_Quail/source/statistics/models/formula-object.lsp | (in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(formula-object response-formula
additive-formula linear-formula)))
(defun string-space (x)
(string-downcase (format nil "~S " x)))
;; mf stands for model formula
(defmacro mf (&rest args)
`(apply #'concatenate 'string (mapcar #'string-space (quote ,args))))
(defclass formula-object (quail-object)
((literal :accessor literal-of :initarg :literal
:documentation "string representing the formula.")
(variable-table :accessor variable-table-of :initarg :variable-table
:initform (make-hash-table :test #'equal)
:documentation "hash-table of information ~
about variables in formula."))
(:documentation
"The class of model formulae. ~
(:see-also (model-formulae :topic))")
)
;; for interactive debugging ... see additive-formula-semantics.lisp
(defmethod dump-vtable ((f formula-object))
(dump-vtable (variable-table-of f)))
(defmethod print-object ((f formula-object) stream)
(cond ((slot-boundp f 'literal)
(format stream "#<~S ~S>"
(class-name (class-of f))
(literal-of f)))
(t
(format stream "#<~S ~S>"
(class-name (class-of f))
(qk::system-get-pointer f)))))
(defclass response-formula (formula-object)
((response :accessor response-of :initarg :response
:documentation "name of response in table.")
(predictor-semantics :accessor predictor-semantics-of
:initarg :predictor-semantics
:documentation "semantics of predictor, unreduced."))
(:documentation
"The class of model formulae with an explicit response variable.")
)
(defclass additive-formula (response-formula)
()
(:documentation
"The class of model formulae relating a response to an additive ~
expression in the variables.")
)
(defclass linear-formula (additive-formula)
((reduced-predictors :accessor reduced-predictors-of :initform nil)
(reduced-variables :accessor reduced-variables-of :initform nil)
(coding :accessor coding-of :initform nil))
(:documentation
"The class of model formulae relating to non-adaptive ~
predictor functions which are additive in individual ~
predictors, and each predictor enters the formula as the predictor ~
multiplied by a parameter. The parameters are not specified ~
explicitly, rather there is implicitly one associated with each ~
additive term."))
(defmethod initialize-instance :after ((f additive-formula)
&rest initargs)
(declare (ignore initargs))
(with-slots
(literal variable-table response predictor-semantics) f
(vregister-intercept variable-table)
(let* ((parse-tree (parse :infix literal 0)))
(multiple-value-bind
(resp pred)
(additive-formula-semantics-1 parse-tree variable-table)
(setf response resp)
(setf predictor-semantics (add-intercept! pred)))))
f)
(defmethod initialize-instance :after ((f linear-formula)
&rest initargs)
(declare (ignore initargs))
(formula-encode f)
f)
(defun add-intercept! (pred)
(list 'f+ *intercept* pred))
(defun make-variable-order< (f)
(with-slots (variable-table) f
;; This predicate is probably pretty slow ... could build a faster one.
#'(lambda (x y)
(< (vcount (vfind x variable-table))
(vcount (vfind y variable-table))))))
(defun make-careful-variable-order< (f)
(flet ((formula-variable-not-found (formula variable)
(error "The variable ~S is not part of the formula ~S."
variable formula)))
(with-slots (variable-table) f
;; This predicate is probably pretty slow ... could build a faster one.
#'(lambda (x y)
(< (vcount (or (vfind x variable-table) (formula-variable-not-found f x)))
(vcount (or (vfind y variable-table) (formula-variable-not-found f y))))))))
(defmethod formula-encode ((f linear-formula))
(with-slots (response
predictor-semantics
reduced-predictors
reduced-variables
coding) f
(let ((vo< (make-variable-order< f))
ipredictors)
(setf reduced-predictors (f-reduce predictor-semantics
:f< vo<))
(setf reduced-variables (append (f-variables response)
(f-variables reduced-predictors)))
(setf ipredictors
(mapcar #'(lambda (x)
(mapcar #'(lambda (xx)
(position xx reduced-variables :test #'equal))
x))
(f-remove-ops reduced-predictors)))
(setf coding (compute-coding ipredictors
(length reduced-variables))))))
(defun compute-coding (predictors numvar)
(let* ((numpred (length predictors))
(coding (array nil
:dimensions (list numpred numvar)
:class 'ref-array))
margin
margin-present)
; (loop for i from 0 to (- numpred 1) do
(do ((i 0 (incf i)))
((= i numpred))
; (loop for j from 0 to (- numvar 1) do
(do ((j 0 (incf j)))
((= j numvar))
(when (member j (elt predictors i))
(setf margin (remove j (elt predictors i)))
;; if margin is empty, we have a main effect
(setf margin-present (not margin))
; (loop for ii from 0 to (- i 1)
; while (not margin-present) do
(do ((ii 0 (incf ii)))
((or (= ii i) margin-present))
(progn
(setf margin-present
(equal margin (elt predictors ii)))))
(setf (eref coding i j) (if margin-present
:contrasts
:dummies)))))
coding))
(defun dotted-term-position (dotted-term formula)
(position dotted-term (rest (reduced-predictors-of formula))
:test #'equal))
(defun same-coding-p (dotted-term formula1 formula2 &optional pos1 pos2)
(or pos1
(setq pos1 (dotted-term-position dotted-term formula1)))
(or pos2
(setq pos2 (dotted-term-position dotted-term formula2)))
(flet ((pos-variables (dotted-term formula)
(let ((reduced-variables (reduced-variables-of formula)))
(mapcar #'(lambda (xx)
(position xx reduced-variables :test #'equal))
(rest dotted-term)))))
(let ((vpos1 (pos-variables dotted-term formula1))
(vpos2 (pos-variables dotted-term formula2)))
(loop with same = T
with coding1 = (coding-of formula1)
with coding2 = (coding-of formula2)
while same
for vpos1i in vpos1
as vpos2i in vpos2
do (setq same (eq (eref coding1 pos1 vpos1i)
(eref coding2 pos2 vpos2i)))
finally (return same)))))
(defun compare-dotted-terms-semantics (formula1 formula2 &key (warn T))
;; assumes that formula1 and formula2 have variables sorted in the same order
(let* ((the-same T)
(rp1 (reduced-predictors-of formula1))
(rp2 (reduced-predictors-of formula2))
(dotted-terms-in-both
(loop with pos2
for term in (rest rp1)
as pos1 upfrom 0
when (and (dotted-term-p term)
(setq pos2 (position term (rest rp2) :test #'equal)))
collect (list term pos1 pos2))))
(loop for (dotted-term pos1 pos2) in dotted-terms-in-both
when (not (same-coding-p dotted-term formula1 formula2 pos1 pos2))
do (if warn
(warn "Term ~S has potentially different semantics (and hence encoding) in ~
the two formulae ~S and ~S."
dotted-term formula1 formula2))
(setq the-same NIL))
the-same))
| 8,399 | Common Lisp | .l | 184 | 34.021739 | 98 | 0.583548 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 3491b42223795cfdbab79df1514d2f1d52c041fc19071f540a254da60c926e22 | 33,733 | [
-1
] |
33,734 | orig-link.lsp | rwoldford_Quail/source/statistics/models/orig-link.lsp | (in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(link
def-link
find-link
power-link
)))
(defclass link-object (quail-object)
((name :reader name-of :initarg :name)
(link :reader link-of :initarg :link)
(inverse-link :reader inverse-link-of :initarg :inverse-link))
(:documentation
"
[link] a fn instance
[inverse-link] a fn instance which is the inverse of link"))
(defmethod print-object ((link link-object) stream)
(cond ((slot-boundp link 'name)
(format stream "#<LINK ~S>"
(name-of link)))
(t
(format stream "#<~S ~S>"
(class-name (class-of link))
(qk::system-get-pointer link)))))
(eval-when (:compile-toplevel :load-toplevel)
(defun link-symbol (link-identifier)
(intern (concatenate 'string
(string-upcase
(if (listp link-identifier) ;; ie (quote foo) is a list
(second link-identifier)
link-identifier))
"-LINK")
:quail)))
(defmethod find-link ((link-identifier t))
;; assume it's the right one
(missing-method 'find-link link-identifier))
(defmethod find-link ((link-identifier symbol))
(let (link)
(if (keywordp link-identifier)
(setq link-identifier (intern (symbol-name link-identifier) :quail)))
(if (and (boundp link-identifier)
(typep (setf link (symbol-value link-identifier)) 'link-object))
link
(symbol-value (link-symbol link-identifier)))))
(defmethod find-link ((link-identifier string))
(find-link (intern (string-upcase link-identifier) :quail)))
(defmethod find-link ((link-identifier link-object))
;; assume it's the right one
link-identifier)
(defmacro def-link (link-identifier name link
&key inverse-link link-deriv inverse-link-deriv)
"A macro which simplifies creation of link subclasses."
(let ((foo #'(lambda (fn fn-deriv)
(when fn-deriv (add-deriv fn fn-deriv '(0)))
fn))
(symbol (link-symbol link-identifier)))
`(progn
;; undefine previous versions ... allows easy redefine
(defclass ,symbol () ())
(defclass ,symbol (link-object)
((name :allocation :class :reader name-of
:initform (quote ,name))
(link :allocation :class :reader link-of
:initform (funcall ,foo ,link ,link-deriv))
(inverse-link :allocation :class
:reader inverse-link-of
:initform (funcall ,foo ,inverse-link ,inverse-link-deriv))))
(defvar ,symbol NIL ,name) ;18JUNE2004
(setf ,symbol (make-instance (quote ,symbol)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(export (quote ,symbol) :quail)))))
#| Unnecessary ...
(defun in-bounds-error-chk (x lower upper
&key
(lower-compare-fn #'>=)
(upper-compare-fn #'<=))
"Determines whether the first argument is between the second and third. ~
Comparison functions are given by the keyword arguments ~
lower-compare-fn (default (>= x lower)) ~
and upper-compare-fn (default (<= x upper))."
(if
(and (funcall lower-compare-fn x lower)
(funcall upper-compare-fn x upper))
T
(quail-error "In-bounds-error-chk: Argument ~s out of bounds. ~
lower = ~s upper = ~s." x lower upper)))
|#
(def-link :identity
"Identity: mu"
(fn (mu) mu)
:inverse-link
(fn (eta) eta)
:link-deriv
(fn (mu) 1)
:inverse-link-deriv
(fn (eta) 1))
(def-link :logit
"Logit: (log (/ mu (- 1 mu)))"
(fn (mu)
(log (/ mu (- 1 mu))))
:inverse-link
(fn (eta)
(let ((e-eta (exp eta)))
(/ e-eta (+ 1 e-eta))))
:link-deriv
(fn (mu)
(/ (* mu (- 1 mu))))
:inverse-link-deriv
(fn (eta)
(let* ((e-eta (exp eta))
(1+e-eta (+ 1 e-eta)))
(/ e-eta (* 1+e-eta 1+e-eta))))
)
(def-link :cloglog
"Complimentary log-log: (log (- (log (- 1 mu))))"
(fn (mu) (log (- (log (- 1 mu)))))
:inverse-link
(fn (eta) (let ((e-eta (exp (- eta))))
(- (exp e-eta))))
:link-deriv
(fn (mu)
(let ((1-mu (- 1 mu)))
(- 1 (* 1-mu (log 1-mu)))))
:inverse-link-deriv
(fn (eta)
(- (exp (- (+ eta (exp (- eta)))))))
)
(def-link :log
"Log: (log mu)"
(fn (mu) (log mu))
:inverse-link
(fn (eta) (exp eta))
:link-deriv
(fn (mu) (/ 1 mu))
:inverse-link-deriv
(fn (eta) (exp eta))
)
(def-link :reciprocal
"Reciprocal: (/ 1 mu)"
(fn (mu) (/ 1 mu))
:inverse-link
(fn (eta) (/ 1 eta))
:link-deriv
(fn (mu) (/ -1 (* mu mu)))
:inverse-link-deriv
(fn (eta) (/ -1 eta))
)
(def-link :reciprocal-square
"Reciprocal square: (/ 1 (* mu mu))"
(fn (mu) (/ 1 (* mu mu)))
:inverse-link
(fn (eta) (/ 1 (sqrt eta)))
:link-deriv
(fn (mu) (/ -2 (expt mu 3)))
:inverse-link-deriv
(fn (eta) (* -.5 (expt eta -1.5)))
)
(def-link :sqrt
"Square root: (sqrt mu)"
(fn (mu) (sqrt mu))
:inverse-link
(fn (eta) (* eta eta))
:link-deriv
(fn (mu) (/ 0.5 (sqrt mu)))
:inverse-link-deriv
(fn (eta) (* 2 eta))
)
(defun power-link (power)
"Returns a link-object that is a power transformation mu^power ~
or log(mu) if power is zero."
(let ((link-name (format NIL "Power = ~s: ~s"
power (if (zerop power)
'(log mu)
`(expt mu ,power))))
link-fn inverse-link deriv-link deriv-inverse-link)
(cond
((zerop power)
(setf link-fn (fn (mu) (log mu)))
(setf inverse-link (fn (eta) (exp eta)))
(setf deriv-link (fn (mu) (/ 1 mu)))
(setf deriv-inverse-link (fn (eta) (exp eta))))
(T
(setf link-fn (eval
`(fn (mu) (expt mu , power))))
(setf inverse-link (eval
`(fn (eta) (expt eta ,(/ 1 power)))))
(setf deriv-link (eval
`(fn (mu) (* , power
(expt mu ,(- power 1))))))
(setf deriv-inverse-link (eval
`(fn (eta) (/ (expt eta
,(/ (- 1 power) power))
,power))))))
(flet ((foo (fn fn-deriv)
(when fn-deriv (add-deriv fn fn-deriv '(0)))
fn))
(make-instance 'link-object
:name link-name
:link (foo link-fn deriv-link)
:inverse-link (foo inverse-link deriv-inverse-link))))
)
#|
(def-link :probit
"Probit: (qnorm mu)"
(fn (mu) (qnorm mu))
:inverse-link
(fn (eta) (pnorm eta))
;;:link-deriv
;;(fn (mu) (/ 1 mu))
:inverse-link-deriv
(fn (eta) (norm eta))
)
|#
| 7,341 | Common Lisp | .l | 211 | 25.274882 | 86 | 0.510623 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 2e57ec183f13113cb933182d8c4f73dfde9c0b5d806a7347fcc692d2b045dc66 | 33,734 | [
-1
] |
33,735 | data-object.lsp | rwoldford_Quail/source/statistics/models/data-object.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; data-object.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1992 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; D.G. Anglin 1993-94
;;;
;;;--------------------------------------------------------------------------------
(in-package :quail)
(defclass data-object (quail-object)
())
| 569 | Common Lisp | .l | 17 | 29.176471 | 84 | 0.260073 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 665200f8ff7e9bb63a4094b6a678e4a593cf1bdafe1d45bf90ff650efb099a84 | 33,735 | [
-1
] |
33,736 | glm.lsp | rwoldford_Quail/source/statistics/models/glm.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; glm.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1992 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; Greg Anglin 1992.
;;; ... rwo 93, 95
;;; ... dga 94
;;;
;;;--------------------------------------------------------------------------------
;;;
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(generalized-linear-model generalized-linear-model-fit glm)))
(defclass generalized-linear-model (generalized-additive-model)
((formula :accessor formula-of :initarg :formula :type linear-formula
:documentation "An object of class linear-formula."))
(:documentation
"In this class the formula is restricted to be of class linear-formula. "))
(defmethod model ((model generalized-linear-model)
(formula string)
&rest initargs)
(apply #'model
model
(make-instance 'linear-formula :literal formula)
initargs))
(defmethod model ((model generalized-linear-model)
(formula linear-formula)
&rest initargs)
(apply #'reinitialize-instance model :formula formula initargs)
model)
(defclass generalized-linear-model-fit (generalized-additive-model-fit)
())
(defmethod fit-class ((model generalized-linear-model)
(data data-frame)
(method (eql :maximum-likelihood)))
'generalized-linear-model-fit)
(defmethod initialize-instance :after ((fit generalized-linear-model-fit)
&rest initargs)
(declare (ignore initargs))
(if (and (slot-boundp fit 'data)
(not (slot-boundp fit 'weight)))
(setf (slot-value fit 'weight)
(array 1
:dimensions (list (data-size (slot-value fit 'data)))))))
(defmethod deviance ((fit-obj generalized-linear-model-fit) &key)
(with-slots
(model (mu pred) (y response-matrix) (w weight)) fit-obj
(with-slots (family) model
(deviance family :mu mu :y y :w w))))
(defmethod compute-residuals ((fit-obj generalized-linear-model-fit)
(type (eql :default))
&key)
(compute-residuals fit-obj :deviance))
(defun glm (model-formula
data-frame
&rest keys
&key
(weight nil weight-provided-p)
(methodology :maximum-likelihood)
(offset nil offset-provided-p)
(family nil family-provided-p)
(link nil link-provided-p)
(weight-fn nil weight-fn-provided-p)
(max-iter 50)
(tolerance 1e-7)
(start nil start-provided-p)
(verbose *terminal-io*))
(declare (ignore keys))
;; the following is now handled in fit ... rwo
;;(when (not (typep data-frame 'data-frame))
;; (setf data-frame (data-frame data-frame
;; (copy-list (list-variates data-frame)))))
(let (model-initargs model fit)
(setf model-initargs (mapcan #'(lambda (pred key value)
(and pred (list key value)))
(list family-provided-p
link-provided-p
weight-fn-provided-p
offset-provided-p)
(list :family :link :weight-fn :offset)
(list family link weight-fn offset)))
(setf model (apply #'model
'generalized-linear-model
model-formula
model-initargs))
(apply #'fit
model
data-frame
:fit-object fit
:methodology methodology
:max-iter max-iter
:tolerance tolerance
:verbose verbose
(append
(and weight-provided-p (list :weight weight))
(and start-provided-p (list :start start))))
;; returns fit
))
(defun ensure-zero-weights-effective (weight 1d-object)
(loop for i upto (1- (first (dimensions-of weight)))
when (zerop (eref weight i))
do (setf (eref 1d-object i) 0.0))
1d-object)
(defmethod fit-using-methodology ((model generalized-linear-model)
(data data-frame)
(methodology (eql :maximum-likelihood))
&rest keys
&key
fit-object
weight
(max-iter 50)
(tolerance 1e-3)
(start nil start-provided-p)
(verbose *terminal-io*)
&allow-other-keys)
(declare (ignore weight))
(if (not fit-object)
(setf fit-object (apply #'fit-instantiate
model
data
methodology
keys)))
(if (eq verbose t)
(setf verbose *terminal-io*))
(with-slots
(model-frame
model-matrix
response-matrix
weight
model
pred
coef
resid
(df model-degrees-of-freedom)
;;rank
deviance)
fit-object
(with-slots
(family
(link-obj link)
weight-fn
offset)
model
(multiple-value-setq (response-matrix weight start)
(initialize-response family
;; get rid of unimportant NaNs etc, right now.
(ensure-zero-weights-effective weight
response-matrix)
weight))
(with-slots
(link inverse-link)
link-obj
(let (eta mu deriv)
(if start-provided-p
(progn
(setf eta start)
(setf mu (fn-call inverse-link eta)))
(progn
(setf mu start)
(setf eta (fn-call link mu))))
(setf deriv (find-deriv link))
(let* ((new-dev (deviance family
:mu mu
:y response-matrix
:w weight))
(old-dev (cl:+ 10 (cl:* 10 new-dev)))
(iter 0)
(wls-model (make-instance 'gaussian-linear-model))
(wls-fit (fit-instantiate wls-model
model-frame
:least-squares
:model-frame model-frame
:model-matrix model-matrix
))
deriv-mu
converged)
(with-slots
((zmm model-matrix)
(z response-matrix)
(zw weight)
(zresid resid)
(zcoef coef)
(zqrs qr-solution)
;;(zrank rank)
(zdf model-degrees-of-freedom))
wls-fit
;; valid, but unnecessary ...
;; (setf zmm model-matrix)
(loop
while
(and
(not converged)
(cl:< iter max-iter))
do
(progn
(incf iter)
(setf deriv-mu (fn-call deriv mu))
(setf z (+ eta
(- offset)
(* (- response-matrix mu) deriv-mu)))
(setf zw (fn-call weight-fn mu weight))
;;
;; this next is here because by now, if weight[i]==0,
;; then probably mu[i] == nan => zw[i]==nan ..
;;
(setf zw (ensure-zero-weights-effective weight zw))
(setf z (ensure-zero-weights-effective weight z))
;;
(setf zqrs nil) ;; kill qr-solution from previous fit !!!
(fit wls-model model-frame :fit-object wls-fit
:resid t :coef t :tolerance tolerance)
(setf eta (+ (- z zresid) offset))
(setf mu (fn-call inverse-link eta))
;;(inspect (list eta mu))
(setf old-dev new-dev)
(setf new-dev (deviance family
:mu mu
:y response-matrix
:w weight))
(setf converged
(or (and (eq link-obj identity-link)
(eq family gaussian-family))
(cl:<
(abs
(cl:/
(cl:- old-dev new-dev)
(cl:+ old-dev tolerance)))
tolerance)))
(if verbose
(format verbose
"~&Deviance at iteration ~S is ~S~%"
iter new-dev))
))
(if (not converged)
(warn "Failed to achieve convergence in ~S iterations."
max-iter))
(setf pred mu)
(setf deviance new-dev)
(setf resid zresid)
(setf coef zcoef)
;;(setf rank zrank)
(setf df zdf)))))))
fit-object)
| 10,211 | Common Lisp | .l | 249 | 24.032129 | 126 | 0.431777 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 74e2656cb2dd15833b683bab1127402452e125b077c265accbb4a032ff6300f5 | 33,736 | [
-1
] |
33,737 | model-object.lsp | rwoldford_Quail/source/statistics/models/model-object.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; model-object.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1992 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; Greg Anglin 1992, 1995.
;;;
;;;
;;;--------------------------------------------------------------------------------
;;;
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(model-object response-model model)))
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(formula-of)))
(defclass model-object (quail-object)
()
(:documentation
"Abstract class at the top of the hierarchy of model objects."))
(defclass response-model (model-object)
((formula :accessor formula-of :initarg :formula
:documentation "an object of class formula.")
(predictor-fn :accessor predictor-fn-of :initarg :predictor-fn
:documentation "a function producing the value of the predictor ~
(eta) from predictor values provided by a single argument ~
of class fit-object and optional keyword args."))
(:documentation
"The class of models for which the response variable is separable from the ~
predictor variables."
))
(defmethod print-object ((rm response-model) stream)
(cond ((and (slot-boundp rm 'formula)
(slot-boundp (formula-of rm) 'literal))
(format stream "#<~S ~S>"
(class-name (class-of rm))
(literal-of (formula-of rm))))
(t
(format stream "#<~S ~S>"
(class-name (class-of rm))
(qk::system-get-pointer rm)))))
;; a quick attempt at a model-maker
(defgeneric model (model formula
&rest initargs)
(:documentation
"Initializes a model object of class specified by model ~
with associated formula. ~
(:elaboration Initializes and returns an instance of a subclass of model-object ~
corresponding to model, formula, and (method-specific) initargs.) ~
(:required ~
(:arg model ~
The argument model ~
may be either a symbol naming a subclass of model-object or an instance of a ~
subclass of model-object requiring initialization. When model ~
is a symbol, the generic function is applied again to arguments (make-instance ~
model) formula initargs. When model is an instance of a subclass of ~
model-object, this same instance is returned by the generic function, fully ~
initialized.) ~
(:arg formula ~
The argument formula ~
may be either a string specifying a model formula or an instance of a subclass ~
of formula-object. When formula is a string, the generic function is applied ~
again to args model, an instance of a subclass of formula-object, ~
and initargs. The appropriate subclass is determined by the class of ~
argument model and by the nature of the formula itself.) ~
)~
(:rest ~
initargs ~
These are parsed from the &rest list by individual methods. ~
which methods determine which initargs are applicable.) ~
")
)
(defmethod model ((model symbol) formula &rest initargs)
"This method handles the case when model is a symbol naming a subclass ~
of model-object. (:elaboration This method simply applies the model generic ~
function to args (make-instance ~
model) formula initargs. Usually at this point formula is a string.)"
(apply #'model (make-instance model) formula initargs))
(defmethod model ((model standard-class) formula &rest initargs)
"This method handles the case when model is a class which is a subclass ~
of model-object. (:elaboration This method simply applies the model generic ~
function to args (make-instance ~
model) formula initargs. Usually at this point formula is a string.)"
(apply #'model (make-instance model) formula initargs))
| 4,147 | Common Lisp | .l | 87 | 40.931034 | 102 | 0.625248 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 13f9b3dddfaddaaa4cc9c24d92a0e7581dfb2db4a4b486c88b6d73e91dabd2a0 | 33,737 | [
-1
] |
33,738 | factor.lsp | rwoldford_Quail/source/statistics/models/factor.lsp | (in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(factor-object
nominal-factor
ordinal-factor
interval-factor
binary-factor
factor-array
nominal-factor-array
ordinal-factor-array
interval-factor-array
binary-factor-array
)))
(defclass factor-object (ref-object)
((levels :accessor levels-of :initarg :levels))
(:documentation
"The abstract class of categorical variables. ~
If a factor-object is instantiated, an instance of subclass nominal-factor ~
will be created. ~%~
[levels] the possible values the variable may take."))
(defmethod num-levels ((factor factor-object))
(with-slots (levels) factor
(length levels)))
(defclass nominal-factor (factor-object)
()
(:documentation
"A subclass of factor-object for which the levels of the factor are purely nominal; ~
in models involving these factors, levels should be exchangeable without ~
impacting inferences."))
(defclass ordinal-factor (factor-object)
()
(:documentation
"A restriction of class factor-object to the case when there is an order on the ~
levels of the factor. This is encoded as (elt levels i) < (elt levels j) ~
whenever i < j, but the numerical value of each level in the encoding is ~
not otherwise meaningful."))
(defclass interval-factor (ordinal-factor)
()
(:documentation
"A restriction of class ordinal-factor to the case when the ~
levels of the factor are numerical. The ~
numerical value of the factor is meaningful and is used to ~
encode the factor in a response-matrix or model-matrix."))
(defclass binary-factor (ordinal-factor)
()
(:documentation
"A restriction of class ordinal-factor to the case when there ~
are only two levels of the factor. The first level is always ~
encoded as 0 and the second level as 1 in a response-matrix ~
or model-matrix."))
(defclass factor-array (ref-array factor-object) ())
(defclass nominal-factor-array (factor-array nominal-factor) ())
(defclass ordinal-factor-array (factor-array ordinal-factor) ())
(defclass interval-factor-array (ordinal-factor-array interval-factor) ())
(defclass binary-factor-array (ordinal-factor-array binary-factor) ())
(defmethod make-ref-array ((self factor-array) dimensions &rest rest)
;; allows more specific methods to manipulate levels ..
;; cf. binary-response-vector
(if (not (slot-boundp self 'levels))
(multiple-value-bind (levels extra)
(qk::interpret-keys-only rest
'(:levels)
'make-ref-array
t)
(setf (levels-of self) levels)
(apply #'call-next-method self dimensions extra))
;; on this branch, rest has already had :levels removed
(apply #'call-next-method self dimensions rest)))
(defmethod ref ((r factor-array) &rest args)
(let ((ref-r (ref-instantiate r)))
(ref-kernel ref-r r args)))
(defmethod ref-instantiate ((r factor-array))
(make-instance 'factor-array))
(defmethod ref-kernel ((ref-r factor-array) r args)
(apply #'call-next-method ref-r r args)
(setf (levels-of ref-r) (levels-of r)))
(defmethod print-object ((fac factor-array) stream)
(qk::print-dim-ref-object fac 'FAC stream)
fac)
#|
;; too confusing ... do later ...
(defmethod as-factor ((x ref-array) &key class levels)
(typecase factor-specifier
(null )
(factor-object (change-class x (class-of factor-specifier))
(setf (levels-of x) (levels-of factor-specifier))
x)
((standard-class symbol)
(change-class x factor-specifier)
(set-levels x factor-levels)
x)))
|#
| 3,949 | Common Lisp | .l | 91 | 35.692308 | 89 | 0.657053 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | bd92ff2e45ee5b7910954a618b9121727c69600509b86ab22ebbe8de7918ac77 | 33,738 | [
-1
] |
33,739 | formula-reduce.lsp | rwoldford_Quail/source/statistics/models/formula-reduce.lsp | (in-package :quail)
(defvar *f-remove-p* nil)
(defvar *f<* nil)
(defvar *intercept* "1")
(defvar *negative-intercept* "-1")
(defun f-reduce (formula &key (f-remove-p nil) (f< nil))
(declare (special *f-remove-p* *f<*))
(if (not *f-remove-p*)
(setf *f-remove-p* #'(lambda (x) (declare (ignore x)) t)))
(if (not *f<*)
(setf *f<* #'string<))
;; properly, this should be set up with unwind-protect
(let ((old-f-remove-p *f-remove-p*)
(old-f< *f<*))
(if f-remove-p
(setf *f-remove-p* f-remove-p))
(if f<
(setf *f<* f<))
(prog1
(f-sort (f-reduce-1 formula))
(setf *f-remove-p* old-f-remove-p)
(setf *f<* old-f<))))
;;; I'm trying to use the following naming conventions:
;;; "fterm" or "fterms" looks like (f-op arg1 arg2 arg3 ..) or an atom
;;; "term" or "terms" looks like (arg1 arg2 arg3 ...)
;;; where f-op is like f+, f*, f., etc, and each arg is an fterm.
;;; "reduced-fterms" like fterm except satisfies f-reduced-p
;;; "reduced-terms" like (rest x), x is a non-atom reduced-fterm.
(defun simple-dotted-fterm-p (fterm)
"Returns non-nil if fterm is an atom or is of form (f. atom1 atom2 ...)"
(or (atom fterm)
(and (eq (first fterm) 'f.)
(> (length fterm) 2)
(let ((all-atoms t))
(loop for a in (rest fterm)
until (not all-atoms)
do (setf all-atoms (atom a)))
all-atoms))))
(defun dotted-term-p (term)
(and (listp term) (simple-dotted-fterm-p term)))
(defun f-reduced-p (fterms)
"Returns non-nil if fterms satistfies simple-dotted-fterm-p or is ~%~
of form (f+ simple-dotted-fterm-1 simple-dotted-fterm-2 ...)"
(or (simple-dotted-fterm-p fterms)
(and (eq (first fterms) 'f+)
(let ((all-simple t))
(loop for fterm in (rest fterms)
until (not all-simple)
do (setf all-simple (simple-dotted-fterm-p fterm)))
all-simple))))
(defun f-reduce-1 (fterms)
(if (f-reduced-p fterms)
(f-cancel fterms)
(f-reduce-2 (first fterms) (rest fterms))))
(defun f-sort (reduced-fterms)
(cond ((atom reduced-fterms) reduced-fterms)
((eq (first reduced-fterms) 'f.)
(list* 'f. (f.-sort (rest reduced-fterms))))
((eq (first reduced-fterms) 'f+)
(list* 'f+ (f+-sort (rest reduced-fterms))))))
(defun f.-sort (reduced-terms)
(declare (special *f<*))
(sort (copy-list reduced-terms) *f<*))
(defun f+-sort (reduced-terms)
(let ((r (mapcar #'f-sort reduced-terms)))
(sort (copy-list r) #'simple-dotted<)))
(defun f-cancel (fterms)
(cond ((atom fterms) fterms)
((eq (first fterms) 'f.)
(let ((c (f.-cancel (rest fterms))))
(if c
(list* 'f. c)
nil)))
((eq (first fterms) 'f+)
(let ((c (f+-cancel (rest fterms))))
(if c
(list* 'f+ c)
nil)))))
#|
(defun f.-cancel (terms)
(declare (special *f-remove-p*))
(remove-duplicates terms
:test #'(lambda (x y)
(and (equal x y)
(funcall *f-remove-p* x)))))
|#
;; add the f.-sort here to help f+-cancel with
;; e.g. (f+ (f. "x1" "x2") (f. "x2" "x1"))
;; as early as possible
(defun f.-cancel (terms)
(declare (special *f-remove-p*))
(remove-duplicates (f.-sort terms)
:test #'(lambda (x y)
(and (equal x y)
(funcall *f-remove-p* x)))))
(defun simple-dotted< (x y)
(declare (special *f<*))
(cond ((and (atom x) (atom y))
(funcall *f<* x y))
((atom x) t)
((atom y) nil)
((< (length x) (length y)) t)
((> (length x) (length y)) nil)
(t (let (done answer)
;; from 1, not 0 !!
(loop for xx in (rest x)
as yy in (rest y)
until done
do (when (string/= xx yy)
(setf done t)
(setf answer (funcall *f<* xx yy))))
answer))))
(defun f+-cancel (terms)
(declare (special *intercept* *negative-intercept*))
(setf terms (remove nil terms))
(let ((new-terms (remove-duplicates (mapcar #'f-cancel terms)
:test #'equal)))
;; should work OK with :test #'eql
(if (and (member *intercept* new-terms)
(member *negative-intercept* new-terms))
(remove *intercept*
(remove *negative-intercept* new-terms))
new-terms)))
(defun f-variables (fterms)
"Returns all the atoms involved at any depth in fterms."
(cond ((stringp fterms) (list fterms))
(t
(f+-cancel
(loop for tt in fterms
append (cond ((symbolp tt) nil)
((stringp tt) (list tt))
(t (f-variables tt))))))))
(defun f-remove-ops (reduced-fterms)
(if (atom reduced-fterms)
(f-variables reduced-fterms)
(mapcar #'f-variables (rest reduced-fterms))))
(defmethod f-reduce-2 ((kind (eql 'f+)) args)
(let* ((new-args
(loop for arg in args
append (cond ((atom arg) (list arg))
((eq (first arg) 'f+)
(rest arg))
(t (list (f-reduce-1 arg))))))
(new-f (list* 'f+ new-args)))
(f-reduce-1 new-f)))
(defun first-if-list (x)
(if (listp x)
(first x)
x))
(defmethod f-reduce-2 ((kind (eql 'f.)) args)
(let* ((new-args
(loop for arg in args
append (cond ((atom arg) (list arg))
((eq (first arg) 'f.)
(rest arg))
(t (list (f-reduce-1 arg))))))
(first-f+ (position-if #'(lambda (x) (eq x 'f+)) new-args
:key #'first-if-list :from-end t))
new-f)
(if first-f+
(let ((the-f+ (elt new-args first-f+)))
(setf args (remove the-f+ new-args :test #'equal :count 1))
(setf new-f
(list* 'f+
(loop for item in (rest the-f+)
collect (list* 'f. item args)))))
(setf new-f (if (eq 1 (length new-args))
(first new-args)
(list* 'f. new-args))) )
(f-reduce-1 new-f)))
(defmethod f-reduce-2 ((kind (eql 'f*)) args)
(f-reduce-1
(case (length args)
;; this case can only happen as x**1
(1 (first args))
;; this is the usual case
(2 (list 'f+ (first args) (second args) (list* 'f. args)))
;; this case is rare, occurring only as a result of x**n, n>2.
(t (list 'f* (first args) (list* 'f* (rest args)))))))
(defmethod f-reduce-2 ((kind (eql 'f**)) args)
;; args of length 2, (second args) an integer >0
(f-reduce-1 (list* 'f* (make-sequence 'list (second args)
:initial-element (first args)))))
(defmethod f-reduce-2 ((kind (eql 'f/)) args)
;; We assume args is of length 2
(let ((left (f-reduce-1 (first args)))
(right (second args)))
(f-reduce-1
(list 'f+
left
(cond ((simple-dotted-fterm-p left) (list 'f. right left))
(t (list* 'f. right (f-variables left))))))))
(defun f-remove (args test)
;; We assume args is of length 2
(let ((left (f-reduce-1 (first args)))
(right (f-reduce-1 (second args))))
(f-reduce-1
(cond ((simple-dotted-fterm-p left)
(cond ((equal left right) nil)
(t (error "Can't remove ~S from ~S." right left))))
((simple-dotted-fterm-p right)
(cond ((member right left :test test)
(remove right left :test test))
(t (error "Can't remove ~S from ~S." right left))))
(t
(let ((reduced left))
(loop for right-arg in (rest right)
do (setf reduced
(cond ((member right-arg left :test test)
(remove right-arg reduced :test test))
(t
(error "Can't remove ~S from ~S." right left)))))
reduced))))))
(defmethod f-reduce-2 ((kind (eql 'f-)) args)
(declare (special *intercept* *negative-intercept*))
(cond ((and (eq (length args) 1)
(equal (first args) *intercept*))
*negative-intercept*)
((equal (second args) *intercept*)
(list 'f+ (first args) *negative-intercept*))
(t
(f-remove args #'equal))))
(defun simple-dotted-subfactor (x y)
(cond ((atom y) (equal x y))
((atom x) (member x (rest y) :test #'equal))
(t (let ((all-there t)
(remaining (rest y)))
(loop for xx in (rest x)
while all-there
do (progn
(setf all-there (member xx remaining :test #'equal))
(setf remaining (remove xx remaining :test #'equal :count 1))))
all-there))))
(defmethod f-reduce-2 ((kind (eql 'f-*)) args)
(f-remove args #'simple-dotted-subfactor))
(defmethod f-reduce-2 ((kind (eql 'f-/)) args)
;; We assume args is of length 2
(let ((left (f-reduce-1 (first args)))
(right (f-reduce-1 (second args))))
(f-reduce-1 (list 'f+ (list 'f-* left right) right))))
| 9,880 | Common Lisp | .l | 240 | 29.754167 | 88 | 0.496639 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | f83b38040b6d87c49691ebb3798bc9103fe3f335877e273eea2ec370f1deb9b6 | 33,739 | [
-1
] |
33,740 | link.lsp | rwoldford_Quail/source/statistics/models/link.lsp | (in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(link
def-link
find-link
power-link
)))
(defclass link-object (quail-object)
((name :reader name-of :initarg :name)
(link :reader link-of :initarg :link)
(inverse-link :reader inverse-link-of :initarg :inverse-link))
(:documentation
"
[link] a fn instance
[inverse-link] a fn instance which is the inverse of link"))
(defmethod print-object ((link link-object) stream)
(cond ((slot-boundp link 'name)
(format stream "#<LINK ~S>"
(name-of link)))
(t
(format stream "#<~S ~S>"
(class-name (class-of link))
(qk::system-get-pointer link)))))
(eval-when (:compile-toplevel :load-toplevel)
(defun link-symbol (link-identifier)
(intern (concatenate 'string
(string-upcase
(if (listp link-identifier) ;; ie (quote foo) is a list
(second link-identifier)
link-identifier))
"-LINK")
:quail)))
(defmethod find-link ((link-identifier t))
;; assume it's the right one
(missing-method 'find-link link-identifier))
(defmethod find-link ((link-identifier symbol))
(let (link)
(if (keywordp link-identifier)
(setq link-identifier (intern (symbol-name link-identifier) :quail)))
(if (and (boundp link-identifier)
(typep (setf link (symbol-value link-identifier)) 'link-object))
link
(symbol-value (link-symbol link-identifier)))))
(defmethod find-link ((link-identifier string))
(find-link (intern (string-upcase link-identifier) :quail)))
(defmethod find-link ((link-identifier link-object))
;; assume it's the right one
link-identifier)
#| replaced 16Aug2004 based on spr29116
(defmacro def-link (link-identifier name link
&key inverse-link link-deriv inverse-link-deriv)
"A macro which simplifies creation of link subclasses."
(let ((foo #'(lambda (fn fn-deriv)
(when fn-deriv (add-deriv fn fn-deriv '(0)))
fn))
(symbol (link-symbol link-identifier)))
`(progn
;; undefine previous versions ... allows easy redefine
(defclass ,symbol () ())
(defclass ,symbol (link-object)
((name :allocation :class :reader name-of
:initform (quote ,name))
(link :allocation :class :reader link-of
:initform (funcall ,foo ,link ,link-deriv))
(inverse-link :allocation :class
:reader inverse-link-of
:initform (funcall ,foo ,inverse-link ,inverse-link-deriv))))
(defvar ,symbol NIL ,name) ;18JUNE2004
(setf ,symbol (make-instance (quote ,symbol)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(export (quote ,symbol) :quail)))))
|#
;;;; start of stuff from spr29116
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun add-deriv-for-def-link (fn fn-deriv)
(when fn-deriv (add-deriv fn fn-deriv '(0)))
fn)
)
(defmacro def-link (link-identifier name link
&key inverse-link link-deriv inverse-link-deriv)
"A macro which simplifies creation of link subclasses."
(let ((symbol (link-symbol link-identifier)))
`(progn
;; undefine previous versions ... allows easy redefine
#+why??? (defclass ,symbol () ())
(defclass ,symbol (link-object)
((name :allocation :class :reader name-of
:initform (quote ,name))
(link :allocation :class :reader link-of
:initform (add-deriv-for-def-link ,link ,link-deriv))
(inverse-link :allocation :class
:reader inverse-link-of
:initform (add-deriv-for-def-link ,inverse-link
,inverse-link-deriv))))
(defvar ,symbol NIL ,name) ;18JUNE2004
(setf ,symbol (make-instance (quote ,symbol)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(export (quote ,symbol) :quail)))))
;;;; End of stuff from spr29116
#| Unnecessary ...
(defun in-bounds-error-chk (x lower upper
&key
(lower-compare-fn #'>=)
(upper-compare-fn #'<=))
"Determines whether the first argument is between the second and third. ~
Comparison functions are given by the keyword arguments ~
lower-compare-fn (default (>= x lower)) ~
and upper-compare-fn (default (<= x upper))."
(if
(and (funcall lower-compare-fn x lower)
(funcall upper-compare-fn x upper))
T
(quail-error "In-bounds-error-chk: Argument ~s out of bounds. ~
lower = ~s upper = ~s." x lower upper)))
|#
(def-link :identity
"Identity: mu"
(fn (mu) mu)
:inverse-link
(fn (eta) eta)
:link-deriv
(fn (mu) 1)
:inverse-link-deriv
(fn (eta) 1))
(def-link :logit
"Logit: (log (/ mu (- 1 mu)))"
(fn (mu)
(log (/ mu (- 1 mu))))
:inverse-link
(fn (eta)
(let ((e-eta (exp eta)))
(/ e-eta (+ 1 e-eta))))
:link-deriv
(fn (mu)
(/ (* mu (- 1 mu))))
:inverse-link-deriv
(fn (eta)
(let* ((e-eta (exp eta))
(1+e-eta (+ 1 e-eta)))
(/ e-eta (* 1+e-eta 1+e-eta))))
)
(def-link :cloglog
"Complimentary log-log: (log (- (log (- 1 mu))))"
(fn (mu) (log (- (log (- 1 mu)))))
:inverse-link
(fn (eta) (let ((e-eta (exp (- eta))))
(- (exp e-eta))))
:link-deriv
(fn (mu)
(let ((1-mu (- 1 mu)))
(- 1 (* 1-mu (log 1-mu)))))
:inverse-link-deriv
(fn (eta)
(- (exp (- (+ eta (exp (- eta)))))))
)
(def-link :log
"Log: (log mu)"
(fn (mu) (log mu))
:inverse-link
(fn (eta) (exp eta))
:link-deriv
(fn (mu) (/ 1 mu))
:inverse-link-deriv
(fn (eta) (exp eta))
)
(def-link :reciprocal
"Reciprocal: (/ 1 mu)"
(fn (mu) (/ 1 mu))
:inverse-link
(fn (eta) (/ 1 eta))
:link-deriv
(fn (mu) (/ -1 (* mu mu)))
:inverse-link-deriv
(fn (eta) (/ -1 eta))
)
(def-link :reciprocal-square
"Reciprocal square: (/ 1 (* mu mu))"
(fn (mu) (/ 1 (* mu mu)))
:inverse-link
(fn (eta) (/ 1 (sqrt eta)))
:link-deriv
(fn (mu) (/ -2 (expt mu 3)))
:inverse-link-deriv
(fn (eta) (* -.5 (expt eta -1.5)))
)
(def-link :sqrt
"Square root: (sqrt mu)"
(fn (mu) (sqrt mu))
:inverse-link
(fn (eta) (* eta eta))
:link-deriv
(fn (mu) (/ 0.5 (sqrt mu)))
:inverse-link-deriv
(fn (eta) (* 2 eta))
)
(defun power-link (power)
"Returns a link-object that is a power transformation mu^power ~
or log(mu) if power is zero."
(let ((link-name (format NIL "Power = ~s: ~s"
power (if (zerop power)
'(log mu)
`(expt mu ,power))))
link-fn inverse-link deriv-link deriv-inverse-link)
(cond
((zerop power)
(setf link-fn (fn (mu) (log mu)))
(setf inverse-link (fn (eta) (exp eta)))
(setf deriv-link (fn (mu) (/ 1 mu)))
(setf deriv-inverse-link (fn (eta) (exp eta))))
(T
(setf link-fn (eval
`(fn (mu) (expt mu , power))))
(setf inverse-link (eval
`(fn (eta) (expt eta ,(/ 1 power)))))
(setf deriv-link (eval
`(fn (mu) (* , power
(expt mu ,(- power 1))))))
(setf deriv-inverse-link (eval
`(fn (eta) (/ (expt eta
,(/ (- 1 power) power))
,power))))))
(flet ((foo (fn fn-deriv)
(when fn-deriv (add-deriv fn fn-deriv '(0)))
fn))
(make-instance 'link-object
:name link-name
:link (foo link-fn deriv-link)
:inverse-link (foo inverse-link deriv-inverse-link))))
)
#|
(def-link :probit
"Probit: (qnorm mu)"
(fn (mu) (qnorm mu))
:inverse-link
(fn (eta) (pnorm eta))
;;:link-deriv
;;(fn (mu) (/ 1 mu))
:inverse-link-deriv
(fn (eta) (norm eta))
)
|#
| 8,668 | Common Lisp | .l | 240 | 26.4875 | 86 | 0.523342 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 061cd8d81a27bda6fe54ff50e1f94a2218d59a315132a7daf00badd9661d0992 | 33,740 | [
-1
] |
33,741 | residuals.lsp | rwoldford_Quail/source/statistics/models/residuals.lsp | (in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(residuals compute-residuals)))
(defgeneric residuals (fit-obj &key type &allow-other-keys))
(defmethod residuals (fit-obj &key (type :default)
&allow-other-keys)
(compute-residuals fit-obj type))
(defgeneric compute-residuals (fit-obj type &key &allow-other-keys))
(defmethod compute-residuals ((fit-obj response-model-fit)
(type (eql :deviance)) &key)
(with-slots
((mu pred) (y response-matrix) (w weight)) fit-obj
(* (map-element #'signum nil (- y mu))
(map-element #'sqrt nil
(* w (fn-call
(deviances-fn-of (family-of fit-obj))
mu y))))))
(defmethod compute-residuals ((fit-obj response-model-fit)
(type (eql :working)) &key)
(with-slots
(resid) fit-obj
resid))
(defmethod compute-residuals ((fit-obj response-model-fit)
(type (eql :response)) &key)
(with-slots
((y response-matrix) (mu pred)) fit-obj
(- y mu)))
(defmethod compute-residuals ((fit-obj response-model-fit)
(type (eql :pearson)) &key)
;; need working weights, which we haven't stored ...
;; also assume resid has been filled
(with-slots ((w weight) (mu pred) resid) fit-obj
(* (sqrt (fn-call (find-weight-fn (family-of fit-obj)
(link-of fit-obj))
mu w))
resid))
)
| 1,620 | Common Lisp | .l | 36 | 32.805556 | 96 | 0.551348 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | c418464816e717dfbb5f00ae5a93f1242212089ad6d9da0527f5d8c6deb13b08 | 33,741 | [
-1
] |
33,742 | gamfit-1.lsp | rwoldford_Quail/source/statistics/models/gamfit-1.lsp | (in-package :quail)
(defmethod special-formula-operator-handler
((operator-symbol (eql :s)) formula operator-name &rest ensured-args)
"Creates an smoothing-spline-variable for the variable given ~
by (first ensured-args), which must be univariate. ~
(rest ensured-args) may contain keywords and ~
arguments for either :spar (smoothing parameter) or ~
:df (equivalent degrees of freedom), ~
which otherwise will be chosen by the fitting routine ~
by cross-validation."
;(declare (ignore operator-symbol formula operator-name ensured-args))
(declare (ignorable operator-symbol formula operator-name ensured-args))
(error "Special formula operator s(...) has not yet ~
been implemented.")
)
;;; parse and additive-semantics are ready to go ... just do this stuff now!!
| 833 | Common Lisp | .l | 16 | 46.875 | 81 | 0.720787 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 7533581a1e01f2c04c9f70d0dda07a3b2857f26f5b67b89601449c4102624280 | 33,742 | [
-1
] |
33,743 | family.lsp | rwoldford_Quail/source/statistics/models/family.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; family.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; (c) Copyright Statistical Computing Laboratory
;;; University of Waterloo
;;; 1995
;;;
;;; Authors:
;;; D.G. Anglin 1992
;;; R.W. Oldford 1995
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(*families*
family-object
def-family
find-family)))
(defvar *families*
NIL
"A variable containing all currently defined families.")
(defclass family-object (quail-object)
((name :reader name-of :initarg :name)
(variance-fn :reader variance-fn-of :initarg :variance-fn)
(deviances-fn :reader deviances-fn-of :initarg :deviances-fn))
(:documentation
"
[name] name of the family
[variance-fn] a fn producing variance as a function of the mean
for a single observation from this family
[deviances-fn] a fn producing deviances as a function of means and
observed responses for collection of
observations from this family."))
(defmethod print-object ((family family-object) stream)
(cond ((slot-boundp family 'name)
(format stream "#<FAMILY ~S>"
(name-of family)))
(t
(format stream "#<~S ~S>"
(class-name (class-of family))
(qk::system-get-pointer family)))))
(eval-when (:compile-toplevel :load-toplevel)
(defun family-symbol (family-identifier)
(intern (concatenate 'string
(string-upcase
(if (listp family-identifier) ;; ie (quote foo) is a list
(second family-identifier)
family-identifier))
"-FAMILY")
:quail)))
(defmethod find-family ((family-identifier t))
;; assume it's the right one
(missing-method 'find-family family-identifier))
(defmethod find-family ((family-identifier symbol))
(let (family)
(if (keywordp family-identifier)
(setq family-identifier (intern (symbol-name family-identifier) :quail)))
(if (and (boundp family-identifier)
(typep (setf family (symbol-value family-identifier)) 'family-object))
family
(symbol-value (family-symbol family-identifier)))))
(defmethod-multi find-family ((family-identifier string))
(find-family (intern (string-upcase family-identifier) :quail)))
(defmethod find-family ((family-identifier family-object))
;; assume it's the right one
family-identifier)
(defmacro def-family (family-identifier name &key variance-fn deviances-fn)
"A macro which simplifies creation of family subclasses."
(let ((symbol (family-symbol family-identifier)))
`(progn
;; (declare (special *families*))
;; this first defclass is certain to destroy previous versions
;; this is necessary due to :initform weirdness
;(defclass ,symbol () ())
(defclass ,symbol (family-object)
((name :allocation :class :reader name-of :initform (quote ,name))
(variance-fn :allocation :class
:reader variance-fn-of :initform ,variance-fn)
(deviances-fn :allocation :class
:reader deviances-fn-of :initform ,deviances-fn)))
(defvar ,symbol NIL ,name)
(unless (member ,symbol *families*)
(push ,symbol *families*))
(setf ,symbol (make-instance (quote ,symbol)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(export (quote ,symbol) :quail))
,symbol)))
(def-family :gaussian
"Gaussian (constant variance function)"
:variance-fn
(fn (mu) (declare (ignore mu)) 1)
:deviances-fn
(fn (mu y) (expt (- y mu) 2)))
(defun log{x}-or-zero (x)
(if (and (numberp x) (zerop x))
0.0
(qk::ext_log x)))
(defun log{x/u}-or-zero (x u)
(if (and (numberp x) (zerop x))
0.0
(qk::ext_log (qk::ext_/ x u))))
(def-family :binomial
"Binomial"
:variance-fn
(fn (mu) (* mu (- 1 mu)))
:deviances-fn
(fn (mu y)
(labels ((alogb (a b) (* a (log{x}-or-zero b)))
(aloga (a) (alogb a a))
(fdevym (yi mi) (+ (alogb yi mi)
(alogb (- 1 yi) (- 1 mi))))
(fdevy (yi) (+ (aloga yi)
(aloga (- 1 yi)))))
(let* (devy devym)
(setf devy (map-element #'fdevy nil y))
;; This computation is currently unsafe when mu[i] is 0 or 1
(setf devym (map-element #'fdevym nil y mu))
(* 2 (- devy devym))))))
(def-family :poisson
"Poisson"
:variance-fn
(fn (mu) mu)
:deviances-fn
(fn (mu y)
(labels
((devym (yi mi)
(+ mi (- yi) (* yi (log{x/u}-or-zero yi mi)))))
(map-element #'devym nil y mu))))
(def-family :gamma
"Gamma"
:variance-fn
(fn (mu) (* mu mu))
:deviances-fn
(fn (mu y)
(labels
((devym (yi mi)
(- (qk::ext_/ (qk::ext_- yi mi) mi)
(log{x/u}-or-zero yi mi))))
(map-element #'devym nil y mu))
))
(def-family :inverse-gaussian
"Inverse Gaussian"
:variance-fn
(fn (mu) (expt mu 3))
:deviances-fn
(fn (mu y)
(/ (- y mu) 1/2 (* mu mu) y)
))
(defgeneric initialize-response (family response weight)
(:documentation
"Returns three values: response-matrix, weights, and starting values for ~
the glm fit.")
;; cf. fit method for generalized-linear-model-fit in glm.lisp
)
(defmethod initialize-response ((f family-object) response weight)
(missing-method 'initialize-response f response weight))
;; In the following methods:
;; the ref collapses the dimensions -- could be done easier maybe.
;; the sel provides a new instance to hold starting values.
;; these need some work to help preserve eq-ness when possible
#|
;;; Mapply is gone. The following function is replaced
;;; by substitute-slices-if in initialize-response
;;; Seems like a bizarre initialization ... rwo
(defun replace-zeros-with-1/6 (1d-object)
(mapply #'(lambda (r)
(let ((rr (eref r)))
(if (> rr 0)
rr
1/6)))
(list 1d-object t)))
|#
(defmethod initialize-response ((f gaussian-family) response weight)
(values (ref response) (ref weight) (sel response)))
(defmethod initialize-response ((f binomial-family) response weight)
(let (n mu)
(setf n (.* response '(1 1)))
(setf response (/ (ref response t 0) n))
(setf weight (* weight n))
(setf mu (+ response (/ (- 1/2 response) n)))
(values (ref response) (ref weight) (ref mu))))
(defmethod-multi initialize-response ((f (poisson-family
gamma-family
inverse-gaussian-family))
response
weight)
(values (ref response)
(ref weight)
(substitute-slices-if 1/6
#'(lambda (r) (<= (eref r) 0))
response)))
| 7,569 | Common Lisp | .l | 193 | 30.284974 | 84 | 0.550232 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 8ed5bf0812160c7902181f05de7f68145c931574c26a209f8f2bad37f3946f96 | 33,743 | [
-1
] |
33,744 | lsfit.lsp | rwoldford_Quail/source/statistics/models/lsfit.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; lsfit.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1990 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; Michael Lewis 1991.
;;; Greg Anglin 1992.
;;; R.W. Oldford 1995.
;;;
;;;--------------------------------------------------------------------------------
;;; just a change so I could add a comment to the rlog. ... rwo
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(lsfit)))
;-------------------------------------------------------------------------
;GENERIC FUNCTION: lsfit
;-------------------------------------------------------------------------
(defgeneric lsfit (x &rest keyword-args &key qy qty coef resid pred
&allow-other-keys)
(:documentation
"Args: x, a gaussian-linear-model-fit object. ~%~
On return, the same gaussian-linear-model-fit object with the least squares ~
solution computed."))
(defmethod lsfit ((self gaussian-linear-model-fit)
&rest keyword-args
&key qy qty coef resid pred
&allow-other-keys)
(declare (ignore keyword-args))
(with-slots (response-matrix
model-matrix
weight
qr-solution
(lsfit-df model-degrees-of-freedom)
(lsfit-coef coef)
(lsfit-resid resid)
(lsfit-pred pred))
self
(let* ((y (apply-weight weight response-matrix))
(x (apply-weight weight model-matrix))
solve-coef
)
(unless qr-solution
(multiple-value-setq
(solve-coef qr-solution)
(solve x y :qy qy :qty qty :coef coef :resid resid :fit pred)))
(setf lsfit-df (rank-of qr-solution))
(if coef (setf lsfit-coef solve-coef))
(if resid (setf lsfit-resid (resid-of qr-solution)))
(if pred (setf lsfit-pred (pred-of qr-solution)))
(if qy (qy-of qr-solution))
(if qty (qty-of qr-solution))
self
)))
;-----
(defmethod lsfit :after ((self gaussian-linear-model-fit)
&rest keyword-args
&key qy qty coef resid pred
&allow-other-keys)
(declare (ignore keyword-args qy qty))
(with-slots (model-matrix
response-matrix
weight
qr-solution
(lsfit-coef coef)
(lsfit-pred pred)
(lsfit-resid resid)) self
(with-slots (pivot jpvt)
(qrd-of qr-solution)
(if pivot
;; unpivot the coefficients
(if coef (setf lsfit-coef (unpivot-in-place lsfit-coef jpvt))))
(if weight
;; remove the weights from the residuals
;; and predictors
(cond ((null weight))
((and (mat1dp weight)
(or resid pred))
(let ((inv-wt-factor (matrix-sqrt (/ weight))))
(if pred (setf lsfit-pred (* lsfit-pred inv-wt-factor)))
(if resid (setf lsfit-resid (* lsfit-resid inv-wt-factor)))
(if (loop with no-zeros = t
for ii upto (1- (first (dimensions-of weight)))
while no-zeros
;; take a chance we won't see a symbol ... need ext_zerop
when (zerop (eref weight ii 0))
do (setf no-zeros nil)
finally (return (not no-zeros)))
(let* ((wt-zero (multiple-position-if weight #'zerop))
(x0 (ref model-matrix wt-zero))
(y0 (ref response-matrix wt-zero))
(pred0 (.* x0 lsfit-coef)))
(if resid (setf (ref lsfit-resid wt-zero) (- y0 pred0)))
(if pred (setf (ref lsfit-pred wt-zero) pred0))))))
((and (mat2dp weight)
(or resid pred))
(with-slots ((cholesky-a a)
(cholesky-info info))
(cholesky-of weight)
(if (not (= (eref cholesky-info) (first (dimensions-of weight))))
(progn
(setf lsfit-pred (.* model-matrix lsfit-coef))
(setf lsfit-resid (- response-matrix lsfit-pred)))
(let (work-resid work-pred (job 01))
(if resid
(progn
(setf work-resid lsfit-resid)
(dtrls cholesky-a work-resid job)
(setf lsfit-resid work-resid)))
(if pred
(progn
(setf work-pred lsfit-pred)
(dtrls cholesky-a work-pred job)
(setf lsfit-pred work-pred))))))))))))
| 5,522 | Common Lisp | .l | 118 | 29.957627 | 85 | 0.442556 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 68ea108e2f52e338c2ebd6a83745fa835755a9d366bd6086aba2e40190ca9a75 | 33,744 | [
-1
] |
33,745 | partlink.lsp | rwoldford_Quail/source/statistics/models/partlink.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; partlink.lsp
;;;
;;; 21JUNE2004
;;;
;;; Holding bits of link.lsp which
;;; demonstrate the crash in link-checks.lsp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; (un)fortunately, what it below works as quail
;;; expects it should !
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; first a package
(defpackage "WAYNE"
(:use "COMMON-LISP")
(:nicknames "IGOR"))
;;; then the in-package
(in-package :igor)
;;; the definition of the class link-object
(defclass link-object ()
((name :reader name-of :initarg :name))
)
;;; now the definition of link-symbol
;;; modified for the new package
(eval-when (:compile-toplevel :load-toplevel)
(defun link-symbol (link-identifier)
(intern (concatenate 'string
(string-upcase
(if (listp link-identifier) ;; ie (quote foo) is a list
(second link-identifier)
link-identifier))
"-LINK")
:igor)))
;;; and so to the macro
(defmacro def-link (link-identifier name link)
"A macro which simplifies creation of link subclasses."
(let ((symbol (link-symbol link-identifier)))
`(progn
;; undefine previous versions ... allows easy redefine
(defclass ,symbol () ())
(defclass ,symbol (link-object)
((name :allocation :class :reader name-of
:initform (quote ,name))))
(defvar ,symbol NIL ,name)
(setf ,symbol (make-instance (quote ,symbol)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(export (quote ,symbol) :igor)))))
;;; finally an example of def-link
(def-link :identity
"Identity: mu"
#'(lambda (z) z))
| 1,834 | Common Lisp | .l | 51 | 28.72549 | 82 | 0.542421 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 17364296392ab999e711df73faf69252b9446a81afe5844d4bba5cbc29300282 | 33,745 | [
-1
] |
33,746 | display.lsp | rwoldford_Quail/source/statistics/models/display.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; display.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1993
;;;
;;;
;;;
;;;----------------------------------------------------------------------------------
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(display)))
(defmethod display ((model generalized-linear-model) &rest grid-plot-args
&key
(draw? T)
(color wb::*white-color*)
(title NIL)
&allow-other-keys)
(unless title
(setf title
(format NIL "Model summary: ~s." (class-name (class-of model)))))
(let*
((link (link-of model))
(formula (formula-of model))
(family (family-of model))
(formula-label (label :viewed-object "Formula:"
:draw? NIL
:justification '(:left :top)))
(link-label (label :viewed-object "Link:"
:draw? NIL
:justification '(:left :top)))
(family-label (label :viewed-object "Family:" :draw? NIL
:justification '(:left :top)))
(formula-value (text-view
:viewed-object formula
:text (literal-of formula)
:draw? NIL))
(link-value (text-view
:viewed-object link
:text (name-of link)
:draw? NIL))
(family-value (text-view
:viewed-object family
:text (name-of family)
:draw? NIL))
(view-layout (grid-layout
:viewed-object model
:subviews (list formula-label formula-value
link-label link-value
family-label family-value
)
:nrows 3 :box-views? NIL
:gap-x 0.1 :gap-y 0.1))
(result
(apply #'grid-plot
:viewed-object model
:interior-view view-layout :gap-x 0.1 :gap-y 0.1
:title title
:draw? NIL
:color color
grid-plot-args)))
(when draw?
(draw-view result))
result))
(defmethod display ((fit generalized-linear-model-fit) &rest grid-plot-args
&key
(draw? T)
(color wb::*white-color*)
(title NIL)
&allow-other-keys)
(unless title
(setf title
(format NIL "Summary of ~s." (class-name (class-of fit)))))
(let*
((model (model-of fit))
(formula (formula-of model))
(response-name (response-of formula))
(model-display (display model :draw? NIL))
(predictor-matrix (model-matrix-of fit))
(response (response-matrix-of fit))
(deviance (deviance-of fit))
(df (model-degrees-of-freedom-of fit))
(deviance-result (array (list deviance
df
(- 1.0 (dist-chi deviance :df df)))
:dimensions '(1 3)))
deviance-display
(working-resids (residuals fit :type :working))
(response-resids (residuals fit :type :response))
(deviance-resids (residuals fit :type :deviance))
(pearson-resids (residuals fit :type :pearson))
(n (first (dimensions-of working-resids)))
(pred (pred-of fit))
(index (seq 1 n))
(fitted-data (cglue index pred
working-resids
response-resids
deviance-resids
pearson-resids
response
predictor-matrix))
big-layout
result
ctrl-middle-items
(fitted-value-name "Fitted Values"))
(dataset fitted-data
:identifiers (list-identifiers response)
:variates (append (list "Index" fitted-value-name
"Working Residuals"
"Response Residuals"
"Deviance Residuals"
"Pearson Residuals"
response-name)
(list-variates predictor-matrix)))
(dataset deviance-result :variates (list "Deviance" "d.f." "Significance"))
(setf deviance-display (display deviance-result :draw? NIL :title NIL
:row-labels? NIL))
(setf big-layout (grid-layout :viewed-object fit
:subviews (list model-display deviance-display)
:nrows 2 :box-views? t
:gap-x 0.1 :gap-y 0.1))
(setf result
(apply #'grid-plot :interior-view big-layout :gap-x 0.1 :gap-y 0.1
:title title
:draw? NIL
:color color
grid-plot-args))
(setf ctrl-middle-items
(list
(list "Residual plots" NIL
"Produce residual plots for this fit."
:sub-items
(list (list "Rotating plot"
#'(lambda (&rest args)
(declare (ignore args))
(let*
((resid-plot
(rotating-plot :data fitted-data
:x "Index"
:y "Deviance Residuals"
:z fitted-value-name
:draw? T
:title (literal-of formula)
:link? T))
)
(link-view (interior-view-of resid-plot))
resid-plot
)
)
"Produce a rotating plot of the residuals.")
(list "Residuals vs index"
#'(lambda (&rest args)
(declare (ignore args))
(let*
((resid-plot
(scatterplot
:data fitted-data
:x "Index"
:y "Deviance Residuals"
:draw? T
:title (literal-of formula)))
)
(link-view (interior-view-of resid-plot))
resid-plot
)
)
"Produce a plot of the residuals versus their index.")
(list "Residuals vs fit"
#'(lambda (&rest args)
(declare (ignore args))
(let*
((resid-plot
(scatterplot
:data fitted-data
:x fitted-value-name
:y "Deviance Residuals"
:draw? T
:title (literal-of formula)))
)
(link-view (interior-view-of resid-plot))
resid-plot
)
)
"Produce a plot of the residuals versus the predictor.")
(list "Histogram"
#'(lambda (&rest args)
(declare (ignore args))
(let*
((resid-plot
(histogram
:data fitted-data
:y "Deviance Residuals"
:draw? T
:title (literal-of formula))
)
)
(link-view (interior-view-of resid-plot))
resid-plot
)
)
"Histogram of the residuals.")
(list "QQ-gauss"
#'(lambda (&rest args)
(declare (ignore args))
(let*
((resid-plot
(qq-gauss deviance-resids
:bottom-label "Deviance Residuals"
:draw? T
:title (literal-of formula)))
)
(link-view (interior-view-of resid-plot))
resid-plot
)
)
"Histogram of the residuals.")
(list "Scatterplot-matrix"
#'(lambda (&rest args)
(declare (ignore args))
(let*
((resid-plot
(scat-mat
:data fitted-data
:draw? T
:title (literal-of formula)))
)
(link-view (interior-view-of resid-plot))
resid-plot
)
)
"Produce a scatterplot matrix of the results.")))
(list "Diagnostics" NIL
"Produce some diagnostic plots."
:sub-items
(list (list "Goodness of link"
#'(lambda (&rest args)
(declare (ignore args))
(inform-user "Unimplemented")
)
"Produce a diagnostic plot ~
for assessing the link function.")
(list "Variance function"
#'(lambda (&rest args)
(declare (ignore args))
(inform-user "Unimplemented")
)
"Produce a diagnostic plot ~
for assessing the variance function.")
))
(list "Analysis" NIL
"Produce some analytic results."
:sub-items
(list
(list "Coefficients"
#'(lambda (&rest args)
(declare (ignore args))
(let*
((coefs (coef-of fit)))
(dataset
coefs
:identifiers (list-variates predictor-matrix)
:variates '("Estimate:"))
(display
coefs
:draw? T
:title "Coefficient estimates.")
))
"Produce a display of the estimated coefficients.")
(list "Analysis of Deviance"
#'(lambda (&rest args)
(declare (ignore args))
(inform-user "Unimplemented")
)
"Produce a plot of the residuals versus their index.")
))))
(when draw?
(draw-view result)
(let ((view-window (window-of (first (viewports-of result)))))
(setf (wb::middle-title-items-of view-window)
ctrl-middle-items)
(wb::install-title-menus view-window)
(wb::set-up-title-menus view-window :title-middle "Model Assessment"))
)
result
))
| 13,673 | Common Lisp | .l | 292 | 22.047945 | 86 | 0.343095 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 98fb1da5a32b1d2329ef2a01c63dc4cfdfbee801e7470674dee3a8130e9acb09 | 33,746 | [
-1
] |
33,747 | partlink-1.lsp | rwoldford_Quail/source/statistics/models/partlink-1.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; partlink-1.lsp
;;;
;;; 21JUNE2004
;;;
;;; Holding bits of partlink.lsp which
;;; demonstrate the crash in link-checks.lsp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; We start from all of partlink
;;; and try adding pieces
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; first a package
(defpackage "WAYNE"
(:use "COMMON-LISP")
(:nicknames "IGOR"))
;;; then the in-package
(in-package :igor)
;;; the definition of the class link-object
;;;1
(defclass link-object ()
((name :reader name-of :initarg :name))
)
;;; now the definition of link-symbol
;;; modified for the new package
(eval-when (:compile-toplevel :load-toplevel)
(defun link-symbol (link-identifier)
(intern (concatenate 'string
(string-upcase
(if (listp link-identifier) ;; ie (quote foo) is a list
(second link-identifier)
link-identifier))
"-LINK")
:igor)))
;;; and so to the macro
(defmacro def-link (link-identifier name link)
"A macro which simplifies creation of link subclasses."
(let ((symbol (link-symbol link-identifier)))
`(progn
;; undefine previous versions ... allows easy redefine
(defclass ,symbol () ())
(defclass ,symbol (link-object)
((name :allocation :class :reader name-of
:initform (quote ,name))))
(defvar ,symbol NIL ,name)
(setf ,symbol (make-instance (quote ,symbol)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(export (quote ,symbol) :igor)))))
;;; finally an example of def-link
(def-link :identity
"Identity: mu"
#'(lambda (z) z))
| 1,830 | Common Lisp | .l | 51 | 28.588235 | 82 | 0.542565 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | edce9bfe7c784846192a628ec9f5165b75de5d8510c352853d74b22b03d720ca | 33,747 | [
-1
] |
33,748 | least-squares-mixin.lsp | rwoldford_Quail/source/statistics/models/least-squares-mixin.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; least-squares-mixin.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1990 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; Michael Lewis 1991.
;;; Greg Anglin 1992.
;;;
;;;
;;;--------------------------------------------------------------------------------
;;;
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(least-squares-mixin)))
;--------------------------------------------------------------------------
; CLASS: least-squares-mixin
;--------------------------------------------------------------------------
(defclass least-squares-mixin ()
((qrd :initarg :qrd :initform nil :accessor qrd
:documentation
"QR decomposition used in calculations.")
(qy :initarg :qy :initform nil :accessor qy
:documentation
"QY is the vector: Q times y, where y is the response matrix")
(qty :initarg :qty :initform nil :accessor qty
:documentation
"QTY is the vector: transpose(Q) times y, ~
where y is the response matrix") )
(:documentation
"Least squares fits have this class as a superclass"))
| 1,431 | Common Lisp | .l | 35 | 34.885714 | 89 | 0.415706 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | c5f5a28fe2f77c1cf814ae23b2db9efe608a4cdcb8fbf31b0cb571fab965cdfa | 33,748 | [
-1
] |
33,749 | families | rwoldford_Quail/source/statistics/models/models_testing,_etc/families | Script started on Wed Jul 17 15:49:23 1991
[r S statistics
> print.default(gaussian())
$family:
name link variance
"Gaussian" "Identity: mu" "Constant: 1"
$names:
[1] "Identity: mu"
$link:
function(mu)
mu
$inverse:
function(eta)
eta
$deriv:
function(mu)
1
$initialize:
expression(mu <- y, maxit <- 1)
$variance:
function(mu)
1
$deviance:
function(mu, y, w, residuals = F)
if(residuals) (y - mu) else sum(w * (y - mu)^2)
$weight:
expression(w)
attr(, "class"):
[1] "family"
> print.default(binomial())
$family:
name link variance
"Binomial" "Logit: log(mu/(1 - mu))" "Binomial: mu(1-mu)"
$names:
[1] "Logit: log(mu/(1 - mu))"
$link:
function(mu)
log(mu/(1 - mu))
$inverse:
function(eta)
{
junk <- care.exp(eta)
junk/(1 + junk)
}
$deriv:
function(mu)
{
d <- 1/(mu * (1 - mu))
if(any(huge <- is.na(d))) {
warning("Model unstable; fitted probabilities of 0 or 1")
d[huge] <- 1/.Machine$double.eps
}
d
}
$initialize:
expression({
if(is.matrix(y)) {
if(dim(y)[2] > 2)
stop("only binomial response matrices (2 columns)")
n <- drop(y %*% c(1, 1))
y <- y[, 1]
}
else {
if(is.category(y))
y <- as.numeric(y) - 1
else y <- as.vector(y)
n <- rep(1, length(y))
}
y <- y/n
w <- w * n
mu <- y + (0.5 - y)/n
}
)
$variance:
function(mu)
mu * (1 - mu)
$deviance:
function(mu, y, w, residuals = F)
{
devy <- y
nz <- y != 0
devy[nz] <- y[nz] * log(y[nz])
nz <- (1 - y) != 0
devy[nz] <- devy[nz] + (1 - y[nz]) * log(1 - y[nz])
devmu <- y * log(mu) + (1 - y) * log(1 - mu)
if(any(small <- is.na(devmu))) {
warning("fitted values close to 0 or 1")
smu <- mu[small]
sy <- y[small]
smu <- ifelse(smu < .Machine$double.eps, .Machine$double.eps,
smu)
onemsmu <- ifelse((1 - smu) < .Machine$double.eps, .Machine$
double.eps, 1 - smu)
devmu[small] <- sy * log(smu) + (1 - sy) * log(onemsmu)
}
devi <- 2 * (devy - devmu)
if(residuals)
sign(y - mu) * sqrt(devi * w)
else sum(w * devi)
}
$weight:
expression(w * mu * (1 - mu))
attr(, "class"):
[1] "family"
> print.default(poisson())
$family:
name link variance
"Poisson" "Log: log(mu)" "Identity: mu"
$names:
[1] "Log: log(mu)"
$link:
function(mu)
log(mu)
$inverse:
function(eta)
care.exp(eta)
$deriv:
function(mu)
1/mu
$initialize:
expression({
if(!is.null(dimy <- dim(y))) {
if(dimy[2] > 1)
stop("multiple responses not allowed")
else y <- drop(y)
}
mu <- y + 0.167 * (y == 0)
}
)
$variance:
function(mu)
mu
$deviance:
function(mu, y, w, residuals = F)
{
nz <- y > 0
devi <- - (y - mu)
devi[nz] <- devi[nz] + y[nz] * log(y[nz]/mu[nz])
if(residuals)
sign(y - mu) * sqrt(2 * devi * w)
else 2 * sum(w * devi)
}
$weight:
expression(w * mu)
attr(, "class"):
[1] "family"
> q()
% exit
%
script done on Wed Jul 17 15:50:20 1991
| 3,602 | Common Lisp | .l | 150 | 17.046667 | 78 | 0.467922 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | c618baeb05ca80f238f620e0e49cb584f58caf18925cc210e990a2f5e684f7e2 | 33,749 | [
-1
] |
33,750 | simple-drop+add-test.lsp | rwoldford_Quail/source/statistics/models/models_testing,_etc/simple-drop+add-test.lsp | (in-package q)
(setq x0 (list 1 2 3 4 5 1 2 3 4 5))
(setq x1 (* x0 x0))
(setq x (cglue x0 x1))
(setq y (+ 3 (* 4 x0) (* 5 x1) (random-gaussian :n (first (dimensions-of x0))
:location 0.0
:scale 2)))
(setq d (data-frame (list y x) (list "y" "x")))
(setq fit1 (lm "y ~ x" d))
(setq fit2 (lm "y ~ x[t 0]" d))
(setq fit3 (lm "y ~ x[t (:c 1)]" d))
;; fails ... too complicated to fix, though ...
(setq fit4 (lm "y ~ x - x[t 0]" d))
;;;;
(setq x2 (array (list 1 2 2 3 3 1 2 2 3 3) :class 'factor-array :levels '(1 2 3)))
(setq d2 (data-frame (list y x0 x1 x2) (list "y" "x0" "x1" "x2")))
(setq fit5 (lm "y ~ x0 + x2 + x0.x2" d2))
(setq fit6 (drop fit5 "x2.x0"))
(setq fit7 (drop fit6 "x2"))
;;
(setq fit8 (add fit7 "x2"))
(setq fit9 (add fit8 "x2.x0"))
;;; something a little bit different!
(setq fit10 (drop fit5 "x0"))
(setq fit11 (add fit10 "x0")) | 1,003 | Common Lisp | .l | 25 | 32.84 | 83 | 0.510096 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | f142da217a36b87c3f5ccf39a5f749a82044c0d1ff2877088330f9e39da86786 | 33,750 | [
-1
] |
33,751 | family_copy.lsp | rwoldford_Quail/source/statistics/models/models_testing,_etc/family_copy.lsp | (in-package :quail)
(export '(family gaussian binomial))
(defclass family (quail-object)
((name :reader name-of :initarg :name)
(variance-fn :reader variance-fn-of :initarg :variance-fn)
(deviance-fn :reader deviance-fn-of :initarg :deviance-fn))
(:documentation
"
[name] name of the family
[variance-fn] a fn producing variance as a function of the mean
for a single observation from this family
[deviance-fn] a fn producing deviance as a function of means,
observed responses, and weights for collection of
observations from this family."))
(defmethod print-object ((family family) stream)
(cond ((slot-boundp family 'name)
(format stream "#<FAMILY subclass ~S>"
(name-of family)))
(t
(format stream "#<~S ~S>"
(class-name (class-of family))
(qk::system-get-pointer family)))))
(defmacro def-family (symbol name &key variance-fn deviance-fn)
"A macro which simplifies creation of family subclasses."
`(progn
(defclass ,symbol (family)
((name :allocation :class :reader name-of :initform (quote ,name))
(variance-fn :allocation :class
:reader variance-fn-of :initform ,variance-fn)
(deviance-fn :allocation :class
:reader deviance-fn-of :initform ,deviance-fn)))
(defvar ,symbol NIL ,name)
(setf ,symbol (make-instance (quote ,symbol)))))
(def-family gaussian
"Gaussian (constant variance function)"
:variance-fn
(fn (mu) 1)
:deviance-fn
(fn (mu y w &optional residuals)
(let ((e (- y mu)))
(if residuals
e
(.* w (* e e))))))
#|
(def-family gaussian
"Gaussian (constant variance function)"
:variance-fn
(fn (mu) 1)
:deviances-fn
(fn (mu y) (- y mu)))
|#
(def-family binomial
"Binomial"
:variance-fn
(fn (mu) (* mu (- 1 mu)))
:deviance-fn
(fn (mu y w &optional residuals)
(labels ((xlogy (x y) (if (zerop y)
0
(* x (base-lisp::log y))))
(xlogx (x) (xlogy x x))
(devxy (x y) (+ (xlogy x y)
(xlogy (- 1 x) (- 1 y))))
(devx (x) (+ (xlogx x)
(xlogx (- 1 x)))))
(let* (devy devmu devi)
(setf devy (map-element #'devx nil y))
;; This computation is currently unsafe when mu[i] is 0 or 1
(setf devmu (map-element #'devxy nil y mu))
(setf devi (* 2 (- devy devmu)))
(if residuals
(* (map-element #'signum nil (- y mu))
(map-element #'sqrt nil (* devi w)))
(.* w devi))))))
;; these need some work to help preserve eq-ness when possible
(defmethod initialize-response ((f family) response weight)
(missing-method 'initialize-response f response weight))
(defmethod initialize-response ((f gaussian) response weight)
(values (ref response) (ref weight) (sel response)))
(defmethod initialize-response ((f binomial) response weight)
(let (n mu)
(setf n (.* response '(1 1)))
(setf response (/ (ref response t 0) n))
(setf weight (* weight n))
(setf mu (+ response (/ (- 0.5 response) n)))
(values (ref response) (ref weight) (ref mu))))
(def-family poisson
"Poisson"
:variance-fn
(fn (mu) mu)
:deviance-fn
(fn (mu y w &optional residuals)
))
(def-family gamma
"Gamma"
:variance-fn
(fn (mu) (* mu mu))
:deviance-fn
(fn (mu y w &optional residuals)
))
(def-family inverse-gaussian
"Inverse Gaussian"
:variance-fn
(fn (mu) (expt mu 3))
:deviance-fn
(fn (mu y w &optional residuals)
)) | 3,890 | Common Lisp | .l | 107 | 27.738318 | 74 | 0.566506 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | b5bc507c56c2543473bb53feb28d270f4d7ce1a3ce26395ee63fc0aced69cb55 | 33,751 | [
-1
] |
33,752 | calib-data.lsp | rwoldford_Quail/source/statistics/models/models_testing,_etc/calib-data.lsp | (in-package q)
(setf calib (data-frame (list (array '(10) :initial-contents
'(4.0 8.0 12.5 16.0 20.0 25.0
31.0 36.0 40.0 40.0))
(array '(10) :initial-contents
'(3.7 7.8 12.1 15.6 19.8 24.5
31.1 35.5 39.4 39.5))
(array '(10 1) :initial-contents
'((3.7) (7.8) (12.1) (15.6) (19.8) (24.5)
(31.1) (35.5) (39.4) (39.5))))
(list "x" "y" "ymat")))
(setf f1 (lm "y ~ x" calib))
(setf f2 (lm "y ~ -1 + x" calib))
(setf f3 (lm "ymat ~ -1 + x" calib)) | 771 | Common Lisp | .l | 14 | 30.5 | 80 | 0.322281 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 0f4ed94ce33f33de5911cbbc828ec1dff37a797f8cc76be8a2c1f4408bfe794e | 33,752 | [
-1
] |
33,753 | slm.out | rwoldford_Quail/source/statistics/models/models_testing,_etc/slm.out | Working data will be in /usr/people/dganglin/.Data
> add1.lm
function(object, scope = . ~ ., scale, keep, x = NULL)
{
add.all <- function(qr, effect, x, assgn, tol = .Machine$double.eps^
0.5)
{
dx <- dim(x)
n <- as.integer(dx[1])
p <- as.integer(dx[2])
pold <- as.integer(length(qr$pivot))
number <- as.integer(length(assgn))
lngth <- as.integer(sapply(assgn, length))
start <- as.integer(sapply(assgn, "[[", 1))
.Fortran("addall",
x = x,
n,
p,
start,
lngth,
number,
effect,
effects = matrix(0, n, number),
pivot = integer(p),
rank = integer(number),
chisq = double(number),
pold,
qr$qr,
qr$qraux,
qr$pivot,
qr$rank,
double(3 * p + n),
tol)[c("x", "effects", "chisq", "pivot", "rank")]
}
p <- length(object$coef)
if(!is.character(scope))
scope <- add.scope(object, update.formula(object, scope,
evaluate = F))
if(!length(scope))
stop("no terms in scope for adding to object")
if(is.null(x)) {
# when called iteratively x can be known
# need to do the following since the scope might be a character vector of term labels
add.rhs <- paste(scope, collapse = "+")
add.rhs <- eval(parse(text = paste("~ . +", add.rhs)))
new.form <- update.formula(object, add.rhs, evaluate = F)
fc <- object$call
Terms <- terms(new.form)
fc$formula <- Terms
fob <- list(call = fc)
class(fob) <- class(object)
m <- model.frame(fob)
x <- model.matrix(Terms, m)
}
cnames <- dimnames(x)[[2]]
iswt <- !is.null(wt <- object$weights)
if(iswt)
x <- x * sqrt(wt)
n <- dim(x)[[1]]
asgn <- attr(x, "assign")
tl <- names(asgn)
if(!all(match(scope, tl, F)))
stop("scope is not a subset of term labels of the supplied x")
xasgn <- unlist(asgn[names(object$assign)])
asgn <- asgn[scope]
k <- length(scope)
rdf <- object$df.resid
chisq <- deviance.lm(object)
if(missing(scale))
scale <- sqrt(chisq/rdf)
if(!missing(keep)) {
max.keep <- c("coefficients", "fitted", "residuals",
"x.residuals", "effects", "R")
if(is.logical(keep) && keep)
keep <- max.keep
else {
if(!all(match(keep, max.keep, F)))
stop(paste("Can only keep one or more of: \"",
paste(max.keep, collapse = "\", \""),
"\"", sep = ""))
}
fv <- predict(object)
y <- object$residuals + fv
if(iswt) {
if(any(wt == 0))
stop(
"\"keep\" not allowed when some of the weights are zero"
)
wt <- sqrt(wt)
}
}
else keep <- character(0)
xr <- match("x.residuals", keep, F)
value <- array(vector("list", 6 * k), c(k, 6), list(scope, c(
"coefficients", "fitted", "residuals", "x.residuals", "effects",
"R")))
if(length(ef <- object$effects) < n)
stop(
"function only currently defined for methods that compute effects"
)
dfs <- double(k)
chis <- double(k)
R <- object$R
if(length(xasgn))
oldx <- x[, xasgn, drop = F]
else stop("need a term or an intercept in initial model")
qR <- object$qr
if(is.null(qR)) {
qR <- qr(oldx)
}
if(xr) {
xresid <- qr.resid(qR, x[, unlist(asgn)])
if(iswt)
xresid <- xresid/wt
}
newx <- x[, unlist(asgn), drop = F]
newnames <- cnames[unlist(asgn)]
TT <- rep(T, (p + length(newnames)))
TT[xasgn] <- F
asgn <- assign.sub(asgn, TT)
addall <- add.all(qR, ef, newx, asgn)
chis <- addall$chis
dfs <- addall$rank
if(length(keep)) {
pivot <- addall$pivot
newqr <- addall$x
effects <- addall$effects
Rnames <- dimnames(R)[[1]]
oldrank <- object$rank
oldns <- !is.na(object$coef)
oldns <- seq(oldns)[oldns]
for(i in 1:k) {
asgni <- asgn[[i]]
ranki <- dfs[i]
pivoti <- pivot[asgni]
pi <- length(asgni)
if(xr) {
value[[i, 4]] <- xresid[, asgni]
}
newrank <- oldrank + ranki
goodcols <- seq(newrank)
nR <- newqr[oldrank + seq(pi), asgni, drop = F]
nR[lower.tri(nR)] <- 0
nR <- rbind(newqr[seq(oldrank), pivoti, drop = F],
nR)
rnames <- c(Rnames, newnames[pivoti])
r <- array(0, c(p + pi, p + pi), list(rnames, rnames))
r[seq(p), seq(p)] <- R
r[seq(oldrank + pi), seq(pi) + p] <- nR
#reshuffle R if it was rank defficient
if(Tr <- p - oldrank)
r <- r[, c(seq(oldrank), seq(pi) + p, seq(
Tr) + oldrank)]
efi <- effects[, i]
names(efi) <- c(dimnames(r)[[2]][goodcols], rep("",
n - newrank))
attr(r, "rank") <- newrank
class(r) <- "upper"
bi <- backsolve(r[goodcols, goodcols], efi[goodcols])
#now slot in the NAs
if(Tr | (pi - ranki)) {
Bi <- rep(NA, p + pi)
names(Bi) <- c(cnames[xasgn], newnames[asgni])
if(ranki) {
TT <- (pivoti - asgni[1] + 1)[seq(
ranki)]
Bi[c(oldns, p + TT)] <- bi
fvi <- cbind(oldx[, oldns, drop = F],
newx[, asgni[TT]]) %*% bi
}
else {
Bi[seq(p)] <- object$coef
fvi <- object$fitted
}
bi <- Bi
}
else fvi <- cbind(oldx, newx[, asgni]) %*% bi
if(iswt)
fvi <- fvi/wt
value[i, -4] <- list(bi, fvi, y - fvi, efi, r)
}
}
scope <- c("<none>", scope)
dfs <- c(0, dfs)
chis <- c(chisq, chis)
aics <- chis + 2 * (n - rdf + dfs) * scale^2
dfs[1] <- NA
aod <- data.frame(Df = dfs, "Sum of Sq" = c(NA, chis[1] - chis[-1]),
RSS = chis, Cp = aics, row.names = scope, check.names = F)
head <- c("Single term additions", "\nModel:", deparse(as.vector(
formula(object))))
if(!missing(scale))
head <- c(head, paste("\nscale: ", format(scale), "\n"))
class(aod) <- c("anova", "data.frame")
attr(aod, "heading") <- head
if(length(keep))
list(anova = aod, keep = structure(value[, keep, drop = F],
class = "matrix"))
else aod
}
> alias.lm
function(object, complete = T, partial = T, pattern.arg = T, ...)
{
value <- list(Model = attr(object$terms, "formula"))
what <- object$qr
if(is.null(what))
qr <- object$R
else qr <- what$qr
d <- dim(qr)
rank <- object$rank
p <- d[2]
if(complete) {
if(is.null(p) || rank == p) beta12 <- NULL else {
p1 <- 1:rank
dn <- dimnames(qr)[[2]]
beta12 <- backsolve(qr[p1, p1], qr[p1, - p1, drop = F]
)
dimnames(beta12) <- list(dn[p1], dn[ - p1])
beta12 <- t(beta12)
if(pattern.arg)
beta12 <- pattern(beta12, abb = F)
}
# full rank, no aliasing
value$Complete <- beta12
}
if(partial) {
beta11 <- summary.lm(object)$correl
if(pattern.arg)
beta11 <- zapsmall(beta11)
beta11[row(beta11) >= col(beta11)] <- 0
if(all(beta11 == 0))
beta11 <- NULL
else if(pattern.arg) {
mx <- max(abs(beta11))
beta11 <- pattern(beta11)
attr(beta11, "Notes") <- list("Max. Abs. Corr." = round(
mx, 3))
}
value$Partial <- beta11
}
class(value) <- "listof"
value
}
> alias.mlm
function(object, ...)
{
# aliases are unrelated to response, so this method arranges
# to call alias.lm with a suitable object
object[c("coefficients", "residuals", "effects", "fitted.values")] <-
list(object$coef[, 1], object$resid[, 1], object$effects[,
1], object$fitted[, 1])
class(object) <- "lm"
alias.lm(object, ...)
}
> all.equal.lm
function(target, current, ...)
{
rt <- target$R
rc <- current$R
if(length(rt) && length(rc) && length(dim(rt)) == 2 && length(dim(
rc)) == 2) {
s <- sign(diag(rt)) * sign(diag(rc))
if(any(s < 0)) {
p1 <- 1:length(s)
current$effects <- c(s * current$effects[p1], sum(
current$effects[ - p1]^2)^0.5)
target$effects <- c(target$effects[p1], sum(target$
effects[ - p1]^2)^0.5)
rc[] <- rc[] * s
current$R <- rc
}
}
NextMethod("all.equal")
}
> anova.lm
function(object, ..., test = c("F", "none", "Chisq", "Cp"))
{
test <- match.arg(test)
margs <- function(...)
nargs()
if(margs(...))
anova.lmlist(list(object, ...), test = test)
else {
aod <- summary.aov(object)
heading <- c("Analysis of Variance Table\n", paste("Response: ",
as.character(formula(object))[2], "\n", sep = ""),
"Terms added sequentially (first to last)")
attr(aod, "heading") <- heading
if(test == "F")
aod
else {
aod$"F Value" <- NULL
aod$"Pr(F)" <- NULL
last <- unlist(aod[dim(aod)[1], c(1, 2), drop = T])
scale <- last[2]/last[1]
n <- length(object$residuals)
stat.anova(aod, test, last[2]/last[1], last[1], n)
}
}
}
> anova.lmlist
function(object, ..., test = c("none", "Chisq", "F", "Cp"))
{
diff.term <- function(term.labels, i)
{
t1 <- term.labels[[1]]
t2 <- term.labels[[2]]
m1 <- match(t1, t2, F)
m2 <- match(t2, t1, F)
if(all(m1)) {
if(all(m2))
return("=")
else return(paste(c("", t2[ - m1]), collapse = "+"))
}
else {
if(all(m2))
return(paste(c("", t1[ - m2]), collapse = "-"))
else return(paste(i - 1, i, sep = " vs. "))
}
}
test <- match.arg(test)
rt <- length(object)
if(rt == 1) {
object <- object[[1]]
UseMethod("anova")
}
forms <- sapply(object, function(x)
as.character(formula(x)))
subs <- as.logical(match(forms[2, ], forms[2, 1], F))
if(!all(subs))
warning(
"Some fit objects deleted because response differs from the first model"
)
if(sum(subs) == 1)
stop("The first model has a different response from the rest")
forms <- forms[, subs]
object <- object[subs]
dfres <- sapply(object, "[[", "df.resid")
dev <- sapply(object, deviance.lm)
tl <- lapply(object, labels)
rt <- length(dev)
effects <- character(rt)
for(i in 2:rt)
effects[i] <- diff.term(tl[c(i - 1, i)], i)
ddev <- - diff(dev)
ddf <- - diff(dfres)
heading <- c("Analysis of Variance Table", paste("\nResponse: ", forms[
2, 1], "\n", sep = ""))
aod <- data.frame(Terms = forms[3, ], "Resid. Df" = dfres, RSS = dev,
Test = effects, Df = c(NA, ddf), "Sum of Sq" = c(NA, ddev),
check.names = F)
aod <- as.anova(aod, heading)
if(test != "none") {
n <- length(object[[1]]$residuals)
o <- order(dfres)
stat.anova(aod, test, dev[o[1]]/dfres[o[1]], dfres[o[1]], n)
}
else aod
}
> coef.lm
function(object)
{
cf <- object$coefficients
r <- object$rank
asgn <- object$assign
if(!length(r)) {
}
else if(r == 0) {
nsing <- length(coef)
asgn <- list()
cf <- numeric()
}
else if(nsing <- length(cf) - r) {
cf <- cf[unlist(asgn)]
ii <- 1:r
for(i in names(asgn)) {
ai <- asgn[[i]]
if(ni <- length(ai)) {
asgn[[i]] <- ii[ni <- 1:ni]
ii <- ii[ - ni]
}
}
}
structure(cf, assign = asgn, singular = nsing, class = "coef")
}
> deviance.lm
function(object, ...)
if(is.null(w <- object$weights)) sum(object$residuals^2) else sum(w * object$
residuals^2)
> drop1.lm
function(object, scope, scale, keep)
{
b <- coef(object)
cnames <- labels(b)
singular <- attr(b, "singular")
p <- length(b)
x <- object$x
if(is.null(x))
x <- model.matrix(object$terms, model.frame(object))
iswt <- !is.null(wt <- object$weights)
if(iswt)
x <- x * sqrt(wt)
n <- dim(x)[[1]]
asgn <- attr(x, "assign")
tl <- attr(object$terms, "term.labels")
if(missing(scope))
scope <- drop.scope(object)
else {
if(!is.character(scope))
scope <- attr(terms(update.formula(object, scope)),
"term.labels")
if(!all(match(scope, tl, F)))
stop("scope is not a subset of term labels")
}
asgn <- asgn[scope]
k <- length(scope)
rdf <- object$df.resid
chisq <- deviance.lm(object)
if(missing(scale))
scale <- sqrt(chisq/rdf)
if(!missing(keep)) {
max.keep <- c("coefficients", "fitted", "residuals",
"x.residuals", "effects", "R")
if(is.logical(keep) && keep)
keep <- max.keep
else {
if(!all(match(keep, max.keep, F)))
stop(paste("Can only keep one or more of: \"",
paste(max.keep, collapse = "\", \""),
"\"", sep = ""))
}
fv <- predict(object)
y <- object$residuals + fv
if(iswt) {
if(any(wt == 0))
stop(
"\"keep\" not allowed when some of the weights are zero"
)
wt <- sqrt(wt)
}
}
else keep <- character(0)
xr <- match("x.residuals", keep, F)
value <- array(vector("list", 6 * k), c(k, 6), list(scope, c(
"coefficients", "fitted", "residuals", "x.residuals", "effects",
"R")))
if(length(ef <- object$effects) < n)
stop(
"function only currently defined for methods that compute effects"
)
dfs <- double(k)
chis <- double(k)
if(singular) {
if(iswt) {
if(!length(keep))
wt <- sqrt(wt)
y <- (object$residuals + predict(object)) * wt
}
rank <- object$rank
for(i in 1:k) {
ii <- asgn[[i]] #brute force method
z <- lm.fit.qr(x[, - ii, drop = F], y, singular = T,
qr = xr)
efi <- z$effects
dfs[i] <- rank - (ranki <- z$rank)
chis[i] <- sum(efi[ - seq(ranki)]^2)
if(length(keep)) {
fvi <- z$fitted
res <- z$residuals
if(iswt) {
fvi <- fvi/wt
res <- res/wt
}
value[i, -4] <- list(z$coef, fvi, res, efi,
z$R)
if(xr) {
xres <- qr.resid(z$qr, x[, ii, drop = F
])
if(iswt)
xres <- xres/wt
value[[i, 4]] <- xres
}
}
}
}
else {
R <- object$R
R <- array(R, dim(R), dimnames(R))
if(xr) {
xk <- array(0, dim(x), dimnames(x))
xk[1:p, ] <- R
}
else xk <- array(ef, c(n, 1), list(dimnames(x)[[1]], NULL))
for(i in 1:k) {
ii <- asgn[[i]]
pii <- length(ii)
dfs[i] <- pii
if(xr) {
xi <- xk[, c(1, ii)]
xi[, 1] <- ef
}
else xi <- xk
r <- R
pi <- 1:(p - pii)
pp <- - p
for(j in rev(ii)) {
z <- delcol(r, xi, j)
r <- z[[1]][pp, ]
xi <- z[[2]]
pp <- pp + 1
}
efi <- xi[, 1]
chis[i] <- sum(efi[ - pi]^2)
if(length(keep)) {
# compute it all, even though all may not be reqd
bi <- as.matrix(backsolve(r, xi[pi, ]))
dimnames(bi)[[1]] <- cnames[ - ii]
fvi <- x[, - ii, drop = F] %*% bi
if(iswt)
fvi <- fvi/wt
names(efi)[] <- ""
names(efi)[pi] <- cnames[ - ii]
value[i, -4] <- list(bi[, 1], fvi[, 1], y -
fvi[, 1], efi, r)
if(xr) {
xres <- x[, ii] - fvi[, -1]
if(iswt)
xres <- xres/wt
value[[i, 4]] <- xres
}
}
}
}
scope <- c("<none>", scope)
dfs <- c(0, dfs)
chis <- c(chisq, chis)
aics <- chis + 2 * (n - rdf - dfs) * scale^2
dfs[1] <- NA
aod <- data.frame(Df = dfs, "Sum of Sq" = c(NA, chis[-1] - chis[1]),
RSS = chis, Cp = aics, row.names = scope, check.names = F)
head <- c("Single term deletions", "\nModel:", deparse(as.vector(
formula(object))))
if(!missing(scale))
head <- c(head, paste("\nscale: ", format(scale), "\n"))
class(aod) <- c("anova", "data.frame")
attr(aod, "heading") <- head
if(length(keep))
list(anova = aod, keep = structure(value[, keep, drop = F],
class = "matrix"))
else aod
}
> effects.lm
function(object)
structure(object$effects, assign = object$assign, class = "coef")
> family.lm
function(object)
gaussian()
> formula.lm
function(object)
attr(object$terms, "formula")
> kappa.lm
function(z)
{
# this should check for the method used; e.g., svd
z <- z$R
NextMethod("kappa")
}
> labels.lm
function(object, ...)
{
TL <- object$terms
if(!is.null(TL)) {
TL <- attr(TL, "term.labels")
TA <- object$assign
if(!is.null(TA)) {
TA <- names(TA)
TL <- TL[match(TA, TL, 0)]
}
}
TL
}
> lm
function(formula, data, weights, subset, na.action, method = "qr", model = F,
x = F, y = F, ...)
{
call <- match.call()
m <- match.call(expand = F)
m$method <- m$model <- m$x <- m$y <- m$... <- NULL
m[[1]] <- as.name("model.frame")
m <- eval(m, sys.parent())
if(method == "model.frame")
return(m)
Terms <- attr(m, "terms")
weights <- model.extract(m, weights)
Y <- model.extract(m, response)
X <- model.matrix(Terms, m)
fit <- if(length(weights)) lm.wfit(X, Y, weights, method, ...) else
lm.fit(X, Y, method, ...)
fit$terms <- Terms
fit$call <- call
if(model)
fit$model <- m
if(x)
fit$x <- X
if(y)
fit$y <- Y
fit
}
> lm.fit
function(x, y, method = "qr", ...)
{
if(!is.numeric(x))
stop("model matrix must be numeric")
if(!is.numeric(y))
stop("response must be numeric")
if(!length(x))
method <- "null"
switch(method,
qr = lm.fit.qr(x, y, ...),
chol = lm.fit.chol(x, y, ...),
svd = lm.fit.svd(x, y, ...),
{
what <- paste("lm.fit.", method, sep = "")
if(exists(what, mode = "function"))
(get(what, mode = "function"))(x, y, ...)
else stop(paste("unimplemented method:", method))
}
)
}
> lm.fit.chol
function(x, y, singular.ok = F, qr = F)
{
storage.mode(x) <- "double"
ny <- length(y)
storage.mode(y) <- "double"
dx <- dim(x)
n <- dx[1]
dn <- dimnames(x)
xn <- dn[[2]]
if(n != ny)
stop("Number of observations in x and y not equal")
p <- dx[2]
xx <- crossprod(x)
xy <- crossprod(x, y)
if(singular.ok) {
z <- .Fortran("chol",
R = xx,
as.integer(p),
double(p),
pivot = as.integer(rep(0, p)),
as.integer(1),
rank = as.integer(0))[c(1, 4, 6)]
}
else {
z <- .Fortran("chol",
R = xx,
as.integer(p),
double(p),
as.integer(0),
as.integer(0),
rank = as.integer(0))[c(1, 6)]
if(z$rank < p)
stop("Choleski decomposition not of full rank")
}
R <- z$R
if((singular <- z$rank < p)) {
if(length(xn)) {
xn <- xn[z$pivot]
dimnames(z$qr)[[2]] <- xn
}
r <- R[1:p, 1:p]
xyp <- xy[1:p]
eff <- backsolvet(r, xyp)
b <- backsolve(r, eff)
fitted <- xx[, pivot[1:p]] %*% b
}
else {
eff <- backsolvet(R, xy)
b <- backsolve(R, eff)
fitted <- x %*% b
}
fitted <- fitted[, ]
z <- c(z, list(coefficients = b[, ], residuals = y - fitted,
fitted.values = fitted, effects = eff[, ]))
class(z) <- "lm"
z
}
> lm.fit.null
function(x, y, ...)
{
# fit a null model: used to provide the raw information, like the model matrix
dy <- dim(y)
q <- if(multiy <- length(dy) == 2) dy[2] else 1
if(!length(x)) {
structure(list(coefficients = numeric(), residuals = y,
fitted.values = 0 * y, effects = y, df.residuals = if(
multiy) dy[1] else length(y), assign = list(), rank = 0
), class = if(multiy) "mlm" else "lm")
}
else {
p <- (dx <- dim(x))[2]
structure(list(coefficients = if(multiy) array(NA, c(p, q))
else as.numeric(rep(NA, p)), residuals = y,
fitted.values = 0 * y, R = array(0, c(p, p)), effects
= if(multiy) array(0, dim(y)) else rep(0, p),
df.residuals = dx[1], assign = list(), rank = 0), class
= if(multiy) "mlm" else "lm")
}
}
> lm.fit.qr
function(x, y, singular.ok = F, tolerance = 1e-07, qr = F)
{
class(x) <- class(y) <- NULL
storage.mode(x) <- storage.mode(y) <- "double"
dx <- dim(x)
dn <- dimnames(x)
dy <- dim(y)
qty <- y
n <- dx[1]
n1 <- 1:n
p <- dx[2]
p1 <- 1:p
qtyn <- xn <- dn[[2]]
if(n > p && length(qtyn))
length(qtyn) <- n
if(multiy <- length(dy) == 2) {
cl <- c("mlm", "lm")
dny <- dimnames(y)
b <- array(double(1), c(dx[2], dy[2]), list(dn[[2]], dny[[2]]))
if(length(dn[[1]]) > length(dny[[1]]))
dimnames(y) <- list(dn[[1]], dny[[2]])
}
else {
dy <- c(length(y), 1)
cl <- "lm"
b <- x[1, ] #inherit the column names
if(length(dn[[1]]) > length(names(y)))
names(y) <- dn[[1]]
}
if(n != dy[1])
stop("Number of observations in x and y not equal")
asgn <- attr(x, "assign")
z <- .Fortran("dqrls",
qr = x,
as.integer(dx),
pivot = as.integer(p1),
qraux = double(p),
y,
as.integer(dy),
coef = b,
residuals = y,
qt = qty,
tol = as.double(tolerance),
double(2 * p),
rank = as.integer(p))
b <- z$coef
qt <- z$qt
if((singular <- (r <- z$rank) < p)) {
if(!singular.ok)
stop(paste("computed fit is singular, rank", z$rank))
pivot <- z$pivot
if(length(qtyn)) qtyn[p1] <- qtyn[pivot]
# coefs in original order, NA's in unestimable locations
# effects are in left in pivoted order -- names pivoted too
if(multiy) {
b[(r + 1):p, ] <- NA
b[pivot, ] <- b
if(n < p) {
tmp <- array(0, c(p, dim(qt)[2]))
tmp[n1, ] <- qt
qt <- tmp
}
dimnames(qt) <- list(qtyn, dimnames(qt)[[2]])
}
else {
b[(r + 1):p] <- NA
b[pivot] <- b
if(n < p)
qt[(n + 1):p] <- 0
names(qt) <- qtyn
}
pasgn <- asgn
newpos <- match(1:p, pivot)
if(length(xn))
names(newpos) <- xn
for(j in names(asgn)) {
aj <- asgn[[j]]
aj <- aj[ok <- (nj <- newpos[aj]) <= r]
if(length(aj)) {
asgn[[j]] <- aj
pasgn[[j]] <- nj[ok]
}
else asgn[[j]] <- pasgn[[j]] <- NULL
}
if(length(xn))
dimnames(z$qr)[[2]] <- xn <- xn[pivot]
}
else if(length(qtyn)) {
if(multiy)
dimnames(qt) <- list(qtyn, dny[[2]])
else names(qt) <- qtyn
}
fitted <- y - z$residuals
if(n < p) {
R <- (z$qr)[n1, , drop = F]
R[lower.tri(R)] <- 0
dimnames(R) <- list(xn[n1], xn)
}
else {
R <- (z$qr)[p1, , drop = F]
R[lower.tri(R)] <- 0
dimnames(R) <- list(xn, xn)
}
attr(R, "rank") <- r
class(R) <- "upper"
fit <- list(coefficients = b, residuals = z$residuals, fitted.values =
fitted, effects = qt, R = R, rank = z$rank, assign = asgn,
df.residual = max(n - r, 0))
if(singular) {
if(fit$df.residual > 0)
fit$assign.residual <- (r + 1):n
fit$R.assign <- pasgn
}
if(qr)
fit$qr <- z[c("qr", "qraux", "rank", "pivot", "tol")]
class(fit) <- cl
fit
}
> lm.fit.svd
function(x, y, u.return = 0)
{
dmx <- dim(x)
dnx <- dimnames(x)
dnp <- dnx[[2]]
n <- dmx[1]
p <- dmx[2]
nv <- min(dmx)
mm <- min(n + 1, p)
mn <- min(dmx)
nu <- if(u.return > 0) max(u.return, mn) else mn
code <- 1 + 10 * (if(nu == n) 1 else 2)
u <- double(n * nu)
dim(u) <- c(n, nu)
v <- double(p * p)
dim(v) <- c(p, p)
z <- .Fortran("dsvdc1",
as.double(x),
as.integer(dmx),
as.integer(code),
double(n),
double(p),
d = double(mm),
u = u,
v = v,
errorcode = integer(1))
if(z$errorcode)
stop(paste("Numerical error (code", z$errorcode,
") in algorithm"))
multiy <- length(dim(y)) == 2
u <- crossprod(z$u, y)
d <- z$d
if(all(dp <- d > 0))
d <- 1/d
else {
d[dp] <- 1/d[dp]
d[!dp] <- 0
}
v <- z$v %*% (d * u[1:p, ]) #coefficients
x <- x %*% v #fitted
r <- sum(dp)
R <- list(d = z$d, v = z$v, dinv = d, rank = r)
class(R) <- "svd.right"
y[] <- y - x
if(multiy) {
dny <- dimnames(y)[[2]]
dimnames(v) <- list(dnp, dny)
if(nu > p) {
dnu <- character(nu)
dnu[1:p] <- dnp
}
else dnu <- dnp
dimnames(u) <- list(dnu, dny)
dimnames(x) <- list(dnx[[1]], dny)
}
else {
v <- as.vector(v)
u <- as.vector(u)
if(length(dnp))
names(u) <- names(v) <- dnp
names(x) <- dnx[[1]]
}
val <- list(coefficients = v, residuals = y, fitted.values = x, effects
= u, R = R, rank = r)
if(u.return)
val$u <- z$u
class(val) <- c(if(length(dim(y))) "mlm" else NULL, "lm")
val
}
> lm.hat
function(lm, Q = F)
{
qr <- lm$qr
if(is.null(qr)) {
x <- lm$x
if(is.null(x))
x <- model.matrix(lm$terms, model.frame(lm))
basis <- left.solve(lm$R, x)
}
else basis <- qr.Q(qr)
p <- dim(basis)[2]
wt <- lm$weights
if(is.null(wt))
h <- (basis^2 %*% array(1, c(p, 1)))[, 1]
else {
out <- wt == 0
d <- dim(basis)
if(any(out)) {
w <- wt[!out]^0.5
hh <- array(1/w, d) * basis * t(array(w, d[2:1]))
h <- 0 * w
h[!out] <- hh
}
else h <- array(1/wt, d) * basis * t(array(wt, d[2:1]))
h <- (h^2 %*% array(1, c(p, 1)))[, 1]
}
if(Q)
attr(h, "Q") <- basis
h
}
> lm.influence
function(lm)
{
wt <- lm$weights
# should really test for < 1/BIG if machine pars available
e <- lm$residuals
n <- length(e)
if(!is.null(wt))
e <- e * sqrt(wt)
beta <- lm$coef
if(is.matrix(beta)) {
beta <- beta[, 1]
e <- e[, 1]
warning("multivariate response, only first y variable used")
}
na <- is.na(beta)
beta <- beta[!na]
p <- lm$rank
if(is.null(p))
p <- sum(!na)
R <- lm$R
if(p < max(dim(R)))
R <- R[1:p, 1:p]
qr <- lm$qr
if(is.null(qr)) {
x <- lm$x
if(is.null(x))
x <- model.matrix(lm$terms, model.frame(lm))
if(!is.null(wt))
x <- x * sqrt(wt)
if(any(na))
x <- x[, !na]
Q <- left.solve(R, x)
}
else {
if(!is.null(wt) && any(zero <- wt == 0)) {
Q <- matrix(0, n, p)
dimnames(Q) <- list(names(e), names(beta))
Q[!zero, ] <- qr.Q(qr)
}
else Q <- qr.Q(qr)
}
h <- as.vector((Q^2 %*% array(1, c(p, 1))))
h.res <- (1 - h)
z <- e/h.res
v1 <- e^2
z <- t(Q * z)
v.res <- sum(v1)
v1 <- (v.res - v1/h.res)/(n - p - 1) # BKW (2.8)
dbeta <- backsolve(R, z)
list(coefficients = t(dbeta + beta), sigma = sqrt(v1), hat = h)
}
> lm.kappa
function(z)
{
# library.dynam("statistics", "dtrco.o")
if(is.list(z)) z <- z$R
if(!is.matrix(z))
stop("z should be an lm object or its R component")
storage.mode(z) <- "double"
dz <- dim(z)
if(diff(dz))
stop("matrix should be square")
p <- as.integer(dz[1])
1/.Fortran("dtrco",
z,
p,
p,
k = double(1),
xx = double(p),
as.integer(1))$k
}
> lm.sensitivity
function(z, condition = lm.kappa(z$R))
{
nrm <- function(x)
.Fortran("nrmsub",
as.integer(length(x)),
as.double(x),
n = double(1))$n
e <- z$resid
y <- z$fitted + e
sn <- nrm(e)/nrm(y)
cs <- 1 - sn^2
n <- length(e)
p <- length(z$coef)
x <- c((1 + 2 * condition) * max(n - p, 1), (condition * (2 + sn *
condition))/cs)
names(x) <- c("residuals", "coefficients")
x
}
> lm.wfit
function(x, y, w, method, ...)
{
if(!is.numeric(x))
stop("model matrix must be numeric")
if(!is.numeric(y))
stop("response must be numeric")
if(any(w < 0))
stop("negative weights not allowed")
zero <- w == 0
multiy <- length(dim(y)) == 2
if(any(zero)) {
pos <- !zero
r <- f <- y
ww <- w
x0 <- x[zero, , drop = F]
y0 <- if(multiy) y[zero, , drop = F] else y[zero]
x <- x[pos, , drop = F]
y <- if(multiy) y[pos, , drop = F] else y[pos]
w <- w[pos]
}
w.factor <- w^0.5
x <- x * w.factor
y <- y * w.factor
fit <- lm.fit(x, y, method, ...)
fit$residuals <- fit$residuals/w.factor
fit$fitted.values <- fit$fitted.values/w.factor
if(any(zero) && method != "null") {
nas <- is.na(fit$coef)
if(any(nas))
f0 <- x0[, !nas] %*% fit$coef[!nas]
else f0 <- x0 %*% fit$coef
if(multiy) {
r[pos, ] <- fit$resid
f[pos, ] <- fit$fitted
r[zero, ] <- y0 - f0
f[zero, ] <- f0
}
else {
r[pos] <- fit$resid
f[pos] <- fit$fitted
r[zero] <- y0 - f0
f[zero] <- f0
}
fit$residuals <- r
fit$fitted.values <- f
w <- ww
}
fit$weights <- w
fit
}
> model.frame.lm
function(formula, data = NULL, na.action = NULL, ...)
{
m <- formula$model
if(!is.null(m))
return(m)
oc <- formula$call
oc$method <- "model.frame"
oc[[1]] <- as.name("lm")
if(length(data)) {
oc$data <- substitute(data)
eval(oc, sys.parent())
}
else eval(oc, list())
}
> plot.lm
function(x, y, ...)
{
op <- par(ask = T)
on.exit(par(op))
form <- formula(x)
f <- predict(x)
r <- residuals(x)
if(missing(y)) {
y <- f + r
yname <- deparse(form[[2]])
}
else yname <- deparse(substitute(y))
fname <- paste("Fitted:", deparse(form[[3]]), collapse = " ")
plot(f, y, xlab = fname, ylab = yname)
abline(0, 1, lty = 2)
plot(f, abs(r), xlab = fname, ylab = deparse(substitute(abs(resid(
x)))))
}
> predict.lm
function(object, newdata, type = c("response", "terms"), se.fit = F, terms =
labels(object))
{
type <- match.arg(type)
if(missing(newdata) && type != "terms" && !se.fit)
return(object$fitted)
Terms <- object$terms
if(!inherits(Terms, "terms"))
stop("invalid terms component of object")
offset <- attr(Terms, "offset")
xbar <- NULL
if(missing(newdata)) {
x <- object$x
if(is.null(x)) x <- model.matrix(Terms, model.frame(object))
#center x if terms are to be computed
if(type == "terms") {
xbar <- apply(x, 2, mean)
x <- sweep(x, 2, xbar)
}
}
else if(!(is.atomic(newdata) | is.list(newdata))) {
#try and coerce newdata to look like the x matrix
if(!is.null(offset)) {
warning("Offset not included")
offset <- NULL
}
TT <- length(object$coef)
if(is.matrix(newdata) && ncol(newdata) == TT)
x <- newdata
else if(length(newdata) == TT)
x <- matrix(newdata, 1, TT)
else stop(
"Argument \"newdata\" is not a data frame, and cannot be coerced to an appropriate model matrix"
)
}
else {
#newdata is a list, data frame or frame number
x <- model.matrix(delete.response(Terms), newdata)
if(!is.null(offset))
offset <- eval(attr(Terms, "variables")[offset],
newdata)
}
if(!missing(newdata) && type == "terms") {
#need to center x
xold <- object$x
if(is.null(xold))
xold <- model.matrix(Terms, model.frame(object))
xbar <- apply(xold, 2, mean)
x <- sweep(x, 2, xbar)
}
coefs <- coef(object)
asgn <- attr(coefs, "assign")
if(type == "terms") {
terms <- match.arg(terms, labels(object))
asgn <- asgn[terms]
}
nac <- is.na(object$coef)
if(any(nac)) {
xbar <- xbar[!nac]
x <- x[, !nac]
}
attr(x, "constant") <- xbar
if(se.fit) {
fit.summary <- summary.lm(object)
pred <- Build.terms(x, coefs, fit.summary$cov * fit.summary$
sigma, asgn, collapse = type != "terms")
pred$residual.scale <- fit.summary$sigma
pred$df <- object$df.resid
}
else pred <- Build.terms(x, coefs, NULL, assign = asgn, collapse = type !=
"terms")
if(!is.null(offset) && type != "terms") {
if(missing(newdata))
warning("Offset not included")
else {
if(se.fit)
pred$fit <- pred$fit + offset
else pred <- pred + offset
}
}
pred
}
> print.lm
function(x, ...)
{
if(!is.null(cl <- x$call)) {
cat("Call:\n")
dput(cl)
}
coef <- coefficients(x)
if(ns <- attr(coef, "singular"))
cat("\nCoefficients: (", ns,
" not defined because of singularities)\n", sep = "")
else cat("\nCoefficients:\n")
print(coef, ...)
rank <- x$rank
if(is.null(rank))
rank <- sum(!nas)
nobs <- length(residuals(x))
rdf <- x$df.resid
if(is.null(rdf))
rdf <- nobs - rank
cat("\nDegrees of freedom:", nobs, "total;", rdf, "residual\n")
if(rdf > 0) {
if(is.null(w <- x$weights))
cat("Residual standard error:", format((sum(x$residuals^
2)/rdf)^0.5), "\n")
else cat("Residual standard error (on weighted scale):", format(
(sum(w * x$residuals^2)/rdf)^0.5), "\n")
}
invisible(x)
}
> proj.lm
function(object, onedf = F)
{
prj <- object$proj
if(!is.null(prj)) {
if(is.null(attr(prj, "onedf"))) {
}
else if(attr(prj, "onedf") == onedf)
return(prj)
else if(onedf)
stop(
"Cannot recover single degree of freedom projections"
)
else {
ncol.prj <- ncol(prj)
if(ncol.prj == 1)
return(prj)
if(dimnames(prj)[[2]][ncol.prj] == "Residuals") {
tmp <- prj[, - ncol.prj, drop = F]
attr.assign(tmp) <- attr.xdim(prj)
attr(tmp, "df") <- attr(prj, "df")[ - ncol.prj]
prj <- tmp
}
}
}
else {
if(is.null(object$qr))
object <- update(object, qr = T)
if(object$rank > 0)
prj <- proj.default(object, onedf = T)[, seq(object$
rank), drop = F]
else prj <- numeric(0)
# needed for strata with no treatment effects
}
if(onedf) {
df <- rep(1, object$rank)
result <- prj
}
else {
asgn <- object$assign
ldf <- length(asgn)
df <- vector("numeric", ldf)
result <- matrix(0, length(object$residuals), ldf)
dimnames(result) <- list(dimnames(object$fitted.values)[[1]],
names(asgn))
is.qr.object <- is.qr(object$qr)
for(i in seq(along = asgn)) {
if(is.qr.object)
select <- match(asgn[[i]], object$qr$pivot)
else select <- asgn[[i]]
df[i] <- length(select)
result[, i] <- prj[, select, drop = F] %*% rep(1, df[
i])
}
}
if(object$df.residual > 0) {
dn <- dimnames(result)
d <- dim(result)
result <- c(result, object$residuals)
dim(result) <- d + c(0, 1)
dn[[1]] <- names(object$residuals)
names(result) <- NULL
dn[[2]] <- c(dn[[2]], "Residuals")
dimnames(result) <- dn
df <- c(df, object$df.residual)
}
names(df) <- dimnames(result)[[2]]
attr(result, "df") <- df
attr(result, "formula") <- object$call$formula
attr(result, "onedf") <- onedf
result
}
> | 32,824 | Common Lisp | .l | 1,291 | 21.375678 | 101 | 0.552649 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | abc66798e2d1d723fe4d44d9502a422fb8129792e0570de15a133be199c865d4 | 33,753 | [
-1
] |
33,754 | sglm.out | rwoldford_Quail/source/statistics/models/models_testing,_etc/sglm.out | Working data will be in /usr/people/dganglin/.Data
> anova.glm
function(object, ..., test = c("none", "Chisq", "F", "Cp"))
{
test <- match.arg(test)
margs <- function(...)
nargs()
if(margs(...))
return(anova.glmlist(list(object, ...), test = test))
Terms <- object$terms
term.labels <- attr(Terms, "term.labels")
nt <- length(term.labels)
x <- object$x
m <- model.frame(object)
if(is.null(x))
x <- model.matrix(Terms, m)
ass <- attr(x, "assign")
control <- glm.control()
family <- as.family(object)
a <- attributes(m)
y <- model.extract(m, "response")
w <- model.extract(m, "weights")
if(!length(w))
w <- rep(1, nrow(m))
offset <- attr(Terms, "offset")
if(is.null(offset))
offset <- 0
else offset <- m[[offset]]
dev.res <- double(nt)
df.res <- dev.res
nulld <- object$null.deviance
if(is.null(nulld))
nulld <- sum(w * (y - weighted.mean(y, w))^2)
dev.res[1] <- nulld
df.res[1] <- nrow(x) - attr(Terms, "intercept")
if(nt > 1)
for(iterm in seq(nt, 2)) {
x <- x[, - (ass[[(term.labels[iterm])]])]
fit <- glm.fit(x, y, w, offset = offset, family =
family)
dev.res[iterm] <- deviance(fit)
df.res[iterm] <- fit$df.resid
}
dev.res <- c(dev.res, deviance(object))
df.res <- c(df.res, object$df.resid)
dev <- c(NA, - diff(dev.res))
df <- c(NA, - diff(df.res))
heading <- c("Analysis of Deviance Table\n", paste(family$family[1],
"model\n"), paste("Response: ", as.character(formula(object))[
2], "\n", sep = ""), "Terms added sequentially (first to last)"
)
aod <- data.frame(Df = df, Deviance = dev, "Resid. Df" = df.res,
"Resid. Dev" = dev.res, row.names = c("NULL", term.labels),
check.names = F)
attr(aod, "heading") <- heading
attr(aod, "class") <- c("anova", "data.frame")
if(test == "none")
aod
else stat.anova(aod, test, deviance.lm(object)/object$df.resid, object$
df.resid, nrow(x))
}
> anova.glmlist
function(object, ..., test = c("none", "Chisq", "F", "Cp"))
{
diff.term <- function(term.labels, i)
{
t1 <- term.labels[[1]]
t2 <- term.labels[[2]]
m1 <- match(t1, t2, F)
m2 <- match(t2, t1, F)
if(all(m1)) {
if(all(m2))
return("=")
else return(paste(c("", t2[ - m1]), collapse = "+"))
}
else {
if(all(m2))
return(paste(c("", t1[ - m2]), collapse = "-"))
else return(paste(i - 1, i, sep = " vs. "))
}
}
test <- match.arg(test)
rt <- length(object)
if(rt == 1) {
object <- object[[1]]
UseMethod("anova")
}
forms <- sapply(object, function(x)
as.character(formula(x)))
subs <- as.logical(match(forms[2, ], forms[2, 1], F))
if(!all(subs))
warning(
"Some fit objects deleted because response differs from the first model"
)
if(sum(subs) == 1)
stop("The first model has a different response from the rest")
forms <- forms[, subs]
object <- object[subs]
dfres <- sapply(object, "[[", "df.resid")
dev <- sapply(object, "[[", "deviance")
tl <- lapply(object, labels)
rt <- length(dev)
effects <- character(rt)
for(i in 2:rt)
effects[i] <- diff.term(tl[c(i - 1, i)], i)
ddev <- - diff(dev)
ddf <- - diff(dfres)
heading <- c("Analysis of Deviance Table", paste("\nResponse: ", forms[
2, 1], "\n", sep = ""))
aod <- data.frame(Terms = forms[3, ], "Resid. Df" = dfres,
"Resid. Dev" = dev, Test = effects, Df = c(NA, ddf), Deviance
= c(NA, ddev), check.names = F)
aod <- as.anova(aod, heading)
if(test != "none") {
n <- length(object[[1]]$residuals)
o <- order(dfres)
stat.anova(aod, test, dev[o[1]]/dfres[o[1]], dfres[o[1]], n)
}
else aod
}
> deviance.glm
function(object, ...)
object$deviance
> family.glm
function(object)
family(object$call$family)
> glm
function(formula = formula(data), family = gaussian, data = sys.parent(),
weights, subset, na.action, start = eta, control = glm.control(...),
method = "glm.fit", model = F, x = F, y = T, ...)
{
call <- match.call()
m <- match.call(expand = F)
m$family <- m$method <- m$model <- m$x <- m$y <- m$control <- m$... <-
NULL
m[[1]] <- as.name("model.frame")
m <- eval(m, sys.parent())
Terms <- attr(m, "terms")
if(method == "model.frame")
return(m)
a <- attributes(m)
Y <- model.extract(m, response)
X <- model.matrix(Terms, m)
w <- model.extract(m, weights)
if(!length(w))
w <- rep(1, nrow(m))
start <- model.extract(m, start)
offset <- attr(Terms, "offset")
if(is.null(offset))
offset <- 0
else offset <- m[[offset]]
family <- as.family(family)
if(missing(method))
method <- attr(family, "method")
if(!is.null(method)) {
if(!exists(method, mode = "function"))
stop(paste("unimplemented method:", method))
}
else method <- "glm.fit"
glm.fitter <- get(method)
fit <- glm.fitter(x = X, y = Y, w = w, start = start, offset = offset,
family = family, maxit = control$maxit, epsilon = control$
epsilon, trace = control$trace, null.dev = T, ...)
attr(fit, "class") <- c("glm", "lm")
fit$terms <- Terms
fit$formula <- as.vector(attr(Terms, "formula"))
fit$call <- call
if(model)
fit$model <- m
if(x)
fit$x <- X
if(!y)
fit$y <- NULL
fit
}
> glm.control
function(epsilon = 0.0001, maxit = 10, trace = F, ...)
{
if(epsilon <= 0) {
warning(
"the value of epsilon supplied is zero or negative; the default value of 0.0001 was used instead"
)
epsilon <- 0.0001
}
if(maxit < 1) {
warning(
"the value of maxit supplied is zero or negative; the default value of 10 was used instead"
)
maxit <- 10
}
list(epsilon = epsilon, maxit = maxit, trace = as.logical(trace)[1])
}
> glm.fit
function(x, y, w = rep(1, length(x[, 1])), start = NULL, offset = 0, family =
gaussian(), maxit = 10, epsilon = 0.001, trace = F, null.dev = NULL,
qr = F, ...)
{
#for backchat with fortran
new.s.call <- expression({
if(c.list$one.more) {
eta <- c.list$fit + offset
mu <- family$inverse(eta)
old.dev <- new.dev
new.dev <- family$deviance(mu, y, w)
if(trace)
cat("GLM linear loop ", iter,
": deviance = ", format(round(new.dev,
4)), " \n", sep = "")
if(is.na(new.dev)) {
one.more <- FALSE
warning(
"iterations terminated prematurely because of singularities"
)
}
else one.more <- abs((old.dev - new.dev)/(old.dev +
epsilon)) > epsilon && iter < maxit
if(one.more) {
iter <- iter + 1
deriv.mu <- family$deriv(mu)
z <- eta + (y - mu) * deriv.mu - offset
c.list$z <- z
wz <- eval(family$weight)
c.list$wz <- wz
}
c.list$one.more <- one.more
}
c.list
}
)
family <- as.family(family)
eval(family$initialize)
if(length(start)) {
eta <- start
mu <- family$inverse(eta)
}
else eta <- family$link(mu)
new.dev <- family$deviance(mu, y, w)
if(!is.null(null.dev)) {
null.dev <- glm.null(x, y, w, offset, family)
if(length(null.dev) > 1)
return(null.dev)
}
dn <- dimnames(x)
xn <- dn[[2]]
yn <- dn[[1]]
iter <- 1
old.dev <- 10 * new.dev + 10
deriv.mu <- family$deriv(mu)
storage.mode(y) <- "double"
z <- eta + (y - mu) * deriv.mu - offset
wz <- eval(family$weight)
names(z) <- names(wz) <- yn
c.list <- list(wz = wz, z = z, fit = eta, one.more = T)
### for Fortran backchat##############################
nframe <- sys.nframe()
.C("init_call",
as.integer(nframe),
new.s.call)
######################################################
dx <- as.integer(dim(x))
n <- dx[[1]]
p <- dx[[2]]
tfit <- .Fortran("glmfit",
x,
n,
p,
backchat = T,
z,
weights = wz,
coefficients = double(p),
linear.predictors = z,
effects = z,
qr = x,
qraux = double(p),
rank = as.integer(0),
pivot = as.integer(seq(p)),
double(3 * n))
if(maxit > 1 && iter == maxit)
cat("Linear convergence not obtained in ", maxit,
" iterations.\n")
coefs <- tfit$coeff
asgn <- attr(x, "assign")
names(coefs) <- xn
rank <- tfit$rank
cnames <- xn
if(rank < p) {
pivot <- tfit$pivot
coefs[pivot[ - seq(rank)]] <- NA
pasgn <- asgn
newpos <- match(1:p, pivot)
names(newpos) <- xn
for(j in names(asgn)) {
aj <- asgn[[j]]
aj <- aj[ok <- (nj <- newpos[aj]) <= rank]
if(length(aj)) {
asgn[[j]] <- aj
pasgn[[j]] <- nj[ok]
}
else asgn[[j]] <- pasgn[[j]] <- NULL
}
cnames <- xn[pivot]
}
R <- tfit$qr[1:p, 1:p]
R[lower.tri(R)] <- 0
attributes(R) <- list(dim = c(p, p), dimnames = list(cnames, cnames),
rank = rank, class = "upper")
effects <- tfit$effects
neff <- rep("", n)
neff[seq(p)] <- cnames
names(effects) <- neff
residuals <- z - tfit$linear
names(mu) <- names(residuals)
df.residual <- n - rank - sum(tfit$weights == 0)
fit <- list(coefficients = coefs, residuals = residuals, fitted.values
= mu, effects = effects, R = R, rank = rank, assign = asgn,
df.residual = df.residual)
if(rank < p) {
if(df.residual > 0)
fit$assign.residual <- (rank + 1):n
fit$R.assign <- pasgn
}
if(qr)
fit$qr <- tfit[c("qr", "rank", "pivot", "qraux")]
fit$weights <- tfit$weights
if(length(attributes(w)) | any(w != w[1]))
fit$prior.weights <- w
this.call <- match.call()
c(fit, list(family = family$family, linear.predictors = tfit$linear,
deviance = new.dev, null.deviance = null.dev, call = this.call,
iter = iter, y = y))
}
> glm.links
identity logit
names Identity: mu Logit: log(mu/(1 - mu))
link function, 2 function, 2
inverse function, 2 function, 2
deriv function, 2 function, 2
initialize
cloglog probit
names Complimentary Log: log( - log(1 - mu)) Probit: qnorm(mu)
link function, 2 function, 2
inverse function, 2 function, 2
deriv function, 2 function, 2
initialize
log inverse 1/mu^2
names Log: log(mu) Inverse: 1/mu Inverse Square: 1/mu^2
link function, 2 function, 2 function, 2
inverse function, 2 function, 2 function, 2
deriv function, 2 function, 2 function, 2
initialize
sqrt
names Square Root: sqrt(mu)
link function, 2
inverse function, 2
deriv function, 2
initialize
attr(, "names"):
[1] "" "link" "inverse" "deriv" "initialize"
[6] "" "link" "inverse" "deriv" "initialize"
[11] "" "link" "inverse" "deriv" "initialize"
[16] "" "link" "inverse" "deriv" "initialize"
[21] "" "link" "inverse" "deriv" "initialize"
[26] "" "link" "inverse" "deriv" "initialize"
[31] "" "link" "inverse" "deriv" "initialize"
[36] "" "link" "inverse" "deriv" "initialize"
> glm.null
function(x, y, w, offset, family)
{
n <- length(y)
intl <- attr(x, "term.labels")
int <- if(is.null(intl)) F else as.logical(match(intl[1], c("(Int.)",
"(Intercept)"), F))
mu <- if(int) weighted.mean(y, w) else family$inverse(0)
mu <- rep(mu, n)
deviance <- family$deviance(mu, y, w)
order <- attr(x, "order")
if(!any(order) && !(any(offset) & int)) {
residuals <- family$deriv(mu) * (y - mu)
if(int) {
coefficients <- family$link(mu[1])
names(coefficients) <- intl[1]
R <- matrix( - sqrt(n), dimnames = list(intl[1], intl[
1]))
}
else {
coefficients <- NULL
R <- matrix(0)
}
class(R) <- "upper"
rank <- as.numeric(int)
attribute(R, "rank") <- rank
wz <- eval(family$weight)
null.deviance <- deviance
if(any(offset)) {
mu <- family$inverse(offset)
deviance <- family$deviance(mu, y, w)
}
list(coefficients = coefficients, residuals = residuals,
fitted.values = mu, rank = rank, df.residual = n - int,
weights = wz, y = y, iter = 0, linear.predictors =
family$link(mu), deviance = deviance, null.deviance =
null.deviance, R = R)
}
else deviance
}
> glm.variances
constant mu(1-mu) mu mu^2 mu^3
name Constant: 1 Binomial: mu(1-mu) Identity: mu Square: mu^2 Cube: mu^3
variance function, 2 function, 2 function, 2 function, 2 function, 2
deviance function, 5 function, 5 function, 5 function, 5 function, 5
attr(, "names"):
[1] "" "variance" "constant" "" "variance" "mu(1-mu)"
[7] "" "variance" "mu" "" "variance" "mu^2"
[13] "" "variance" "mu^3"
> glm.weight
function(link, variance)
{
default <- expression(w/((sqrt(family$variance(mu)) * family$deriv(
mu))^2))
dnames <- dimnames(glm.weights)
if(!match(link, dnames[[1]], F))
return(default)
if(!match(variance, dnames[[2]], F))
return(default)
ww <- glm.weights[link, variance]
if(as.character(ww) == "NULL")
default
else ww
}
> glm.weights
Constant: 1 Binomial: mu(1-mu)
Identity: mu
Logit: log(mu/(1 - mu)) call, 3
Complimentary Log: log( - log(1 - mu))
Probit: qnorm(mu)
Log: log(mu) call, 3
Inverse: 1/mu
Inverse Square: 1/mu^2
Square Root: sqrt(mu)
Identity: mu Square: mu^2 Cube: mu^3
Identity: mu
Logit: log(mu/(1 - mu))
Complimentary Log: log( - log(1 - mu))
Probit: qnorm(mu)
Log: log(mu) call, 3
Inverse: 1/mu call, 3
Inverse Square: 1/mu^2
Square Root: sqrt(mu)
> glmlist
function(...)
{
gl <- list(...)
class(gl) <- "glmlist"
gl
}
> plot.glm
function(x, y, ...)
{
form <- formula(x)
p <- predict(x)
r <- residuals(x)
f <- fitted(x)
if(missing(y)) {
y <- x$y
yname <- deparse(form[[2]])
}
else yname <- deparse(substitute(y))
xylims <- range(f, y)
plot(f, y, xlab = deparse(substitute(fitted(x))), ..., ylab = yname,
ylim = xylims, xlim = xylims)
abline(0, 1, lty = 2)
plot(p, abs(r), ..., xlab = deparse(substitute(predict(x))), ylab =
deparse(substitute(abs(resid(x)))))
}
> predict.glm
function(object, newdata, type = c("link", "response", "terms"), se.fit = F,
terms = labels(object), ...)
{
type <- match.arg(type)
if(!se.fit) {
#No standard errors
if(missing(newdata)) switch(type,
link = object$linear.predictors,
response = object$fitted,
terms = NextMethod("predict")) else switch(
type,
response = family(object)$inverse(NextMethod(
"predict")),
NextMethod("predict"))
}
else {
if(type == "response") {
pred <- NextMethod("predict")
famob <- family(object)
pred$fit <- famob$inverse(pred$fit)
pred$se.fit <- pred$se.fit/abs(famob$deriv(pred$fit))
pred
}
else NextMethod("predict")
}
}
> print.glm
function(x, ...)
{
if(!is.null(cl <- x$call)) {
cat("Call:\n")
dput(cl)
}
coef <- x$coef
if(any(nas <- is.na(coef))) {
if(is.null(names(coef))) names(coef) <- paste("b", 1:length(
coef), sep = "") # coef <- coef[!nas]
cat("\nCoefficients: (", sum(nas),
" not defined because of singularities)\n", sep = "")
}
else cat("\nCoefficients:\n")
print(coef, ...)
rank <- x$rank
if(is.null(rank))
rank <- sum(!nas)
nobs <- length(x$residuals)
rdf <- x$df.resid
if(is.null(rdf))
rdf <- nobs - rank
cat("\nDegrees of Freedom:", nobs, "Total;", rdf, "Residual\n")
cat("Residual Deviance:", format(x$deviance), "\n")
invisible(x)
}
> step.glm
function(object, scope, scale, direction = c("both", "backward", "forward"),
trace = T, keep = NULL, steps = 1000, ...)
{
if(missing(direction))
direction <- "both"
else direction <- match.arg(direction)
sub.assign <- function(terms, assign)
{
a <- attributes(terms)
tl <- a$term.labels
if(a$intercept)
tl <- c(names(assign)[1], tl)
asgn <- assign[tl]
poi <- 0
for(i in tl) {
la <- length(asgn[[i]])
asgn[[i]] <- seq(poi + 1, poi + la)
poi <- poi + la
}
asgn
}
re.arrange <- function(keep)
{
namr <- names(k1 <- keep[[1]])
namc <- names(keep)
nc <- length(keep)
nr <- length(k1)
array(unlist(keep, recursive = F), c(nr, nc), list(namr, namc))
}
make.step <- function(models, fit, scale, object)
{
change <- sapply(models, "[[", "change")
rd <- sapply(models, "[[", "deviance")
dd <- c(NA, diff(rd))
rdf <- sapply(models, "[[", "df.resid")
ddf <- c(NA, diff(rdf))
AIC <- sapply(models, "[[", "AIC")
heading <- c("Stepwise Model Path \nAnalysis of Deviance Table",
"\nInitial Model:", deparse(as.vector(formula(object))),
"\nFinal Model:", deparse(as.vector(formula(fit))),
"\n")
aod <- data.frame(Step = change, Df = ddf, Deviance = dd,
"Resid. Df" = rdf, "Resid. Dev" = rd, AIC = AIC,
check.names = F)
attr(aod, "heading") <- heading
attr(aod, "class") <- c("anova", "data.frame")
fit$anova <- aod
fit
}
backward <- direction == "both" | direction == "backward"
forward <- direction == "both" | direction == "forward"
if(missing(scope)) {
fdrop <- numeric(0)
fadd <- NULL
}
else {
if(is.list(scope)) {
fdrop <- if(!is.null(fdrop <- scope$lower)) attr(terms(
update.formula(object, fdrop)),
"factor") else numeric(0)
fadd <- if(!is.null(fadd <- scope$upper)) attr(terms(
update.formula(object, fadd)), "factor"
)
}
else {
fadd <- if(!is.null(fadd <- scope)) attr(terms(
update.formula(object, scope)),
"factor")
fdrop <- numeric(0)
}
}
if(is.null(fadd)) {
backward <- T
forward <- F
}
m <- model.frame(object)
objectcall <- object$call #build the big model matrix
if(forward) {
add.rhs <- paste(dimnames(fadd)[[2]], collapse = "+")
add.rhs <- eval(parse(text = paste("~ . +", add.rhs)))
new.form <- update.formula(object, add.rhs, evaluate = F)
fc <- objectcall
Terms <- terms(new.form)
fc$formula <- Terms
fobject <- list(call = fc)
class(fobject) <- class(object)
M <- model.frame(fobject)
x <- model.matrix(Terms, M)
}
else {
Terms <- object$terms
x <- model.matrix(Terms, m)
}
Asgn <- attr(x, "assign") #from glm.fit
a <- attributes(m)
y <- model.extract(m, "response")
w <- model.extract(m, "weights")
if(is.null(w))
w <- rep(1, nrow(m))
offset <- attr(Terms, "offset")
if(is.null(offset))
offset <- 0
else offset <- m[, offset]
family <- family(object)
control <- object$call$control
control <- if(is.null(control)) glm.control() else eval(control)
models <- vector("list", steps)
if(!is.null(keep)) {
keep.list <- vector("list", steps)
nv <- 1
}
n <- length(object$fitted)
if(missing(scale)) {
famname <- family$family["name"]
scale <- switch(famname,
Poisson = 1,
Binomial = 1,
deviance(object)/object$df.resid)
}
fit <- object
bAIC <- deviance(fit) + 2 * (n - fit$df.resid) * scale
nm <- 1
Terms <- fit$terms
if(trace)
cat("Start: AIC=", format(round(bAIC, 4)), "\n", deparse(
as.vector(formula(fit))), "\n\n")
models[[nm]] <- list(deviance = deviance(fit), df.resid = fit$df.resid,
change = "", AIC = bAIC)
if(!is.null(keep))
keep.list[[nm]] <- keep(fit, bAIC)
AIC <- bAIC + 1
while(bAIC < AIC & steps > 0) {
steps <- steps - 1
AIC <- bAIC
bfit <- fit
ffac <- attr(Terms, "factor")
scope <- factor.scope(ffac, list(add = fadd, drop = fdrop))
aod <- NULL
change <- NULL
if(backward && (ndrop <- length(scope$drop))) {
aod <- drop1.lm(fit, scope$drop, scale)
if(trace)
print(aod)
change <- rep("-", ndrop + 1)
}
if(forward && (nadd <- length(scope$add))) {
aodf <- add1.lm(fit, scope$add, scale, x = x)
if(trace)
print(aodf)
change <- c(change, rep("+", nadd + 1))
if(is.null(aod))
aod <- aodf
else {
ncaod <- dim(aod)[1]
aod[seq(ncaod + 1, ncaod + nadd + 1), ] <-
aodf
}
}
if(is.null(aod))
break
o <- order(aod[, "Cp"])[1]
if(o[1] == 1)
break
change <- paste(change[o], dimnames(aod)[[1]][o])
Terms <- terms(update(formula(fit), eval(parse(text = paste(
"~ .", change)))))
attr(Terms, "formula") <- rebld.formula(Terms)
asgn <- sub.assign(Terms, Asgn)
tx <- x[, unlist(Asgn[names(asgn)]), drop = F]
attr(tx, "assign") <- asgn
newfit <- glm.fit(tx, y, w, NULL, offset, family, control$
maxit, control$epsilon)
bAIC <- deviance(newfit) + 2 * (n - newfit$df.resid) * scale
if(trace)
cat("\nStep: AIC=", format(round(bAIC, 4)), "\n",
deparse(as.vector(formula(Terms))), "\n\n")
if(bAIC >= AIC)
break
nm <- nm + 1
models[[nm]] <- list(deviance = deviance(newfit), df.resid =
newfit$df.resid, change = change, AIC = bAIC)
fit <- c(newfit, list(x = tx, terms = Terms, formula = attr(
Terms, "formula")))
oc <- objectcall
oc$formula <- as.vector(fit$formula)
fit$call <- oc
fit$family <- object$family
class(fit) <- class(object)
if(!is.null(keep))
keep.list[[nm]] <- keep(fit, bAIC)
}
if(!is.null(keep))
fit$keep <- re.arrange(keep.list[seq(nm)])
make.step(models = models[seq(nm)], fit, scale, object)
}
> | 22,576 | Common Lisp | .l | 725 | 25.466207 | 101 | 0.543602 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 16d3ffdf1777fce9ff97d1348048c16ebec117041b305cba7b06f46c73b833c1 | 33,754 | [
-1
] |
33,755 | calib.s | rwoldford_Quail/source/statistics/models/models_testing,_etc/calib.s | cmat <- matrix(c(
4.0,3.7,3.7,
8.0,7.8,7.8,
12.5,12.1,12.1,
16.0,15.6,15.6,
20.0,19.8,19.8,
25.0,24.5,24.5,
31.0,31.1,31.1,
36.0,35.5,35.5,
40.0,39.4,39.4,
40.0,39.5,39.5,
), 10,3, byrow=T)
| 202 | Common Lisp | .l | 12 | 14.833333 | 18 | 0.547368 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | a6ca0942fdd848eb86558c2cdf3e96c7b784d8692ed4408e5e1a8c392c4f7d45 | 33,755 | [
-1
] |
33,756 | new-matrix-multiply.lsp | rwoldford_Quail/source/statistics/models/models_testing,_etc/new-matrix-multiply.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; matrix-multiply.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1990 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; Greg Anglin 1992.
;;;
;;;
;;;--------------------------------------------------------------------------------
;;;
(in-package qk)
(defmacro dot-times-instantiate-target (target rows cols u v)
(let ((dims (gensym)))
`(let ((,dims (delete 1 (list rows cols))))
;; avoid instantiating a complex instance when it would be
;; thrown away anyway
(if (or ,dims ;; usual case
(not (eql 1 ,rows))
(not (eql 1 ,cols))
,target) ;; if we're this far, target is an atom for sure.
(make-dimensioned-result ,dims ,u ,v)
(make-list 1)))))
(labels
((erefer (source-rank source-rows)
(case source-rank
(0 #'0d-eref)
(1 (if (eql source-rows 1)
#'1d-row-eref
#'1d-column-eref))
(2 #'eref)))
(setf-erefer (target-rank target-rows)
(case target-rank
(0 #'0d-eset)
(1 (if (eql target-rows 1)
#'1d-row-eset
#'1d-column-eset))
(2 *setf-eref*))))
(defun dot-times-instantiate-1 (u v &optional target)
(declare (optimize speed))
(let* ((udim (or (dimensions-of u) '(1))) ;; fake out zero-dim case
(vdim (or (dimensions-of v) '(1)))
(u2d (eql (length udim) 2))
(v2d (eql (length vdim) 2))
p rows cols)
(if (atom target)
(progn
(multiple-value-setq
(rows cols p)
;; use m=2d matrix, c=1d column, r=1d row
(cond
;; the rc and cr case
((and (not u2d) (not v2d))
(cond
;; rc == simple dot product
((eql (first udim) (first vdim))
(values 1 1 (first udim)))
;; cr case
((or (eql (first udim) 1) (eql (first vdim) 1))
(values (first udim) (first vdim) 1))
;; bomb out
(t (error "The matrices ~S and ~S are not conformable for matrix ~
multiplication." u v))))
;; the mm and mc cases
((and u2d (eql (second udim) (first vdim)))
(values (first udim) (if v2d (second vdim) 1) (second udim)))
;; the cm case
((and v2d (eql 1 (first vdim)))
(values (first udim) (second vdim) 1))
;; the rm case
((and v2d (eql (first udim) (first vdim)))
(values 1 (second vdim) (first udim)))
;; the mr case
((and u2d (eql 1 (second udim)))
(values (first udim) (second vdim) 1))
;; bomb out
((or (> (length udim) 2) (> (length vdim) 2))
(error "One of the arrays ~S or ~S has too many dimensions to be ~
multiplied." u v))
(t (error "The matrices ~S and ~S are not conformable for matrix ~
multiplication." u v))))
(setf target
(dot-times-instantiate-target target rows cols u v)))
(progn
;; I think the case where we have a target but no dot-times-env
;; will be rare, so I haven't tried to optimize this part of the
;; code. At least the math ops are the CL ones.
(setf p (isqrt (/ (* (apply #'* udim)
(apply #'* vdim))
(* (apply #'* (dimensions-of target))))))
(setf rows (/ (apply #'* udim) p))
(setf cols (/ (apply #'* vdim) p))))
(values target
rows
cols
p
(setf-erefer (array-rank target) rows)
(erefer (array-rank u) rows)
(erefer (array-rank v) p)))))
;; the interface for clever users.
(defun dot-times-instantiate (u v &optional target)
(declare (optimize speed))
(let (rows cols p target-setf-eref u-eref v-eref)
(multiple-value-setq (target rows cols p
target-setf-eref u-eref v-eref)
(dot-times-instantiate-1 u v target))
(values target
(list rows cols p target-setf-eref u-eref v-eref))))
(defun dot-times-compute (u v &optional
(target nil target-provided-p)
dot-times-env
(plus-op #'ext_+)
(times-op #'ext_*))
(declare (optimize speed))
(let* (accum rows cols p target-setf-eref u-eref v-eref)
(cond (dot-times-env
(multiple-value-setq (rows cols p
target-setf-eref u-eref v-eref)
(apply #'values dot-times-env))
(if (atom target)
(setf target
(dot-times-instantiate-target target rows cols u v))))
(t
(multiple-value-setq (target rows cols p
target-setf-eref u-eref v-eref)
(dot-times-instantiate-1 u v target))))
;; On the Mac anyway, loop is faster than dotimes !!!
;; ... and do is faster than loop for straight iteration. CW.
; (loop for ri from 0 to (1- rows) do
(do ((ri 0 (incf fi)))
((= ri rows))
; (loop for ci from 0 to (1- cols) do
(do ((ci 0 (incf ci)))
((= ci cols))
(funcall target-setf-eref
;; new-value
(progn
;; this structure is a little ugly, but it saves one addition
;; for each time around ie. saves rows * cols additions in
;; total
(setf accum (funcall times-op
(funcall u-eref u ri 0)
(funcall v-eref v 0 ci)))
; (loop for pp from 1 to (1- p) do
(do ((pp 1 (incf pp)))
((= pp p))
(setf accum
(funcall
plus-op
accum
(funcall
times-op
(funcall u-eref u ri pp)
(funcall v-eref v pp ci)))))
accum)
;; rest
target ri ci)))
(if (and (eql rows 1)
(eql cols 1)
(not target-provided-p))
(eref target 0) ;;; in this case, target's a list of length 1 (fastest)
target))) | 7,003 | Common Lisp | .l | 167 | 27.784431 | 85 | 0.43935 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 7c0a1214aac511eab322d6de1d2c1940088827af8196c3e6fff22e83d1ae44c4 | 33,756 | [
-1
] |
33,757 | test.lsp | rwoldford_Quail/source/statistics/models/models_testing,_etc/test.lsp | (in-package :quail)
(setf d1 (data-frame (list '(1 2 3 4)
'(11 19 29 40)
(array '(4 2) :initial-contents '((67 58) (93 24)
(20 21) (22 23)))
(array '(4)
:class 'factor-array
:initial-contents '("Hi" "Lo" "Lo" "Hi")
:levels '("Lo" "Hi"))
(array '(4)
:class 'factor-array
:initial-contents '("Foo" "Bar" "Baz" "Foo")
:levels '("Foo" "Bar" "Baz")))
(list "x" "y" "z" "u" "w")))
(setf m1 (model 'generalized-additive-model "y ~ x + {(* x x)}"))
(setf m2 (model 'generalized-additive-model "y ~ x + {(* z[t 0] z[t 1])}"))
(setf m3 (model 'generalized-additive-model
"y ~ xx{(* x x)} + xz{(+ (* x z[t 0]) (* x z[t 1]))}"))
(setf m4 (model 'generalized-additive-model
"y ~ x * w * u - x . u"))
(setf m5 (model 'generalized-additive-model
"y ~ x - 1"))
(setf fit1 (fit-instantiate m1 d1 :maximum-likelihood))
(setf fit2 (fit-instantiate m2 d1 :maximum-likelihood))
(setf fit3 (fit-instantiate m3 d1 :maximum-likelihood))
(setf fit4 (fit-instantiate m4 d1 :maximum-likelihood))
(setf fit5 (fit-instantiate m5 d :maximum-likelihood))
(setf d2 (data-frame (list (array '(6 2)
:initial-contents '((10 30) (11 30) (11 29)
(28 12) (32 8) (29 9)))
(array '(6) :initial-contents '(10 10 20 20 20 10))
(array '(6 2)
:initial-contents '((10 30) (30 11) (11 29)
(28 12) (32 8) (9 29)))
(array '(6)
:initial-contents '(0 0 0 1 1 1)
:class 'factor-array
:levels '(0 1))
(array '(6)
:initial-contents '(1 2 3 4 5 6))
(array '(6)
:initial-contents '(11 19 28 39 53 55))
(array '(6) :class 'ones-array))
(list "y1" "y2" "y3" "x" "y4" "x4" "ones")))
(setf w1 (array '(6) :initial-contents '(3 5 5 3 5 5)))
(inspect
(setf g1
(glm "y1 ~ ones + x" d2 :family binomial :link logit-link :tolerance .001)))
(setf g2 (glm "y2 ~ x"
d2
:family gaussian
:tolerance .001))
(setf lm1 (lm "y4 ~ x4" d2 :weight w1))
| 2,892 | Common Lisp | .l | 53 | 32.528302 | 84 | 0.387166 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 2488a5fa7e14e2bb53970657591d25b1c2d56885fcac0b519bd12bc34a4178cf | 33,757 | [
-1
] |
33,758 | s-glm-test | rwoldford_Quail/source/statistics/models/models_testing,_etc/s-glm-test | y _ matrix(c(10, 30, 11, 30, 11, 29, 28, 12, 32, 8, 29, 9), ncol=2, byrow=T)
x _ c(-1,-1,-1,1,1,1)
g1 _ glm(y ~ x, family=binomial())
| 142 | Common Lisp | .l | 3 | 44 | 78 | 0.518519 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 5e083dd1c5388c52d0ccb93051a784fa12ffbf21ab8461d1e4dc9afbcc05c3ad | 33,758 | [
-1
] |
33,759 | response-session.lsp | rwoldford_Quail/source/statistics/stat-sessions/response-session.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; response-sessions.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1995
;;;
;;;
;;;
;;;----------------------------------------------------------------------------------
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(model-session glm-session lm-session)))
(defun model-session
(&rest all-args
&key data
(draw? T)
(color wb::*white-color*)
(title NIL)
(viewport NIL)
&allow-other-keys)
"Sets up a view from which a response model may be constructed."
(declare (ignore color)) ; 31JUL2023
(unless (dataset-p data) (setf data (choose-dataset)))
(unless title (setf title "Model session"))
(let*
(;(data-name (text-view :text "Dataset: " ; 31JUL2023 never used
; :draw? NIL
; :viewed-object data))
(data-view (dataset-view :data data
:draw? NIL
:viewed-object data
:signposts? NIL))
(hline1 (line :slope 0 :intercept .5
:viewed-object data))
(hline2 (line :slope 0 :intercept .5
:viewed-object data))
(glm-button (control-button
:viewed-object data
:text
(format NIL "Generalized Linear Modelling")
:left-fn
#'(lambda ()
(apply #'glm-session :data data :draw? T all-args))
:draw? NIL))
(lm-button (control-button
:viewed-object data
:text
(format NIL "Linear Regression")
:left-fn
#'(lambda ()
(apply #'lm-session :data data :draw? T all-args))))
(button-panel
(grid-layout :nsubviews 2
:ncols 2 :box-views? NIL
:gap-x 0.1 :gap-y 0.1
:subviews (list lm-button glm-button)
:cols '(0 .4 .6 1)
:draw? NIL
:viewed-object data
))
(result (view-layout
:viewed-object data
:subviews (list
data-view
hline1
button-panel
hline2 )
:positions '((0 100 60 100)
(0 100 59 60)
(10 90 5 20)
(0 100 0 2)
)
:box-views? NIL
:gap-x 0.1 :gap-y 0.1
))
)
(when draw?
(unless (viewport-p viewport)
(setf viewport
(make-viewport
(make-view-window
:left 10 :right 400
:bottom (- (wb::screen-height) 350)
:top (- (wb::screen-height) 100)
:title (if (dataset-name data)
(format NIL "Modelling ~a" (dataset-name data))
"Modelling Session")))))
(draw-view result :viewport viewport))
result))
(defun glm-session (&rest keyword-args
&key
(data NIL)
;;(model NIL)
(draw? NIL)
(viewport NIL)
&allow-other-keys
)
(unless data
(setf data (choose-dataset)))
(let (;;(title (text-view :text "Model specification"
;; :justification :center
;; :draw? NIL))
(name (text-view :text (concatenate 'string "Modelling "
(dataset-name data))
:draw? NIL))
(data-view (dataset-view :data data
:draw? NIL
:viewed-object data
:signposts? NIL))
(response-label
(text-view :text "Response: "
:draw? NIL))
(response
(text-view :text ""
:draw? NIL))
(predictor-label
(text-view :text "Linear predictor: "
:draw? NIL))
(linear-predictor
(text-view :text ""
:draw? NIL))
#|
(de-activated-cases
(view-layout
:draw? NIL
:positions '((0 1 8.1 10) (0 1 0 8))
:subviews
(list
(text-view :draw? NIL
:text "Deactivate cases"
:justification :center)
(case-display-list
:data data
:draw? NIL
:scrollable? T)))
)
|#
(hline1 (line :slope 0 :intercept .5 :draw? NIL))
(hline2 (line :slope 0 :intercept .5 :draw? NIL))
(hline3 (line :slope 0 :intercept .5 :draw? NIL))
(edit-response-btn (control-button :text "<- Edit"
:draw? NIL))
(edit-predictor-btn (control-button :text "<- Edit"
:draw? NIL))
(fit-button (control-button :text "Fit" :draw? NIL))
;;(save-model-button (control-button :text "Save model" :draw? NIL))
model-spec-layout
;; cases-to-delete
)
;; Entry for the linear predictor on a control button
(setf (left-fn-of edit-predictor-btn)
#'(lambda ()
(highlight-view linear-predictor)
(erase-view linear-predictor)
(set-text
linear-predictor
(wb::prompt-user
:prompt-string
(format NIL
"Enter linear predictor (Wilkinson-Rogers notation). ~%
EG. A + B + C*D ~%
Enter variate labels containing blanks as strings. ~%
Enclose lisp function calls in {} as in { (log x) }")
:initial-string (get-text linear-predictor))
)
(draw-view linear-predictor)))
;; Entry for the response on a control button
(setf (left-fn-of edit-response-btn)
#'(lambda ()
(highlight-view response)
(erase-view response)
(set-text
response
(wb::prompt-user
:prompt-string
(format NIL
"Enter response variate. ~%
If blanks are part of the variate name, ~%
enter the name as a string. ~%
Enclose lisp function calls in {} as in { (log y) }")
:initial-string (get-text response))
)
(draw-view response)))
;; Do the fit button
(setf (left-fn-of fit-button)
#'(lambda ()
(let
((response-var (get-text response))
(lin-pred (get-text linear-predictor))
wilkinson-rogers-formula
fit-object)
(when (string-equal response-var "")
(set-text
response
(wb::prompt-user
:prompt-string
(format NIL
"Enter response variate. ~%
If blanks are part of the variate name, ~%
enter the name as a string. ~%
Enclose lisp function calls in {} as in { (log y) }")
:initial-string (get-text response))
)
(draw-view response)
(setf response-var (get-text response)))
(when (string-equal lin-pred "")
(set-text
linear-predictor
(wb::prompt-user
:prompt-string
(format NIL
"Enter linear predictor (Wilkinson-Rogers notation). ~%
EG. A + B + C*D ~%
Enter variate labels containing blanks as strings. ~%
Enclose lisp function calls in {} as in { (log x) }")
:initial-string (get-text linear-predictor))
)
(draw-view linear-predictor)
(setf lin-pred (get-text linear-predictor)))
(setf wilkinson-rogers-formula
(concatenate 'string
response-var " ~ " lin-pred))
(setf fit-object (glm wilkinson-rogers-formula data))
(display fit-object :draw? T :signposts? T)
)
)
)
#|
;; Do the save-model button
(setf (left-fn-of save-model-button)
#'(lambda ()
(let
((response-var (get-text response))
(lin-pred (get-text linear-predictor))
wilkinson-rogers-formula)
(when (string-equal response-var "")
(set-text
response
(wb::prompt-user
:prompt-string
(format NIL
"Enter response variate. ~%~
If blanks are part of the variate name, ~
enter the name as a string. ~%~
Enclose lisp function calls in {} as in { (log y) }")
:initial-string (get-text response))
)
(draw-view response)
(setf response-var (get-text response)))
(when (string-equal lin-pred "")
(set-text
linear-predictor
(wb::prompt-user
:prompt-string
(format NIL
"Enter linear predictor (Wilkinson-Rogers notation). ~%~
EG. A + B + C*D ~%~
Enter variate labels containing blanks as strings. ~%~
Enclose lisp function calls in {} as in { (log x) }")
:initial-string (get-text linear-predictor))
)
(draw-view linear-predictor)
(setf lin-pred (get-text linear-predictor)))
(setf wilkinson-rogers-formula
(concatenate 'string
response-var " ~ " lin-pred))
(setf model (model 'gaussian-linear-model
wilkinson-rogers-formula))
)
)
)
|#
(setf model-spec-layout
(apply #'view-layout
:viewed-object data
:draw? NIL
:subviews
(list
;;title
name
hline1
data-view
response-label
response
edit-response-btn
predictor-label
linear-predictor
edit-predictor-btn
;;de-activated-cases
hline2
fit-button
;;save-model-button
hline3
)
:positions
'(;;(30 70 95 100) ;; title
(10 40 92 95) ;; name
( 0 100 90 91) ;; hline1
( 0 100 60 89) ;; data-view
( 2 20 45 50) ;; response-label
(21 75 45 50) ;; response
(76 90 45 50) ;; edit-response-btn
( 2 20 40 45) ;; predictor-label
(21 75 40 45) ;; linear-predictor
(76 90 40 45) ;; edit-predictor-btn
;;(4.1 6 1.5 2.8) ;; de-activated-cases
( 0 100 38 40) ;; hline2
(10 30 30 38) ;; fit-button
;;(4.5 5.9 0.3 .9) ;; save-model-button
( 0 100 28 30) ;; bottom line
)
keyword-args
)
)
(if draw?
(draw-view model-spec-layout
:viewport (if viewport
viewport
(make-viewport
(make-view-window
:left 0
:bottom 0
:right (- (wb::screen-width) 50)
:top (- (wb::screen-height) 50)
:title (format NIL "Model session for ~s."
(or (dataset-name data)
"data"))))))
model-spec-layout
)
)
)
(defun lm-session (&rest keyword-args
&key
(data NIL)
;;(model NIL)
(draw? NIL)
(viewport NIL)
&allow-other-keys
)
(unless data (setf data (choose-dataset)))
(let (;;(title (text-view :text "Regression session"
;; :justification :center
;; :draw? NIL))
(name (text-view :text (concatenate 'string "Linear modelling of "
(dataset-name data))
:draw? NIL))
(data-view (dataset-view :data data
:draw? NIL
:viewed-object data
:signposts? NIL))
(response-label
(text-view :text "Response: "
:draw? NIL))
(response
(text-view :text ""
:draw? NIL))
(predictor-label
(text-view :text "Linear predictor: "
:draw? NIL))
(linear-predictor
(text-view :text ""
:draw? NIL))
#|
(de-activated-cases
(view-layout
:draw? NIL
:positions '((0 1 8.1 10) (0 1 0 8))
:subviews
(list
(text-view :draw? NIL
:text "Deactivate cases"
:justification :center)
(case-display-list
:data data
:draw? NIL
:scrollable? T)))
)
|#
(hline1 (line :slope 0 :intercept .5 :draw? NIL))
(hline2 (line :slope 0 :intercept .5 :draw? NIL))
(hline3 (line :slope 0 :intercept .5 :draw? NIL))
(edit-response-btn (control-button :text "<- Edit"
:draw? NIL))
(edit-predictor-btn (control-button :text "<- Edit"
:draw? NIL))
(fit-button (control-button :text "Fit" :draw? NIL))
;;(save-model-button (control-button :text "Save model" :draw? NIL))
model-spec-layout
;; cases-to-delete
)
;; Entry for the linear predictor on a control button
(setf (left-fn-of edit-predictor-btn)
#'(lambda ()
(highlight-view linear-predictor)
(erase-view linear-predictor)
(set-text
linear-predictor
(wb::prompt-user
:prompt-string
(format NIL
"Enter linear predictor (Wilkinson-Rogers notation). ~%
EG. A + B + C*D ~%
Enter variate labels containing blanks as strings. ~%
Enclose lisp function calls in {} as in { (log x) }")
:initial-string (get-text linear-predictor))
)
(draw-view linear-predictor)))
;; Entry for the response on a control button
(setf (left-fn-of edit-response-btn)
#'(lambda ()
(highlight-view response)
(erase-view response)
(set-text
response
(wb::prompt-user
:prompt-string
(format NIL
"Enter response variate. ~%
If blanks are part of the variate name, ~%
enter the name as a string. ~%
Enclose lisp function calls in {} as in { (log y) }")
:initial-string (get-text response))
)
(draw-view response)))
;; Do the fit button
(setf (left-fn-of fit-button)
#'(lambda ()
(let
((response-var (get-text response))
(lin-pred (get-text linear-predictor))
wilkinson-rogers-formula
fit-object)
(when (string-equal response-var "")
(set-text
response
(wb::prompt-user
:prompt-string
(format NIL
"Enter response variate. ~%
If blanks are part of the variate name, ~%
enter the name as a string. ~%
Enclose lisp function calls in {} as in { (log y) }")
:initial-string (get-text response))
)
(draw-view response)
(setf response-var (get-text response)))
(when (string-equal lin-pred "")
(set-text
linear-predictor
(wb::prompt-user
:prompt-string
(format NIL
"Enter linear predictor (Wilkinson-Rogers notation). ~%
EG. A + B + C*D ~%
Enter variate labels containing blanks as strings. ~%
Enclose lisp function calls in {} as in { (log x) }")
:initial-string (get-text linear-predictor))
)
(draw-view linear-predictor)
(setf lin-pred (get-text linear-predictor)))
(setf wilkinson-rogers-formula
(concatenate 'string
response-var " ~ " lin-pred))
(setf fit-object (glm wilkinson-rogers-formula data))
(display fit-object :draw? T :signposts? T)
)
)
)
#|
;; Do the save-model button
(setf (left-fn-of save-model-button)
#'(lambda ()
(let
((response-var (get-text response))
(lin-pred (get-text linear-predictor))
wilkinson-rogers-formula)
(when (string-equal response-var "")
(set-text
response
(wb::prompt-user
:prompt-string
(format NIL
"Enter response variate. ~%~
If blanks are part of the variate name,~
enter the name as a string. ~%~
Enclose lisp function calls in {} as in { (log y) }")
:initial-string (get-text response))
)
(draw-view response)
(setf response-var (get-text response)))
(when (string-equal lin-pred "")
(set-text
linear-predictor
(wb::prompt-user
:prompt-string
(format NIL
"Enter linear predictor (Wilkinson-Rogers notation). ~%~
EG. A + B + C*D ~%~
Enter variate labels containing blanks as strings. ~%~
Enclose lisp function calls in {} as in { (log x) }")
:initial-string (get-text linear-predictor))
)
(draw-view linear-predictor)
(setf lin-pred (get-text linear-predictor)))
(setf wilkinson-rogers-formula
(concatenate 'string
response-var " ~ " lin-pred))
(setf model (model 'gaussian-linear-model
wilkinson-rogers-formula))
)
)
)
|#
(setf model-spec-layout
(apply #'view-layout
:viewed-object data
:draw? NIL
:subviews
(list
;;title
name
hline1
data-view
response-label
response
edit-response-btn
predictor-label
linear-predictor
edit-predictor-btn
;;de-activated-cases
hline2
fit-button
;;save-model-button
hline3
)
:positions
'(;;(30 70 95 100) ;; title
(10 40 92 95) ;; name
( 0 100 90 91) ;; hline1
( 0 100 60 89) ;; data-view
( 2 20 45 50) ;; response-label
(21 75 45 50) ;; response
(76 90 45 50) ;; edit-response-btn
( 2 20 40 45) ;; predictor-label
(21 75 40 45) ;; linear-predictor
(76 90 40 45) ;; edit-predictor-btn
;;(4.1 6 1.5 2.8) ;; de-activated-cases
( 0 100 38 40) ;; hline2
(10 30 30 38) ;; fit-button
;;(4.5 5.9 0.3 .9) ;; save-model-button
( 0 100 28 30) ;; bottom line
)
keyword-args
)
)
(if draw?
(draw-view model-spec-layout
:viewport (if viewport
viewport
(make-viewport
(make-view-window
:left 0
:bottom 0
:right (- (wb::screen-width) 50)
:top (- (wb::screen-height) 50)
:title (format NIL "Linear model session for ~s."
(or (dataset-name data)
"data"))))))
model-spec-layout
)
)
)
| 24,447 | Common Lisp | .l | 579 | 22.780656 | 105 | 0.387841 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 9854685315a2ffc26972e337412b18d2337774e04f695253cc019f234d16d3d7 | 33,759 | [
-1
] |
33,760 | display-probability.lsp | rwoldford_Quail/source/statistics/stat-graphics/display-probability.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; display-probability.lsp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1993
;;;
;;;
;;;
;;;----------------------------------------------------------------------------------
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(display)))
(defmethod display :around
((distribution prob-measure)
&rest grid-plot-args
&key
(draw? T)
(cdf? T)
(pdf? T)
(color vw::*DEFAULT-CURVE-COLOR*)
(title NIL)
(nlines 30)
(from NIL)
(to NIL)
&allow-other-keys)
"Sorts out the from, to, and title arguments. ~
(:rest (:arg grid-plot-args Any keyword acceptable to a grid-plot is acceptable ~
here.)) ~
(:key ~
(:arg draw? T Flag to indicate whether the display is to be drawn or not.) ~
(:arg cdf? T If non-NIL the cumulative distribution function will be displayed.) ~
(:arg pdf? T If non-NIL the probability, or probability density, function will be ~
displayed.) ~
(:arg color vw::*DEFAULT-CURVE-COLOR* The draw color.) ~
(:arg title NIL Title of the display.) ~
(:arg nlines 30 The number of lines to be used in displaying each function.) ~
(:arg from NIL The lower bound to use in the display of the functions. If not a ~
number, then the lowest numerical percentile will be selected.) ~
(:arg to NIL The upper bound to use in the display of the functions. If not a ~
number, then the highest numerical percentile will be selected.) ~
) ~
"
(declare (ignore draw? cdf? pdf? color nlines))
(unless from
(setf from (lower-bound-of distribution)))
(unless to
(setf to (upper-bound-of distribution)))
(if (>= from to)
(quail-error "Display: To display a probability-measure (~s), the lower bound of ~
the display range (here from = ~s) ~
must be less than the upper bound of the display range ~
(here to = ~s).~&"
distribution from to))
(unless (numberp (- to from))
(cond
((not (or (numberp from) (numberp to)))
; (loop for i from 1 to 99
; until (and (numberp from)
; (numberp to)) do
(do ((i 1 (incf i)))
((or (= i 100) (and (numberp from) (numberp to))))
(unless (numberp from)
(setf from (quantile-at distribution (/ i 100))))
(unless (numberp to)
(setf to (quantile-at distribution (/ (- 100 i) 100))))
)
)
((numberp to)
; (loop for i from 1 to 99
; until (numberp from) do
(do ((i 1 (incf i)))
((or (= i 100) (numberp from)))
(setf from (quantile-at distribution (/ i 100)))))
((numberp from)
; (loop for i from 99 downto 1
; until (numberp to) do
(do ((i 99 (decf i)))
((or (= i 0) (numberp to)))
(setf to (quantile-at distribution (/ i 100)))))
)
)
;;(unless (numberp from) (setf from (max -5.0 (lower-bound-of distribution))))
;;(unless (numberp to) (setf to (min 5.0 (upper-bound-of distribution))))
(cond
((not (and (numberp from) (numberp to)))
(quail-error "To display this distribution (~s), it will be necessary ~
to provide numerical values for the range parameters from ~
and to (not from = ~s and to = ~s)."
distribution from to)
)
((>= from to)
(setf to (+ from 1.0))))
(unless title
(setf title (format NIL "The ~s."
(class-name (class-of distribution)))))
(apply #'call-next-method distribution :title title :from from :to to grid-plot-args)
)
(defmethod display ((distribution prob-measure)
&rest grid-plot-args
&key
(draw? T)
(cdf? T)
(pdf? T)
(color vw::*DEFAULT-CURVE-COLOR*)
(title NIL)
(nlines 30)
(from NIL)
(to NIL)
&allow-other-keys)
(declare (ignore grid-plot-args
draw? cdf? pdf?
color title nlines
from to)))
(defmethod display ((distribution continuous-dist)
&rest grid-plot-args
&key
(draw? T)
(cdf? T)
(pdf? T)
(color vw::*DEFAULT-CURVE-COLOR*)
(title NIL)
(nlines 30)
(from NIL)
(to NIL)
&allow-other-keys)
"Display a distribution as a view. ~
(:rest (:arg grid-plot-args Any keyword acceptable to a grid-plot is acceptable ~
here.)) ~
(:key ~
(:arg draw? T Flag to indicate whether the display is to be drawn or not.) ~
(:arg cdf? T If non-NIL the cumulative distribution function will be displayed.) ~
(:arg pdf? T If non-NIL the probability, or probability density, function will be ~
displayed.) ~
(:arg color vw::*DEFAULT-CURVE-COLOR* The draw color.) ~
(:arg title NIL Title of the display.) ~
(:arg nlines 30 The number of lines to be used in displaying each function.) ~
(:arg from NIL The lower bound to use in the display of the functions. If not a ~
number, then the lowest numerical percentile will be selected.) ~
(:arg to NIL The upper bound to use in the display of the functions. If not a ~
number, then the highest numerical percentile will be selected.) ~
) ~
"
(let
(the-plot)
(setf
the-plot
(cond
((and pdf? cdf?)
(let*
((pdf
(function-plot
:function
#'(lambda (x) (pdf-at distribution x))
:domain
(list from to)
:nlines nlines
:left-view t :bottom-view t
:left-label "density" :bottom-label "y"
:viewed-object distribution
:title "Density"
:color color
:draw? NIL
:link? T
))
(cdf
(function-plot
:function
#'(lambda (x) (cdf-at distribution x))
:domain
(list from to)
:nlines
nlines
:left-view t :bottom-view t
:left-label "probability" :bottom-label "y"
:viewed-object distribution
:title "Cumulative distribution"
:color color
:draw? NIL
:link? T
)
)
(view-layout (grid-layout :subviews (list pdf cdf)
:nrows 1 :box-views? NIL
:gap-x 0.1 :gap-y 0.1)))
(apply #'grid-plot :interior-view view-layout :gap-x 0.1 :gap-y 0.1
:title title
:draw? draw?
grid-plot-args)))
(pdf?
(let*
((pdf
(function-plot
:function
#'(lambda (x) (pdf-at distribution x))
:domain
(list from to)
:nlines nlines
:left-view t :bottom-view t
:left-label "density" :bottom-label "y"
:viewed-object distribution
:title "Density"
:color color
:draw? NIL
:link? T
))
(view-layout (grid-layout :subviews (list pdf)
:nrows 1 :box-views? NIL
:gap-x 0.1 :gap-y 0.1)))
(apply #'grid-plot :interior-view view-layout :gap-x 0.1 :gap-y 0.1
:title title
:draw? draw?
grid-plot-args))
)
(cdf?
(let*
((cdf
(function-plot
:function
#'(lambda (x) (cdf-at distribution x))
:domain
(list from to)
:nlines nlines
:left-view t :bottom-view t
:left-label "probability" :bottom-label "y"
:viewed-object distribution
:title "Cumulative distribution"
:color color
:draw? NIL
:link? T
))
(view-layout (grid-layout :subviews (list cdf)
:nrows 1 :box-views? NIL
:gap-x 0.1 :gap-y 0.1)))
(apply #'grid-plot :interior-view view-layout :gap-x 0.1 :gap-y 0.1
:title title
:draw? draw?
grid-plot-args))
)
))
(loop for s-v in (sub-views-of (interior-view-of the-plot))
do (set-drawing-style (interior-view-of s-v)
:color color))
the-plot
)
)
(defmethod display ((distribution discrete-dist) &rest grid-plot-args
&key
(draw? T)
(cdf? T)
(pdf? T)
(color vw::*DEFAULT-CURVE-COLOR*)
(title NIL)
(from NIL)
(to NIL)
&allow-other-keys)
"Display a discrete distribution as a view. ~
(:rest (:arg grid-plot-args Any keyword acceptable to a grid-plot is acceptable ~
here.)) ~
(:key ~
(:arg draw? T Flag to indicate whether the display is to be drawn or not.) ~
(:arg cdf? T If non-NIL the cumulative distribution function will be displayed.) ~
(:arg pdf? T If non-NIL the probability, or probability density, function will be ~
displayed.) ~
(:arg color vw::*DEFAULT-CURVE-COLOR* The draw color.) ~
(:arg title NIL Title of the display.) ~
(:arg from NIL The lower bound to use in the display of the functions. If not a ~
number, then the lowest numerical percentile will be selected.) ~
(:arg to NIL The upper bound to use in the display of the functions. If not a ~
number, then the highest numerical percentile will be selected.) ~
) ~
"
(let
(the-plot)
(setf
the-plot
(cond
((and pdf? cdf?)
(let*
((ys (loop for i from from to to by 1 collect i))
(probs (loop for y in ys
collect (pdf-at distribution y)))
(pdf
(plot
:interior-view
(loop for prob in probs
as y in ys
collect
(line-segment :color color
:endpoints
(list (list y 0)
(list y prob)))
)
:left-view t :bottom-view t
:left-label "probability" :bottom-label "y"
:viewed-object distribution
:title "Density"
:color color
:draw? NIL
:link? T
))
(cum-probs (loop for y in ys
collect (cdf-at distribution y)))
(cdf
(plot
:interior-view
(loop for i from 0 to (- (length ys) 1)
as y in ys
as p in cum-probs
collect
(line-segment :color color
:endpoints
(list (list y p)
(list (+ y 1) p))))
:left-view t :bottom-view t
:left-label "distribution" :bottom-label "y"
:viewed-object distribution
:title "Cumulative Distribution"
:color color
:draw? NIL
:link? T
)
)
(view-layout (grid-layout :subviews (list pdf cdf)
:nrows 1 :box-views? NIL
:gap-x 0.1 :gap-y 0.1)))
(set-extent (left-view-of pdf) 0 (eref (max probs) 0))
(set-extent (bottom-view-of pdf) (- from .1) to)
(set-extent (left-view-of cdf) 0 1)
(set-extent (bottom-view-of cdf) from to)
(apply #'grid-plot :interior-view view-layout :gap-x 0.1 :gap-y 0.1
:title title
:draw? draw?
grid-plot-args)))
(pdf?
(let*
((ys (loop for i from from to to by 1 collect i))
(probs (loop for y in ys
collect (pdf-at distribution y)))
(pdf
(plot
:interior-view
(loop for prob in probs
as y in ys
collect
(line-segment :color color
:endpoints
(list (list y 0)
(list y prob)))
)
:left-view t :bottom-view t
:left-label "probability" :bottom-label "y"
:viewed-object distribution
:title "Density"
:color color
:draw? NIL
:link? T
))
(view-layout (grid-layout :subviews (list pdf)
:nrows 1 :box-views? NIL
:gap-x 0.1 :gap-y 0.1)))
(set-extent (left-view-of pdf) 0 (eref (max probs) 0))
(set-extent (bottom-view-of pdf) (- from .1) to)
(apply #'grid-plot :interior-view view-layout :gap-x 0.1 :gap-y 0.1
:title title
:draw? draw?
grid-plot-args))
)
(cdf?
(let*
((ys (loop for i from from to to by 1 collect i))
(cum-probs (loop for y in ys
collect (cdf-at distribution y)))
(cdf
(plot
:interior-view
(loop for i from 0 to (- (length ys) 1)
as y in ys
as p in cum-probs
collect
(line-segment :color color
:endpoints
(list (list y p)
(list (+ y 1) p))))
:left-view t :bottom-view t
:left-label "distribution" :bottom-label "y"
:viewed-object distribution
:title "Cumulative Distribution"
:color color
:draw? NIL
:link? T
)
)
(view-layout (grid-layout :subviews (list cdf)
:nrows 1 :box-views? NIL
:gap-x 0.1 :gap-y 0.1)))
(set-extent (left-view-of cdf) 0 1)
(set-extent (bottom-view-of cdf) from to)
(apply #'grid-plot :interior-view view-layout :gap-x 0.1 :gap-y 0.1
:title title
:draw? draw?
grid-plot-args))
)
))
(loop for s-v in (sub-views-of (interior-view-of the-plot))
do (draw-view (interior-view-of s-v)
:color color))
the-plot
)
)
| 15,791 | Common Lisp | .l | 416 | 24.490385 | 88 | 0.463166 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 6d8b47af4ca09cda15f028a84ede606872626fc6283ae13cf10167064cf4a33e | 33,760 | [
-1
] |
33,761 | matrix-display.lsp | rwoldford_Quail/source/statistics/stat-graphics/matrix-display.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; matrix-display.lsp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1993
;;;
;;;
;;;
;;;----------------------------------------------------------------------------------
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(display)))
(defmethod display ((thing matrix) &rest grid-plot-args
&key
(draw? T)
(color vw::*DEFAULT-LABEL-COLOR*)
(title NIL)
(gap-x 0.1)
(gap-y 0.1)
(column-labels? T)
(row-labels? T)
(column-labels NIL)
(row-labels NIL)
(row-label-justification '(:left :top))
(col-label-justification '(:center :top))
(cell-justification '(:center :top))
(number-of-characters 10)
(decimal-places 4)
(fixed-point? NIL)
&allow-other-keys)
"A quick and dirty display for matrices."
(flet
((get-string (arg)
(cond
((numberp arg)
(let*
((format-directive
(concatenate 'string
"~"
(format NIL "~a" number-of-characters)
","
(format NIL "~a" decimal-places)
(if fixed-point?
"F"
"G"))))
(format NIL format-directive arg)))
(T
(let*
((format-directive
(concatenate 'string
"~"
(format NIL "~a" number-of-characters)
"@a")))
(format NIL format-directive arg))))))
(let*
((dimensions (dimensions-of thing))
(nrows (first dimensions))
(ncols (if (second dimensions)
(second dimensions)
1))
row0
remaining-rows dummy-label
column-label-views name)
(when row-labels?
(setf row-labels (or row-labels (list-identifiers thing)))
(setf dummy-label (text-view :viewed-object "" :draw? NIL)))
(setf remaining-rows
(loop for i from 0 to (- nrows 1)
as vo = (ref thing i)
collect
(apply #'grid-plot
:viewed-object vo
:interior-view
(grid-layout
:viewed-object vo
:subviews
(cond
(row-labels?
(setf name (nth i row-labels))
(cons (text-view
:viewed-object name
:text (format NIL "~a" name)
:draw? NIL
:justification-mixin row-label-justification)
(loop for j from 0 to (- ncols 1)
as value = (eref thing i j)
collect
(text-view
:viewed-object value
:text (get-string value)
:draw? NIL
:justification-mixin cell-justification))))
(T (loop for j from 0 to (- ncols 1)
as value = (eref thing i j)
collect
(text-view
:viewed-object value
:text (get-string value)
:draw? NIL
:justification-mixin cell-justification))))
:nrows 1
:ncols (if row-labels? (+ ncols 1) ncols)
:box-views? NIL
:gap-x 0.0 :gap-y gap-y)
:gap-x 0.0 :gap-y gap-y
:draw? NIL
:color color
grid-plot-args)))
(when column-labels?
(setf column-labels (or column-labels (list-variates thing)))
(setf column-label-views
(loop for name in column-labels
collect
(text-view
:viewed-object name
:text (format NIL "~a" name)
:draw? NIL
:justification-mixin col-label-justification)))
(setf row0
(apply #'grid-plot
:viewed-object thing
:interior-view
(grid-layout
:viewed-object thing
:subviews
(if row-labels?
(cons dummy-label column-label-views)
column-label-views)
:nrows 1
:ncols (if row-labels? (+ ncols 1) ncols)
:box-views? NIL
:gap-x 0.0 :gap-y gap-y)
:gap-x 0.0 :gap-y gap-y
:draw? NIL
:color color
grid-plot-args)))
(apply #'grid-plot
:viewed-object thing
:interior-view
(grid-layout
:viewed-object thing
:subviews
(if column-labels?
(cons row0 remaining-rows)
remaining-rows)
:nrows
(if column-labels?
(+ 1 nrows)
nrows)
:ncols 1
:box-views? NIL
:gap-x gap-x :gap-y 0.0)
:gap-x gap-x :gap-y 0.0
:draw? draw?
:color color
:title title
grid-plot-args)
)))
| 6,713 | Common Lisp | .l | 165 | 20.678788 | 86 | 0.351943 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | c16776ec9cedad7f66fe4abb071be2bf8b0bc0fb600bd78f6e31812089a4160f | 33,761 | [
-1
] |
33,762 | qq-plot.lsp | rwoldford_Quail/source/statistics/stat-graphics/qq-plot.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; qq-plot.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1993 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1993
;;;
;;;
;;;--------------------------------------------------------------------------------
;;;
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(qq-plot qq-gauss)))
(defgeneric qq-plot (dist1 dist2
&rest plot-args
&key percentiles title draw? lines?
&allow-other-keys)
(:documentation
"Produce a quantile-quantile plot at the selected percentiles. ~
(:required (:arg dist1 The distribution whose quantiles are ~
plotted as the x-coordinate.) ~
(:arg dist2 The distribution whose quantiles are ~
plotted as the y-coordinate.)) ~
(:key ~
(:arg percentiles NIL The percentiles at which the quantiles are to ~
be calculated. This must be a refable object whose elements are between ~
0 and 1. If NIL, either a sequence of the 99 elements from 0.01 to 0.99 ~
is used, or if one of the required arguments is a refable object of finite ~
size, then the percentiles defined by its empirical distribution are used.) ~
(:arg lines? NIL If non-NIL then a lines-plot is constructed. If NIL ~
then a scatterplot is constructed.)~
(:arg title \"Quantile Quantile Plot\" A string to appear as the title of the plot.) ~
(:arg draw? T Toggles whether the plot should be drawn once created.)) ~
(:rest ~
(:arg plot-args NIL Keyword arguments to be passed on to the plot at ~
construction.))"))
(defmethod-multi qq-plot ((dist1 (array dimensioned-ref-object))
(dist2 T)
&rest plot-args
&key (percentiles NIL percentiles?)
(title "Quantile-Quantile Plot")
(draw? T)
(lines? NIL)
&allow-other-keys)
(unless percentiles?
(setf percentiles :standard))
(let
((plot-fn (if lines? #'lines-plot #'scatterplot)))
(cond
((eq percentiles :standard)
(apply plot-fn
:x (sort dist1 #'< :copy? T)
:y (array (quantile-at dist2
(let ((n (number-of-elements dist1)))
(setf percentiles
(loop for i from 1 to n
collect (/ (- i 0.5) n)))))
)
:title title
:draw? draw? plot-args))
(percentiles
(apply plot-fn
:x (quantile-at dist1 percentiles)
:y (quantile-at dist2 percentiles)
:title title
:draw? draw? plot-args))
(T (setf percentiles (cdf-at dist1 dist1))
(apply plot-fn
:x dist1
:y (quantile-at dist2 percentiles)
:title title
:draw? draw? plot-args)))))
(defmethod qq-plot ((dist1 sequence)
(dist2 T)
&rest plot-args
&key (percentiles NIL percentiles?)
(title "Quantile-Quantile Plot")
(draw? T)
(lines? NIL)
&allow-other-keys)
(unless percentiles?
(setf percentiles :standard))
(let
((plot-fn (if lines? #'lines-plot #'scatterplot)))
(cond
((eq percentiles :standard)
(apply plot-fn
:x (sort dist1 #'< :copy? T)
:y (quantile-at dist2
(let ((n (number-of-elements dist1)))
(setf percentiles
(loop for i from 1 to n
collect (/ (- i 0.5) n)))))
:title title
:draw? draw? plot-args))
(percentiles
(apply plot-fn
:x (quantile-at dist1 percentiles)
:y (quantile-at dist2 percentiles)
:title title
:draw? draw? plot-args))
(T (setf percentiles (cdf-at dist1 dist1))
(apply plot-fn
:x dist1
:y (quantile-at dist2 percentiles)
:title title
:draw? draw? plot-args)))))
(defmethod qq-plot ((dist1 T)
(dist2 sequence)
&rest plot-args
&key (percentiles NIL percentiles?)
(title "Quantile Quantile Plot")
(draw? T)
(lines? NIL)
&allow-other-keys)
(unless percentiles?
(setf percentiles :standard))
(let
((plot-fn (if lines? #'lines-plot #'scatterplot)))
(cond
((eq percentiles :standard)
(apply plot-fn
:x (quantile-at dist1
(let ((n (number-of-elements dist2)))
(setf percentiles
(loop for i from 1 to n
collect (/ (- i 0.5) n)))))
:y (sort dist2 #'< :copy? T)
:title title
:draw? draw? plot-args))
(percentiles
(apply plot-fn
:x (quantile-at dist1 percentiles)
:y (quantile-at dist2 percentiles)
:title title
:draw? draw? plot-args))
(T (setf percentiles (cdf-at dist2 dist2))
(apply plot-fn
:x (quantile-at dist1 percentiles)
:y dist2
:title title
:draw? draw? plot-args))
)))
(defmethod-multi qq-plot ((dist1 T)
(dist2 (array dimensioned-ref-object))
&rest plot-args
&key (percentiles NIL percentiles?)
(title "Quantile Quantile Plot")
(draw? T)
(lines? NIL)
&allow-other-keys)
(unless percentiles?
(setf percentiles :standard))
(let
((plot-fn (if lines? #'lines-plot #'scatterplot)))
(cond
((eq percentiles :standard)
(apply plot-fn
:x (array (quantile-at dist1
(let ((n (number-of-elements dist2)))
(setf percentiles
(loop for i from 1 to n
collect (/ (- i 0.5) n))))))
:y (sort dist2 #'< :copy? T)
:title title
:draw? draw? plot-args))
(percentiles
(apply plot-fn
:x (quantile-at dist1 percentiles)
:y (quantile-at dist2 percentiles)
:title title
:draw? draw? plot-args))
(T (setf percentiles (cdf-at dist2 dist2))
(apply plot-fn
:x (quantile-at dist1 percentiles)
:y dist2
:title title
:draw? draw? plot-args))
)))
(defmethod qq-plot ((dist1 prob-measure)
(dist2 prob-measure)
&rest plot-args
&key (percentiles NIL)
(title "Quantile Quantile Plot")
(draw? T)
(lines? NIL)
&allow-other-keys)
(let
((plot-fn (if lines? #'lines-plot #'scatterplot)))
(cond
(percentiles
(apply plot-fn
:x (quantile-at dist1 percentiles)
:y (quantile-at dist2 percentiles)
:title title
:draw? draw? plot-args))
(T (setf percentiles (seq 0.1 .9 .05))
(apply plot-fn
:x (quantile-at dist1 percentiles)
:y (quantile-at dist2 percentiles)
:title title
:draw? draw? plot-args)))))
(defun qq-gauss (y &rest plot-args
&key (percentiles NIL)
(title "Gaussian QQ Plot")
(draw? T)
(lines? NIL)
(bottom-label "Gaussian quantiles")
&allow-other-keys)
"Produce a gaussian quantile-quantile plot at the selected percentiles. ~
(:required (:arg y The data or distribution whose quantiles are ~
plotted as the y-coordinate against the corresponding standard ~
gaussian quantiles ~
on the x-coordinate.)) ~
(:key ~
(:arg percentiles NIL The percentiles at which the quantiles are to ~
be calculated. This must be a refable object whose elements are between ~
0 and 1. If NIL, a sequence is constructed and used. The constructed ~
sequence is either the 99 elements from 0.01 to 0.99 or, if the required ~
argument is a refable object having n elements, it is the sequence ~
of n elements whose i'th element is (/ (- i 0.5) n).) ~
(:arg title \"GaussianQQPlot\" A string to appear as the title of the plot.) ~
(:arg draw? T Toggles whether the plot should be drawn once created.) ~
(:arg bottom-label \"GaussianQuantiles\" Label to appear on the x axis.)) ~
(:rest ~
(:arg plot-args NIL Keyword arguments to be passed on to the plot at ~
construction.))"
(declare (special *gaussian-dist*))
(unless percentiles
(setf percentiles :standard)
)
(apply #'qq-plot
*gaussian-dist* y
:percentiles percentiles
:title title
:draw? draw?
:lines? lines?
:bottom-label bottom-label
plot-args))
| 9,997 | Common Lisp | .l | 244 | 27.295082 | 91 | 0.48637 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 0f59f5e89a36e82af27875ac9aaca2a6eed42cf3abbcffbe9676b2e470501062 | 33,762 | [
-1
] |
33,763 | stem.lsp | rwoldford_Quail/source/statistics/stat-graphics/stem.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; stem.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;;
;;; Authors:
;;; J.W.H. Law 1995 University of Waterloo
;;;
;;;
;;;
;;;----------------------------------------------------------------------------------
;;;(in-package :views)
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(stem stem-view stem-plot)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; The stem-and-leaf display
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#|
;;;; Some data sets
(defconstant tempdata (array '(((53.07 70.2688 70.1) (73.1 84.38 55.3) (78.5 63.5 71.4))
((53.4 82.5 67.3) (69.5 73.0 73.1) (73.2 73.2 73.5))
((73.6 73.4 73.6) (73.9 73.9 55.7) (85.8 95.4 51.1))
((74.4 54.1 77.8) (52.4 69.1 53.5) (64.3 82.7 0.5))
((55.7 70.5 87.5) (50.7 59.5 59.1) (59.3 59.6 59.7))
((59.7 59.4 0.1) (-0.7 -0.7 -0.5) (-0.6 -0.4 -7.8)))
:dimensions '(6 3 3)))
(defconstant tempdata1 (array '((3.25 3.54 3.23 3.76 3.12 2.87 2.54 2.45 2.08 2.06 1.02
1.03 1.70 1.80 1.90 0.10 0.20 0.30 0.40 0.13 0.23 0.25
0.44)
(0.76 0.88 0.01 -.01 -0.07 -.05 -0.10 -.09 -.30 -.20
-.70 -.69 -.50 -.12 -1.2 -.34 -.44 -.66 -.44 -1.3 -1.7
-2.5 -3.6))
:dimensions '(2 23)))
(defconstant tempdata2 (array '(1.12 1.13 1.14 1.80 1.11 1.34 1.23 1.72 1.32 1.22 1.33
1.21 1.02 1.22 1.19 1.18 1.12 1.24 1.14 1.33 1.32 1.38
1.37 1.10 1.01 1.23 1.14 1.31 1.34 1.33 1.37 1.32 1.23
1.28 1.28)
:dimensions '(1 35)))
|#
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun stem_partition (data-list low high)
(let* ((low-pos (slice-positions-if #'(lambda (x) (< x low)) data-list))
(high-pos (slice-positions-if #'(lambda (x) (> x high)) data-list))
(mid-pos (slice-positions-if #'(lambda (x) (and (> x low) (< x high)))
data-list))
(low-list nil)
(high-list nil)
(mid-list nil))
(setf low-list (loop for i in low-pos collect
(row-major-eref data-list i)))
(setf high-list (loop for i in high-pos collect
(row-major-eref data-list i)))
(setf mid-list (loop for i in mid-pos collect
(row-major-eref data-list i)))
(list low-list mid-list high-list)))
(defun stem_default (unit leafwidth spdata)
(let* ((range (- (max spdata) (min spdata)))
(width leafwidth)
(a nil) (b nil) (u unit))
(cond ((numberp unit)
(setf u u))
(t
(if (numberp width)
(setf width width)
(setf width 10))
(setf a (/ (* range 10) (* 20 width)))
(setf u (/ (expt 10 (ceiling (log a 10))) 10))))
(cond ((numberp leafwidth)
(setf width width))
(t
(setf b (/ range u 10))
(cond
((> (* b 2) 20) (setf width 10))
((> (* b 5) 20) (setf width 5))
(t (setf width 2)))))
(list (float u) width)))
(defun stem_splitlist (dlist unit)
(let* ((stem1 nil)
(leaf1 nil))
(dolist (num dlist)
(let* ((sign (signum num))
(norm (* sign num))
(multiplier (/ 0.1 unit))
(num2 (* multiplier norm))
(stemnorm (truncate num2))
(leafnorm (- num2 stemnorm))
(stem (truncate (* sign stemnorm)))
(leaf (truncate (+ 0.001 (* 10 leafnorm)))))
(cond
((and (= 0 stem) (= -1 sign))
(setf stem1 (push -0.01 stem1)))
((= 0 stem)
(setf stem1 (push 0.01 stem1)))
(T
(setf stem (push stem stem1))))
(setf leaf1 (push leaf leaf1))))
(list stem1 leaf1)))
(defun stem_pair (stem leaf initial)
(cond
((null stem)
initial)
(t
(stem_pair (cdr stem) (cdr leaf) (cons (list (car stem) (car leaf)) initial)))))
(defun stem_group (initial pair-list)
(flet ((exam (a i)
(= a i)))
(let* ((minimum (caar pair-list))
(maximum (caar (last pair-list)))
(result nil))
(do ((i maximum (- i 1)))
((< i minimum) initial)
(cond
((= i 0)
(setf i 0.01)
(setf result (delete-if-not #'(lambda (x)
(exam x i)) pair-list :key #'car))
(if (null result)
(setf result (cons (list i nil) nil))
(setf result result))
(setf initial (cons result initial))
(setf i -0.01)
(setf result (delete-if-not #'(lambda (x)
(exam x i)) pair-list :key #'car))
(if (null result)
(setf result (cons (list i nil) nil))
(setf result result))
(setf initial (cons result initial))
(setf i 0))
(t
(setf result (delete-if-not #'(lambda (x)
(exam x i)) pair-list :key #'car))
(if (null result)
(setf result (cons (list i nil) nil))
(setf result result))
(setf initial (cons result initial))))))))
(defun stem_again (group-list leafwidth)
(let* ((finish nil)
(counter nil)
(flag nil)
(part1 nil)
(part2 nil))
(cond
((= leafwidth 10)
(dolist (item group-list)
(setf finish (stem_leaf item leafwidth))
(setf part1 (first finish))
(setf part2 (second finish))
(setf counter (cons (car part1) counter))
(setf flag (cons (car part2) flag)))
(list (reverse counter) (reverse flag)))
((= leafwidth 5)
(dolist (item group-list)
(setf finish (stem_leaf item leafwidth))
(setf part1 (first finish))
(setf part2 (second finish))
(setf counter (cons (cadr part1) (cons (car part1) counter)))
(setf flag (cons (cadr part2) (cons (car part2) flag))))
(list (reverse counter) (reverse flag)))
((= leafwidth 2)
(dolist (item group-list)
(setf finish (stem_leaf item leafwidth))
(setf part1 (first finish))
(setf part2 (second finish))
(setf counter
(cons (car (cddddr part1))
(cons (cadddr part1)
(cons (caddr part1)
(cons (cadr part1)
(cons (car part1) counter))))))
(setf flag
(cons (car (cddddr part2))
(cons (cadddr part2)
(cons (caddr part2)
(cons (cadr part2)
(cons (car part2) flag)))))))
(list (reverse counter) (reverse flag))))))
(defun stem_leaf (datalist leafwidth)
(flet ((exam (a i)
(and (< a i) (>= a (- i leafwidth)))))
(let* ((initial nil) (count nil)
(result nil))
(do ((i leafwidth (+ i leafwidth)))
((> i 10) initial)
(cond
((numberp (second (car datalist)))
(setf result (remove-if-not #'(lambda (x)
(exam x i)) datalist :key #'second)))
(t
(setf result nil)))
(if (null result)
(setf result (cons (list (caar datalist) " ") nil))
result)
(if (stringp (second (car result)))
(setf count (cons 0 count))
(setf count (cons (length result) count)))
(setf initial (cons result initial)))
(if (> (caar datalist) 0)
(setf initial (reverse initial))
initial)
(if (> (caar datalist) 0)
(setf count (reverse count))
count)
(list count initial))))
(defun stem_marker (listlength stopper)
(let* ((total 0)
(flag (cons (car listlength) nil)))
(do ((i (cdr listlength) (cdr i)))
((>= total stopper) flag)
(cond
((= (car i) 0)
flag)
(t
(setf total (+ (car flag) (car i)))
(setf flag (push total flag)))))))
(defun stem_depth (newlist data-length)
(let* ((stop 0) (list1 nil) (list2 nil))
(if (oddp data-length)
(setf stop (/ (+ data-length 1) 2))
(setf stop (/ data-length 2)))
(setf list1 (stem_marker newlist stop))
(setf list2 (stem_marker (reverse newlist) stop))
(cond
((oddp data-length)
(setf (car list1) (cons (- (first list1) (second list1)) nil))
(list (reverse list1) (cdr list2)))
((= (car list1) (car list2))
(setf (car list1) (cons (- (first list1) (second list1)) nil))
(setf (car list2) (cons (- (first list2) (second list2)) nil))
(list (reverse list1) list2))
(t
(setf (car list1) (cons (- (first list1) (second list1)) nil))
(list (reverse list1) (cdr list2))))))
(defun stem_print (output-stream depths lowlist highlist regroup leafwidth)
(let* ((label nil) (flag (first depths)) (flag1 (cadr depths)) (letter nil))
(cond
((= leafwidth 5)
(setf label '("*" ".")))
((= leafwidth 2)
(setf label '("*" "s" "t" "u" ".")))
(t
(setf label '("*"))))
(setf letter label)
(cond
((= (car flag) 0)
(setf flag (cdr flag))
(format output-stream "~%"))
(t
(format output-stream "~%~a~4t low ~,3t |~a" (car flag) lowlist)
(setf flag (cdr flag))))
(dolist (item regroup)
(cond
((numberp (second (car item)))
(format output-stream "~%~a~5t" (car flag))
(cond ((equalp (caar item) 0.01)
(format output-stream "+0"))
((equalp (caar item) -0.01)
(format output-stream "-0"))
(t
(format output-stream "~a" (caar item))))
(format output-stream "~a~,3t |" (car letter))
(dolist (subitem item)
(format output-stream "~a" (second subitem)))
(setf flag (cdr flag)))
(t
(format output-stream "~%~5t")
(cond
((equalp (caar item) 0.01)
(format output-stream "+0"))
((equalp (caar item) -0.01)
(format output-stream "-0"))
(t
(format output-stream "~a" (caar item))))
(format output-stream "~a~,3t |" (car letter))))
(if (null flag)
(setf flag flag1) flag)
(if (equalp letter (last letter))
(setf letter label)
(setf letter (cdr letter))))
(cond
((null highlist)
(format output-stream "~%"))
(t
(format output-stream "~%~a~3t high ~,3t |~a"
(car (last flag1)) highlist)))))
;;;;The main function
(defun stem (data &key (unit nil) (leafwidth nil) (low -infinity)
(high infinity) (output-stream *quail-terminal-io*))
;;;;The documentation string
"(:capsule The function stem takes a batch of data values and creates a stem-and-leaf ~
display.)~
(:elaboration The stem-and-leaf display enables us to see how wide the range of ~
values the data cover, where the values are concentrated, and so on. ~%~
A column of depths is located to the left of the stem column. The depth is the ~
cumulative number of leaves from the nearest end of the batch ~
up to and including the current stem. ~
For the stem containing the median, the depth is not uniquely defined so ~
instead the number of leaves on that stem is recorded ~
in parentheses. Naturally, the depths increase from each end ~
towards the middle of the batch.
Also, you can specify the range of the data to be displayed using the keyword arguments ~
low and high.) ~
(:required (:arg data The data to be displayed.)) ~
(:returns A stem-and-leaf display with a depth column.) ~
(:key (:arg unit 1 Determines the decimal place of the leaf.) ~
(:arg leafwidth 10 This is the maximal number of different leaf values on each stem. ~
It must be one of 2, 5, or 10.) ~
(:arg low -infinity Values less than this are set aside from the main body ~
of the display.) ~
(:arg high +infinity Values greater than this are set aside from the main body ~
of the display.) ~
(:arg output *quail-terminal-io* A stream capable of receiving output.)
)"
(let* ((data-length (number-of-elements data))
(sort-data (sort data #'<))
(part-data (stem_partition sort-data low high))
(lowlist (first part-data))
(highlist (third part-data))
(value (stem_default unit leafwidth (second part-data)))
(newunit (first value))
(newwidth (second value))
(split-data (stem_splitlist (reverse (second part-data)) newunit))
(pair-data (stem_pair (first split-data) (second split-data) nil))
(group-data (stem_group nil (reverse pair-data)))
(regroup-data (stem_again group-data newwidth))
(new1 (reverse (first regroup-data)))
(new2 (push (length highlist) new1))
(new3 (reverse new2))
(new4 (push (length lowlist) new3))
(depth-data (stem_depth new4 data-length)))
(format output-stream "~%(n= ~a)" data-length)
(format output-stream "~%Depths (unit= ~a)~%~%" newunit)
(stem_print output-stream depth-data lowlist highlist
(second regroup-data) newwidth)))
;;;;The end of the program
(defun stem-view (data
&rest view-args
&key
(unit NIL)
(leafwidth NIL)
(low -infinity)
(high infinity)
(draw? NIL))
"(:capsule The function stem takes a batch of data values and creates a stem-and-leaf ~
display.)~
(:elaboration The stem-and-leaf display enables us to see how wide the range of ~
values the data cover, where the values are concentrated, and so on. ~%~
A column of depths is located to the left of the stem column. The depth is the ~
cumulative number of leaves from the nearest end of the batch ~
up to and including the current stem. ~
For the stem containing the median, the depth is not uniquely defined so ~
instead the number of leaves on that stem is recorded ~
in parentheses. Naturally, the depths increase from each end ~
towards the middle of the batch.
Also, you can specify the range of the data to be displayed using the keyword arguments ~
low and high.) ~
(:required (:arg data The data to be displayed.)) ~
(:rest (:arg view-args Arguments such as style parameters to be past on to the ~
view at creation time.) ) ~
(:returns A stem-and-leaf display with a depth column.) ~
(:key (:arg unit 1 Determines the decimal place of the leaf.) ~
(:arg leafwidth 10 This is the maximal number of different leaf values on each stem. ~
It must be one of 2, 5, or 10.) ~
(:arg low -infinity Values less than this are set aside from the main body ~
of the display.) ~
(:arg high +infinity Values greater than this are set aside from the main body ~
of the display.) ~
(:arg draw? NIL Should the stem and leaf plot be drawn in its own view-window?) ~
)"
(let ((output (make-string-output-stream))
result)
(with-open-stream (s output)
(stem data
:unit unit
:leafwidth leafwidth
:low low
:high high
:output-stream s)
(setf result (get-output-stream-string s)))
(format *terminal-io* result)
(apply #'text-view :text result :draw? draw? view-args)
)
)
| 17,163 | Common Lisp | .l | 387 | 32.524548 | 94 | 0.494885 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | e406039b711ae3b5237013cf262b386755df958ac6801afae2dd7c78b8234ecc | 33,763 | [
-1
] |
33,764 | matrix.lsp | rwoldford_Quail/source/statistics/stat-graphics/matrix.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; matrix.lsp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1993
;;;
;;;
;;;
;;;----------------------------------------------------------------------------------
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(display)))
(defmethod display ((thing matrix) &rest grid-plot-args
&key
(draw? T)
(color *default-label-color*)
(title NIL)
(gap-x 0.1)
(gap-y 0.1)
&allow-other-keys)
"A quick and dirty display for matrices."
(let*
((dimensions (dimensions-of thing))
(nrows (first dimensions))
(ncols (second dimensions))
(dummy-label (label :viewed-object ""
:draw? NIL))
(column-labels
(loop for name in (list-variates thing)
collect
(text-view
:viewed-object name
:text (format NIL "~a" name)
:draw? NIL
:justification-mixin '(:center :top))))
(row0
(apply #'grid-plot
:viewed-object thing
:interior-view
(grid-layout
:viewed-object thing
:subviews
(cons dummy-label column-labels)
:nrows 1
:ncols (+ 1 ncols)
:box-views? NIL
:gap-x 0.0 :gap-y gap-y)
:gap-x 0.0 :gap-y gap-y
:draw? NIL
:color color
grid-plot-args))
(remaining-rows
(loop for name in (list-identifiers thing)
as i from 0 to (- nrows 1)
as vo = (ref thing i)
collect
(apply #'grid-plot
:viewed-object vo
:interior-view
(grid-layout
:viewed-object vo
:subviews
(cons (text-view
:viewed-object name
:text (format NIL "~a" name)
:draw? NIL
:justification-mixin '(:left :top))
(loop for j from 0 to (- ncols 1)
as value = (eref thing i j)
collect
(text-view
:viewed-object value
:text (format NIL "~a" value)
:draw? NIL
:justification-mixin '(:center :top))))
:nrows 1
:ncols (+ 1 ncols)
:box-views? NIL
:gap-x 0.0 :gap-y gap-y)
:gap-x 0.0 :gap-y gap-y
:draw? NIL
:color color
grid-plot-args)))
)
(apply #'grid-plot
:viewed-object thing
:interior-view
(grid-layout
:viewed-object thing
:subviews
(cons row0 remaining-rows)
:nrows (+ 1 nrows)
:ncols 1
:box-views? NIL
:gap-x gap-x :gap-y 0.0)
:gap-x gap-x :gap-y 0.0
:draw? draw?
:color color
:title title
grid-plot-args)
))
| 3,768 | Common Lisp | .l | 108 | 20.333333 | 86 | 0.373352 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | bc384ff2ce234e6397411547e6ba3210ea0b8309f1a86125fcc9d536a8f363c4 | 33,764 | [
-1
] |
33,765 | imagel.lsp | rwoldford_Quail/source/statistics/stat-graphics/imagel.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; imagel.lsp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;;
;;; This file is part of the Views system, a toolkit for interactive statistical graphics.
;;;
;;;
;;; Authors:
;;; N. Wiebe 1999
;;;
;;;
;;;----------------------------------------------------------------------------------
(in-package :views)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(imagel)))
;;;----------------------------------------------------------------------------------
(defmacro with-imagel-bounds
(imagel-sym vp xmin xmax ymin ymax &body do-forms)
(let ((c (gensym "c"))
(xc (gensym "xc"))
(yc (gensym "yc"))
(rad1 (gensym "rad1"))
(rad2 (gensym "rad2"))
(width (gensym "width"))
(height (gensym "height")))
`(let* ((,width (draw-style ,imagel-sym :width))
(,height (draw-style ,imagel-sym :height))
(,c (centre-of ,vp))
(,xc (2d-position-x ,c))
(,yc (2d-position-y ,c))
(,rad1 (truncate ,width 2))
(,rad2 (truncate ,height 2)))
(setq ,xmin (- ,xc ,rad1))
(setq ,xmax (+ ,xmin ,width))
(setq ,ymin (- ,yc ,rad2))
(setq ,ymax (+ ,ymin ,height))
,@do-forms)))
(defclass imagel (fixed-size-rectangle linkable-mixin simple-view)
((middle-menu :allocation :class :initform nil)
(style-keys :initform '(:symbol :width :height :color :highlight-color)
:allocation :class)
(label
:initarg :label
:initform #'dataset-name ;identifier-name
:documentation "Function which when applied to subject gives a label, or a label")
)
(:default-initargs :symbol :box :width 4 :height 4 :color *default-point-color*
:highlight-color *default-highlight-color*
:left-fn (list #'default-left-fn :viewport )))
(defmethod viewed-object-description-string :around ((self imagel) )
(if (find-parent self)
(format nil "~A: ~s" (z-variate-of (find-parent self))
(elt (z-coords-of (find-parent self)
:cases (list (viewed-object-of self))) 0))
(call-next-method)))
(defmethod default-left-fn ((self imagel) &key viewport &allow-other-keys)
(identify-view self :viewport viewport)
)
(defmethod highlight-operation ((self imagel))
:default
)
(defmethod highlight-view ((self imagel)
&key viewport operation)
(setq operation (or operation (highlight-operation self)))
(let* (l r b tp)
(with-exposed-viewports self viewport vp
(with-imagel-bounds self vp l r b tp
(wb:canvas-highlight-rectangle (window-of vp) l r b tp
:color (draw-style self :highlight-color)
:operation operation)))))
(defmethod draw-view ((self imagel) &key viewport)
(with-exposed-viewports self viewport vp
(let ((color (draw-style self :color))
(bw (window-of vp))
xmin xmax ymin ymax )
(with-imagel-bounds self vp xmin xmax ymin ymax
(wb:canvas-draw-filled-rectangle bw xmin xmax ymin ymax :color color)))))
(defmethod label-of ((self imagel))
(let ((l (slot-value self 'label)))
(if (functionp l)
(funcall l (viewed-object-of self))
l)))
#|
(defmethod reshape-viewport :after ((self view-with-width-height) viewport &rest ignore)
;; point symbol viewports are not resized when window is reshaped
(declare (ignore ignore viewport))
(fix-viewports self))
(defmethod fix-viewports ((self imagel) &key viewport )
(let* ((width (draw-style self :width))
(height (draw-style self :height)))
(loop for vp in (if viewport
(list viewport ) (viewports-of self) )
do
(set-viewport-width-height vp (+ 2 width) (+ 2 height))
)))
(defun imagel-key (sym)
"Returns the symbol key for sym, if one exists."
(cond
((member sym *point-symbol-types*) sym)
((stringp sym) :text)
((wb:bitmap-p sym) :bitmap)
(t nil)))
(defmethod set-draw-style :after ((self imagel) (style (eql :width)) new &key)
(declare (ignore new))
(fix-viewports self))
(defmethod set-draw-style :after ((self imagel) (style (eql :height)) new &key)
(declare (ignore new))
(fix-viewports self))
|#
(defmethod clear-view-viewport ((self imagel)
&key viewport)
;; erases the view in VIEWPORT, if supplied, else erases in all exposed
;; viewports
(with-exposed-viewports self viewport vp
(let* ((w (window-of vp))
rl rb rw rh)
(when vp
(setq rl (+ 1 (left-of vp)))
(setq rb (+ 1 (bottom-of vp)))
(setq rw (- (width-of vp) 2))
(setq rh (- (height-of vp) 2))
(wb:canvas-clear w
:canvas-left rl :canvas-bottom rb
:width rw :height rh)))))
(defmethod rectangle-width-of ((self imagel))
(draw-style self :width))
(defmethod rectangle-height-of ((self imagel))
(draw-style self :height))
(defmethod (setf rectangle-width-of) (new (self imagel) )
(set-draw-style self :width new))
(defmethod (setf rectangle-height-of) (new (self imagel) )
(set-draw-style self :height new))
(defmethod rectangle-width-increment ((self imagel))
(if (>= (draw-style self :width) 3) 2 1))
(defmethod rectangle-height-increment ((self imagel))
(if (>= (draw-style self :height) 3) 2 1))
(defmethod set-view-width ((self imagel) new &rest args)
(apply #'set-drawing-style self :width new args)
(setf (slot-value self 'rectangle-width) (draw-style self :width)))
(defmethod set-view-height ((self imagel) new &rest args)
(apply #'set-drawing-style self :height new args)
(setf (slot-value self 'rectangle-height) (draw-style self :height)))
(defmethod description-string ((self imagel))
(let ((name (or (label-of self) (viewed-object-description-string self))))
(if name
(format nil "~A viewing ~A" self name)
(format nil "~A" self))))
(defmethod distance-to-location ((self imagel) viewport location)
(let ((locn-c (if (region-p location)
(centre-of location) location)))
(distance-from viewport locn-c)))
(defmethod add-viewport ((self imagel) vp pvp
&key compute-transform?)
(declare (ignore compute-transform?))
(call-next-method self vp pvp :compute-transform? nil))
;;should be in clone.lisp
(defmethod toplevel-clone-list ((self imagel))
(append
(list :label (label-of self) )
(call-next-method)))
#|
(defmethod set-highlight-range-gray ((self imagel))
(let* ((value (image-value-of self))
(lower (wb::prompt-user :prompt-string (format NIL "Enter lower end of range:")
:type 'number :read-type :eval
:initial-string (format NIL "~s" (- value 5))))
;make 5 a constant?
(upper (wb::prompt-user :prompt-string (format NIL "Enter higher end of range:")
:type 'number :read-type :eval
:initial-string (format NIL "~s" (+ value 5))))
(parent (find-parent self)))
(if parent
(progn (loop for sb in (subviews-of parent)
for sb-inten = (image-value-of sb) do
(when (and (<= lower sb-inten) (>= upper sb-inten))
(select-view sb )))))))
(defmethod set-highlight-same-gray ((self imagel))
(let ((value (image-value-of self))
(parent (find-parent self)))
(if parent
(progn (loop for sb in (subviews-of parent) do
(when (eq value (image-value-of sb))
(select-view sb)))
))))
|#
(defun map-with-lhs-matrix (value mat)
; the lhs matrix
;
; | singular lightness value | min lightness | max lightness |
; | singular hue value | min hue | max hue |
; | saturation value | min . max image-value | lightness, hue, or both |
;
(let* ((min-value (car (q::eref mat 2 1)))
(max-value (cdr (q::eref mat 2 1)))
(val (/ (- value min-value) (- max-value min-value)))
)
(case (q::eref mat 2 2)
(:lightness
(let* ((hue (if (q::eref mat 1 0) (mod (q::eref mat 1 0) 360)))
(low-light (q::eref mat 0 1))
(hi-light (q::eref mat 0 2))
(light (+ low-light (* val (- hi-light low-light))))
)
(apply #'wb::make-color (wb::lhs_to_rgb light hue (q::eref mat 2 0)))
))
(:hue
(let* ((light (q::eref mat 0 0))
(low-hue (q::eref mat 1 1))
(hi-hue (q::eref mat 1 2))
(hue (mod (+ low-hue (* val (- hi-hue low-hue))) 360))
)
(apply #'wb::make-color (wb::lhs_to_rgb light hue (q::eref mat 2 0)))
))
(:both
(let* ((low-light (q::eref mat 0 1))
(hi-light (q::eref mat 0 2))
(light (+ low-light (* val (- hi-light low-light))))
(low-hue (q::eref mat 1 1))
(hi-hue (q::eref mat 1 2))
(hue (mod (+ low-hue (* val (- hi-hue low-hue))) 360))
)
(apply #'wb::make-color (wb::lhs_to_rgb light hue (q::eref mat 2 0)))
))
)
))
(defmethod set-draw-style :around ((self imagel) (slot-name (eql :color)) val &key)
;val shouldn't be a colour (an integer), for example use :map if you want to
;use the lhs map matrix of the parent image
(if (find-parent self)
(let* ((parent (find-parent self))
(mat (image-colour-map-of parent))
(image-value (elt (z-coords-of parent
:cases (list (viewed-object-of self))) 0)))
(if (wb::colorp val) ;change colour to something appropriate for an image
(let ((default-mat (qk::sel mat))
)
(case (q::eref mat 2 2)
(:lightness
(setf (q::eref default-mat 1 0) (wb::hue-of val))
)
(:hue
(setf (q::eref default-mat 1 1) (- (wb::hue-of val) 20))
(setf (q::eref default-mat 1 2) (+ (wb::hue-of val) 20))
)
(:both
(setf (q::eref default-mat 1 1) (- (wb::hue-of val) 20))
(setf (q::eref default-mat 1 2) (+ (wb::hue-of val) 20))
)
)
(set-draw-style (drawing-style-of self) :color
(map-with-lhs-matrix
image-value default-mat))
)
(set-draw-style (drawing-style-of self) :color
(map-with-lhs-matrix
image-value mat))))
(call-next-method)))
(defmethod set-draw-style :around ((self imagel) (slot-name (eql :highlight-color)) val
&key)
;val shouldn't be a colour (an integer), for example use :map if you want to
;use the lhs map matrix of the parent image
(if (find-parent self)
(let* ((parent (find-parent self))
(mat (image-colour-map-of parent))
(image-value (elt (z-coords-of parent
:cases (list (viewed-object-of self))) 0)))
(if (wb::colorp val)
(let ((default-mat (make-array '(3 3)))
)
(setf (q::eref default-mat 2 0) (q::eref mat 2 0))
(setf (q::eref default-mat 2 1) (q::eref mat 2 1))
(case (q::eref mat 2 2)
(:lightness
(setf (q::eref default-mat 2 2) :lightness)
(setf (q::eref default-mat 0 1) (q::eref mat 0 1))
(setf (q::eref default-mat 0 2) (q::eref mat 0 2))
(setf (q::eref default-mat 1 0) (wb::hue-of val))
)
(:hue
(setf (q::eref default-mat 2 2) :hue)
(setf (q::eref default-mat 0 0) (q::eref mat 0 0))
(setf (q::eref default-mat 1 1) (- (wb::hue-of val) 15))
(setf (q::eref default-mat 1 2) (+ (wb::hue-of val) 15))
)
(:both
(setf (q::eref default-mat 0 1) (q::eref mat 0 1))
(setf (q::eref default-mat 0 2) (q::eref mat 0 2))
(setf (q::eref default-mat 1 1) (- (wb::hue-of val) 10))
(setf (q::eref default-mat 1 2) (+ (wb::hue-of val) 10))
)
)
(set-draw-style (drawing-style-of self) :highlight-color
(map-with-lhs-matrix
image-value default-mat))
)
(set-draw-style (drawing-style-of self) :highlight-color
(map-with-lhs-matrix
image-value mat)))
(call-next-method))))
| 13,470 | Common Lisp | .l | 304 | 33.819079 | 92 | 0.523722 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 96f78a47d66418e6b2f1a0142f5f88f02fc7a1da9d5111632b3b151182ca8b96 | 33,765 | [
-1
] |
33,766 | projection-trace.lsp | rwoldford_Quail/source/statistics/stat-graphics/projection-trace.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; projection-trace.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1990 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1991.
;;;
;;;
;;;----------------------------------------------------------------------------
;;;
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(projection-trace prompt-projection-trace)))
(defun projection-trace (&rest keyword-args
&key data
(viewed-objects (list-cases data))
(domain '(0.0 1.0))
(projection-fun :andrews)
(title NIL)
(bottom-label "Projection domain")
(left-label "Projected value")
n-ordinates (nlines 100)
&allow-other-keys)
"Produces a projection trace for the data set specified by ~
the keyword argument data. ~
The projection vector is specified by the value of the keyword ~
projection-fun. Currently supported projection-funs are :andrews, :tukey, ~
:parallel-coordinates, and a user-defined function. ~
If user supplies a function it is applied to each case in the ~
dataset, data, to return a function for that case."
(unless data (setf data (choose-dataset)))
(unless (typep data 'matrix)
(quail-error "Sorry the data must be given as a matrix, not as ~
~s" data))
(let*
((dims (dimensions-of data))
(n (or (first dims) 1))
(p (or (second dims) 1))
proj-vector fun-maker)
(unless (= n (length viewed-objects))
(quail-error "Number of viewed-objects is ~s /= ~s, the number of data points!"
(length viewed-objects) n))
(if (functionp projection-fun)
;; The user supplied function is to be used.
(setf fun-maker projection-fun)
;; else use one of our built in projection-funs
(if
(null
(case projection-fun
(:andrews
;; Set up the original Andrews plot.
(setf proj-vector
(cons (/ 1.0 (sqrt 2.0))
(loop for i from 2 to p collect
(if (evenp i)
`(sin (* pi t_i , i))
`(cos (* pi t_i , (- i 1)))))))
(setf fun-maker
#'(lambda (x)
`#'(lambda (t_i)
(declare (special pi))
(.* (tp (list ,@proj-vector )) ,x))))
(if (null title) (setf title "Andrews function plot")))
(:tukey
;; Set up J.W. Tukey's suggested modification.
(setf proj-vector
(loop for i from 1 to p collect
`(cos (* t_i 2.0 pi (sqrt , i)))))
(setf fun-maker
#'(lambda (x)
`#'(lambda (t_i)
(declare (special pi))
(let ((p-vector (list ,@proj-vector )))
(/ (.* (tp p-vector) ,x)
(sqrt (.* (tp p-vector) p-vector)))))))
(if (null title) (setf title "Tukey's function plot")))
(:parallel-coordinates
;; Set up a parallel coordinate plot.
(let (mins );;maxs)
(setf mins (reduce-slices #'min data :slices 0 ))
;;(setf maxs (reduce-slices #'max data :slices 0 ))
(setf data (- data mins))
(setf proj-vector
(loop for i from 1 to p collect
`(cos (* t_i 2.0 pi (sqrt , i)))))
(setf fun-maker
#'(lambda (x)
`#'(lambda (t_i)
(declare (special pi))
(let ((p-vector (list ,@proj-vector )))
(/ (.* (tp p-vector) ,x)
(sqrt (.* (tp p-vector) p-vector)))))))
(if (null title) (setf title "Parallel coordinate plot"))))))
(quail-error "Projection-trace of projection-fun ~s is unknown"
projection-fun)))
(if (null n-ordinates)
(setf n-ordinates nlines))
(let* ((vec (ref data 0))
(the-plot
(apply
#'function-plot
:nlines n-ordinates
:left-label (label :text left-label :orientation :vertical)
:bottom-label (label :text bottom-label)
:title title
:domain domain
:axis :x
:function
(eval (funcall fun-maker vec))
:viewed-object (first viewed-objects)
keyword-args)))
(when (> n 1)
(setf (viewed-object-of the-plot) data)
(loop for i from 1 to (- n 1)
as vo in (rest viewed-objects)
do
(let ((vec (ref data i)))
(add-function (interior-view-of the-plot)
:function
(eval (funcall fun-maker vec))
:viewed-object vo
:nlines n-ordinates
))))
(loop for v in (interior-views-of the-plot) do
(setf (vw::linkable-view-p v) t))
(if (eq projection-fun :parallel-coordinates)
(dotimes (i (choose p 2))
(add-line (interior-view-of the-plot)
:orientation :vertical :intercept i))))))
(defun prompt-projection-trace (fn &key data vars cases &allow-other-keys)
(let* ((sel-plots (top-views)))
(setq data (or data (selected-dataset sel-plots) (choose-dataset)))
(setq cases (or cases (or (list-plot-cases sel-plots :highlit? t)
(list-plot-cases sel-plots)))))
(multiple-value-setq (data cases vars)
(prompt-plot-args data cases vars))
(let ((new-data data)
(ids nil) new-cases new-values
(variates (list-variates data)))
(if (eql vars :prompt)
(setq vars (choose-some-variables data 2)))
(setq vars (or vars variates))
(loop for c in (or cases (list-cases data))
for vals = (value-of c vars :vars variates)
when (every #'numberp vals)
collect c into cases-loc and
collect vals into values-loc
and collect (identifier-of c) into ids-loc
finally (setq new-cases cases-loc new-values values-loc ids ids-loc))
(setq new-data (array new-values))
(dataset new-data :identifiers ids :variates vars :save? nil)
(q::projection-trace
:projection-fun fn
:data new-data
:viewed-objects new-cases
:domain
(loop for l in
(wb::collect-input
(list (cons "from" "0.0")
(cons "to" "1.0")))
collect
(eval (read-from-string (cdr l))))
:nlines
(wb:prompt-user
:type 'number
:read-type :eval
:prompt-string
"Number of line segments to use to plot the ~
each function."
:initial-string "100")
:left-view t :bottom-view t
)))
| 7,822 | Common Lisp | .l | 177 | 29.237288 | 109 | 0.467441 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 1151205d48a2f10f02523dc95bd298292e28441f4b85b2449dd4a2cbe8d0f5bc | 33,766 | [
-1
] |
33,767 | hue-light-view.lsp | rwoldford_Quail/source/statistics/stat-graphics/hue-light-view.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; hue-light-view.lsp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;;
;;; This file is part of the Views system, a toolkit for interactive statistical graphics.
;;;
;;;
;;; Authors: N. Wiebe 1999
;;;
;;;
;;;
;;;----------------------------------------------------------------------------------
(in-package :views)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(user-pick-hue user-pick-hue-light-range)))
;;;----------------------------------------------------------------------------------
(defun user-pick-hue ()
; a user-pick-hue wheel
(let* ((size 300)
(x-centre (truncate size 2))
(y-centre (- x-centre (truncate size 10)))
(radius (truncate size 3))
(arc-angle 1)
(lightness 0.5)
(saturation 1)
(indent 25)
(color-model :double-hexcone)
(text (text-view :text "Click on hue:" :draw? nil))
vw hue-angle
text-vp)
(setf vw (make-view-window :left indent :right (+ indent size)
:bottom indent :top (+ indent size)
:title "Hue Wheel"))
(setf text-vp (make-viewport vw 10 100 (- size 50) (- size 30)))
(draw-view text :viewport text-vp :draw? t)
(loop for i from 0 to 359 by 1
do
(wb::canvas-draw-filled-arc vw i arc-angle
x-centre y-centre radius radius
:color (apply #'wb::make-color
(wb::lhs_to_rgb lightness i saturation
:model color-model))))
(loop until (wb::mouse-down-p))
(when (wb::mouse-down-p)
(let* ((mouse-pos (wb::mouse-position vw))
(x (- (wb::position-x mouse-pos) x-centre))
(y (- (wb::position-y mouse-pos) y-centre))
)
(cond
((> (+ (q::sqr x) (q::sqr y)) (q::sqr radius))
(setf hue-angle nil))
((= 0 x)
(setf hue-angle (if (>= y 0) 90 270)))
((and (> x 0) (>= y 0))
(setf hue-angle (* (/ (atan (/ y x)) pi) 180)))
((and (< x 0) (>= y 0))
(setf hue-angle (+ 180 (* (/ (atan (/ y x)) pi) 180))))
((and (< x 0) (< y 0))
(setf hue-angle (+ 180 (* (/ (atan (/ y x)) pi) 180))))
((and (> x 0) (< y 0))
(setf hue-angle (+ 360 (* (/ (atan (/ y x)) pi) 180))))
)))
(sleep 0.5)
(wb::close-canvas vw)
hue-angle))
(defun user-pick-hue-light-range (self slot &key
(prompt-user-string
"Pick Hue and/or Lightness Range"))
;slot is a 3x3 matrix in self [see map-with-lhs-matrix for details]
(let* ((width (min 450 (floor (wb::screen-width) 2)))
(height (min 350 (floor (wb::screen-height) 2)))
(left (if (<= (+ width (wb::screen-mouse-x) 20)
(wb::screen-width))
(wb::screen-mouse-x)
width))
(bottom (if (<= (+ height (wb::screen-mouse-y) 20) (wb::screen-height))
(wb::screen-mouse-y)
height))
(lhs-matrix (eval `(,slot ,self)))
(light (or (q::eref lhs-matrix 0 0) 0.5))
(light-min (or (q::eref lhs-matrix 0 1) 0.05))
(light-max (or (q::eref lhs-matrix 0 2) 0.95))
(hue (or (q::eref lhs-matrix 1 0) nil))
(hue-min (or (q::eref lhs-matrix 1 1) 0))
(hue-max (or (q::eref lhs-matrix 1 2) 720))
(empty1 (text-view :text "" :draw? NIL))
(empty2 (text-view :text "" :draw? NIL))
(keyword-args nil)
(title (text-view :text prompt-user-string :draw? nil))
(hue-toggle (make-instance 'radio-button :draw? nil))
(lightness-toggle (make-instance 'radio-button :draw? nil))
(hue-lightness-toggle (make-instance 'radio-button :draw? nil))
(hue-text (text-view :text "By Hue?" :draw? nil))
(lightness-text (text-view :text "By Lightness?" :draw? nil))
(hue-lightness-text (text-view :text "By Hue and Lightness?" :draw? nil))
(hue-slider-text (text-view :text (format NIL "Hue Range:") :draw? nil))
(lightness-slider-text (text-view :text (format NIL "Lightness Range:") :draw? nil))
;(color-model-button (make-instance 'control-button :text "triangle" :draw? nil))
(color-model :triangle)
(hue-slider (make-instance 'hue-range-slider
:orientation :horizontal
:min 0 :max 720 :low-level hue-min
:high-level hue-max :draw? nil
:box? t :lightness light :color-model color-model
))
(lightness-slider (make-instance 'lightness-range-slider
:orientation :horizontal
:min 0 :max 720 :low-level (* 720 light-min)
:high-level (* 720 light-max) :draw? nil
:box? t :hue (if hue (mod hue 360)) :color-model color-model
))
(lightness-level-text (text-view :text (format NIL "Lightness Level:") :draw? nil))
(lightness-level-slider (make-instance 'needle-slider :orientation :vertical
:min 0 :max 1 :needle-size 16
:level light :box? t))
(help-button (control-button :text "Help" :draw? nil))
(apply-button (control-button :text "Apply" :draw? nil))
(done-button (control-button :text "Done" :draw? nil))
(red-chip (make-instance 'logical-widget :color wb::*red-color*))
(yellow-chip (make-instance 'logical-widget :color wb::*yellow-color*))
(green-chip (make-instance 'logical-widget :color wb::*green-color*))
(cyan-chip (make-instance 'logical-widget :color wb::*cyan-color*))
(blue-chip (make-instance 'logical-widget :color wb::*blue-color*))
(magenta-chip (make-instance 'logical-widget :color wb::*magenta-color*))
(purple-chip (make-instance 'logical-widget :color wb::*purple-color*))
(orange-chip (make-instance 'logical-widget :color wb::*orange-color*))
(gray-chip (make-instance 'logical-widget :color wb::*gray-color*))
(other-chip (control-button :text "Other" :button-color wb::*white-color*))
(colour-chip-list (list gray-chip magenta-chip red-chip orange-chip yellow-chip
green-chip cyan-chip blue-chip purple-chip))
(hue-choice-toggles (apply #'grid-layout :ncols 5
:subviews
(concatenate 'list colour-chip-list (list other-chip))
:box-views? nil :gap-x .05 :gap-y .05
:viewed-object self
:draw? NIL
keyword-args))
(hue-choice-text (text-view :text (format NIL "Hue Choice:") :draw? nil))
(text1-region (make-region 05 28 63 70))
(object1-region (make-region 05 80 40 63))
(text2-region (make-region 05 28 28 35))
(object2a-region (make-region 05 80 05 28))
(object2b-region (make-region 29 39 05 35))
text1 object1 text2 object2
layout highlight-by vw vp)
(setf layout
(apply #'view-layout
:viewed-object nil
:draw? nil
:subviews
(list empty1
title
lightness-toggle lightness-text
hue-toggle hue-text
hue-lightness-toggle hue-lightness-text
;color-model-button
help-button apply-button done-button
empty2)
:positions
'((00 00 00 00) ;;empty1
(03 97 87 97) ;;title
(03 13 77 87) ;;lightness-toggle
(15 30 77 87) ;;lightness-text
(32 42 77 87) ;;hue-toggle
(44 54 77 87) ;;hue-text
(56 66 77 87) ;;hue-lightness-toggle
(68 97 77 87) ;;hue-lightness-text
;(75 97 68 78) ;;color-model-button
(85 97 50 60) ;;help-button
(85 97 35 45) ;;apply-button
(85 97 05 15) ;;done-button
(100 100 100 100)) ;;empty2
keyword-args))
(setf (left-fn-of red-chip)
#'(lambda (self)
(declare (ignore self))
(if (not (logical-value-of red-chip))
(progn
(loop for chip in colour-chip-list do
(setf (logical-value-of chip) nil)
(draw-view chip :viewport (viewport-of chip) :erase? T))
(setf (logical-value-of red-chip) t)
(draw-view red-chip :viewport (viewport-of red-chip) :erase? T)
(setf (slider-hue-of lightness-slider) (wb::hue-of wb::*red-color*))
(draw-view lightness-slider :viewport (viewport-of lightness-slider)
:erase? t)
))))
(setf (left-fn-of yellow-chip)
#'(lambda (self)
(declare (ignore self))
(if (not (logical-value-of yellow-chip))
(progn
(loop for chip in colour-chip-list do
(setf (logical-value-of chip) nil)
(draw-view chip :viewport (viewport-of chip) :erase? T))
(setf (logical-value-of yellow-chip) t)
(draw-view yellow-chip :viewport (viewport-of yellow-chip) :erase? T)
(setf (slider-hue-of lightness-slider) (wb::hue-of wb::*yellow-color*))
(draw-view lightness-slider :viewport (viewport-of lightness-slider)
:erase? t)
))))
(setf (left-fn-of green-chip)
#'(lambda (self)
(declare (ignore self))
(if (not (logical-value-of green-chip))
(progn
(loop for chip in colour-chip-list do
(setf (logical-value-of chip) nil)
(draw-view chip :viewport (viewport-of chip) :erase? T))
(setf (logical-value-of green-chip) t)
(draw-view green-chip :viewport (viewport-of green-chip) :erase? T)
(setf (slider-hue-of lightness-slider) (wb::hue-of wb::*green-color*))
(draw-view lightness-slider :viewport (viewport-of lightness-slider)
:erase? t)
))))
(setf (left-fn-of cyan-chip)
#'(lambda (self)
(declare (ignore self))
(if (not (logical-value-of cyan-chip))
(progn
(loop for chip in colour-chip-list do
(setf (logical-value-of chip) nil)
(draw-view chip :viewport (viewport-of chip) :erase? T))
(setf (logical-value-of cyan-chip) t)
(draw-view cyan-chip :viewport (viewport-of cyan-chip) :erase? T)
(setf (slider-hue-of lightness-slider) (wb::hue-of wb::*cyan-color*))
(draw-view lightness-slider :viewport (viewport-of lightness-slider)
:erase? t)
))))
(setf (left-fn-of blue-chip)
#'(lambda (self)
(declare (ignore self))
(if (not (logical-value-of blue-chip))
(progn
(loop for chip in colour-chip-list do
(setf (logical-value-of chip) nil)
(draw-view chip :viewport (viewport-of chip) :erase? T))
(setf (logical-value-of blue-chip) t)
(draw-view blue-chip :viewport (viewport-of blue-chip) :erase? T)
(setf (slider-hue-of lightness-slider) (wb::hue-of wb::*blue-color*))
(draw-view lightness-slider :viewport (viewport-of lightness-slider)
:erase? t)
))))
(setf (left-fn-of magenta-chip)
#'(lambda (self)
(declare (ignore self))
(if (not (logical-value-of magenta-chip))
(progn
(loop for chip in colour-chip-list do
(setf (logical-value-of chip) nil)
(draw-view chip :viewport (viewport-of chip) :erase? T))
(setf (logical-value-of magenta-chip) t)
(draw-view magenta-chip :viewport (viewport-of magenta-chip) :erase? T)
(setf (slider-hue-of lightness-slider) (wb::hue-of wb::*magenta-color*))
(draw-view lightness-slider :viewport (viewport-of lightness-slider)
:erase? t)
))))
(setf (left-fn-of purple-chip)
#'(lambda (self)
(declare (ignore self))
(if (not (logical-value-of purple-chip))
(progn
(loop for chip in colour-chip-list do
(setf (logical-value-of chip) nil)
(draw-view chip :viewport (viewport-of chip) :erase? T))
(setf (logical-value-of purple-chip) t)
(draw-view purple-chip :viewport (viewport-of purple-chip) :erase? T)
(setf (slider-hue-of lightness-slider) (wb::hue-of wb::*purple-color*))
(draw-view lightness-slider :viewport (viewport-of lightness-slider)
:erase? t)
))))
(setf (left-fn-of orange-chip)
#'(lambda (self)
(declare (ignore self))
(if (not (logical-value-of orange-chip))
(progn
(loop for chip in colour-chip-list do
(setf (logical-value-of chip) nil)
(draw-view chip :viewport (viewport-of chip) :erase? T))
(setf (logical-value-of orange-chip) t)
(draw-view orange-chip :viewport (viewport-of orange-chip) :erase? T)
(setf (slider-hue-of lightness-slider) (wb::hue-of wb::*orange-color*))
(draw-view lightness-slider :viewport (viewport-of lightness-slider)
:erase? t)
))))
(setf (left-fn-of gray-chip)
#'(lambda (self)
(declare (ignore self))
(if (not (logical-value-of gray-chip))
(progn
(loop for chip in colour-chip-list do
(setf (logical-value-of chip) nil)
(draw-view chip :viewport (viewport-of chip) :erase? T))
(setf (logical-value-of gray-chip) t)
(draw-view gray-chip :viewport (viewport-of gray-chip) :erase? T)
(setf (slider-hue-of lightness-slider) (wb::hue-of wb::*gray-color*))
(draw-view lightness-slider :viewport (viewport-of lightness-slider)
:erase? t)
))))
(setf (left-fn-of other-chip)
#'(lambda ()
(let ((hue (user-pick-hue))
;(colour (wb::user-pick-color)) ;temporary
)
(loop for chip in colour-chip-list do
(setf (logical-value-of chip) nil)
(draw-view chip :viewport (viewport-of chip) :erase? T))
;(setf (slider-hue-of lightness-slider) (wb::hue-of colour))
(setf (slider-hue-of lightness-slider) hue)
(draw-view lightness-slider :viewport (viewport-of lightness-slider)
:erase? t)
)))
(setf (continuous-action-fn-of lightness-level-slider)
#'(lambda()
(setf (slider-lightness-of hue-slider)
(slider-level-of lightness-level-slider))
(draw-view hue-slider :viewport (viewport-of hue-slider) :erase? t)))
(setf (left-fn-of lightness-toggle)
#'(lambda (self)
(declare (ignore self))
(if (not (logical-value-of lightness-toggle))
(progn
(setf (viewed-object-of lightness-toggle) t)
(if (logical-value-of hue-toggle)
(progn (setf (viewed-object-of hue-toggle) nil)
(draw-view hue-toggle :viewport
(viewport-of hue-toggle) :erase? T)))
(if (logical-value-of hue-lightness-toggle)
(progn (setf (viewed-object-of hue-lightness-toggle) nil)
(draw-view hue-lightness-toggle :viewport
(viewport-of hue-lightness-toggle) :erase? T)))
(draw-view lightness-toggle :viewport (viewport-of lightness-toggle)
:erase? T)
(sleep 1)
(erase-view layout :viewport vp)
(if text1 (delete-subview layout text1))
(if object1 (delete-subview layout object1))
(if text2 (delete-subview layout text2))
(if object2 (delete-subview layout object2))
(setf text1 lightness-slider-text)
(setf object1 lightness-slider)
(setf text2 hue-choice-text)
(setf object2 hue-choice-toggles)
(add-subview layout text1 text1-region)
(add-subview layout object1 object1-region)
(add-subview layout text2 text2-region)
(add-subview layout object2 object2a-region)
(setf highlight-by :lightness)
(draw-view layout :viewport vp)
))))
(setf (left-fn-of hue-toggle)
#'(lambda (self)
(declare (ignore self))
(if (not (logical-value-of hue-toggle))
(progn
(setf (viewed-object-of hue-toggle) t)
(if (logical-value-of lightness-toggle)
(progn (setf (viewed-object-of lightness-toggle) nil)
(draw-view lightness-toggle :viewport
(viewport-of lightness-toggle) :erase? T)))
(if (logical-value-of hue-lightness-toggle)
(progn (setf (viewed-object-of hue-lightness-toggle) nil)
(draw-view hue-lightness-toggle :viewport
(viewport-of hue-lightness-toggle) :erase? T)))
(draw-view hue-toggle :viewport (viewport-of hue-toggle) :erase? T)
(sleep 1)
(erase-view layout :viewport vp)
(if text1 (delete-subview layout text1))
(if object1 (delete-subview layout object1))
(if text2 (delete-subview layout text2))
(if object2 (delete-subview layout object2))
(setf text1 hue-slider-text)
(setf object1 hue-slider)
(setf text2 lightness-level-text)
(setf object2 lightness-level-slider)
(add-subview layout text1 text1-region)
(add-subview layout object1 object1-region)
(add-subview layout text2 text2-region)
(add-subview layout object2 object2b-region)
(setf highlight-by :hue)
(draw-view layout :viewport vp)
))))
(setf (left-fn-of hue-lightness-toggle)
#'(lambda (self)
(declare (ignore self))
(if (not (logical-value-of hue-lightness-toggle))
(progn
(setf (viewed-object-of hue-lightness-toggle) t)
(if (logical-value-of hue-lightness-toggle)
(progn (if (logical-value-of hue-toggle)
(progn (setf (viewed-object-of hue-toggle) nil)
(draw-view hue-toggle :viewport
(viewport-of hue-toggle) :erase? T)))
(if (logical-value-of lightness-toggle)
(progn (setf (viewed-object-of lightness-toggle) nil)
(draw-view lightness-toggle :viewport
(viewport-of lightness-toggle)
:erase? T)))))
(draw-view hue-lightness-toggle :viewport
(viewport-of hue-lightness-toggle) :erase? T)
(sleep 1)
(erase-view layout :viewport vp)
(if text1 (delete-subview layout text1))
(if object1 (delete-subview layout object1))
(if text2 (delete-subview layout text2))
(if object2 (delete-subview layout object2))
(setf text1 hue-slider-text)
(setf object1 hue-slider)
(setf text2 lightness-slider-text)
(setf object2 lightness-slider)
(add-subview layout text1 text1-region)
(add-subview layout object1 object1-region)
(add-subview layout text2 text2-region)
(add-subview layout object2 object2a-region)
(setf highlight-by :both)
(setf (slider-lightness-of hue-slider) 0.5)
(setf (slider-hue-of lightness-slider) nil)
(draw-view layout :viewport vp)
(setf (slider-lightness-of hue-slider) light)
(setf (slider-hue-of lightness-slider) hue)
))))
#|
(setf (left-fn-of color-model-button)
#'(lambda ()
(cond
((equal "triangle" (text-of color-model-button))
(setf (text-of color-model-button) "hexcone" color-model :hexcone))
((equal "hexcone" (text-of color-model-button))
(setf (text-of color-model-button) "double-hexcone"
color-model :double-hexcone))
((equal "double-hexcone" (text-of color-model-button))
(setf (text-of color-model-button) "triangle" color-model :triangle)))
(erase-view color-model-button :viewport (viewport-of color-model-button))
(draw-view color-model-button
:viewport (viewport-of color-model-button) :draw? t)
(setf (color-model-of hue-slider) color-model
(color-model-of lightness-slider) color-model)
(draw-view object1 :viewport (viewport-of object1) :erase? t)
(draw-view object2 :viewport (viewport-of object2) :erase? t)
))
|#
(setf (left-fn-of help-button)
#'(lambda ()
(let ((lightness-help (format NIL "To increase or decrease the range of ~%
lightness, click and drag the ends of the ~%
lightness slider in the left or right ~%
directions. ~%To change the singular hue ~%
value of the lightness range, click on one ~%
of the color chips. ~%The other chip ~%
gives the choice of any hue from the hue ~%
wheel. ~%A hue selection will immediately ~%
modify the colours in the lightness ~%
slider."))
(hue-help (format NIL "To increase or decrease the range of hue, click ~%
and drag the ends of the slider in the left or ~%
right directions. ~%To change the singular ~%
lightness level of the hue range, move the ~%
lightness slider up and down. ~%A change in ~%
lightness will immediately modify the colours ~%
in the hue slider."))
(hue-lightness-help (format NIL "To increase or decrease the range of ~%
hue, click and drag the ends of the ~%
hue slider in the left or right ~%
directions. ~%To increase or decrease ~%
the range of lightness, click and drag ~%
the ends of the lightness slider in ~%
the left or right directions.")))
(inform-user (case highlight-by
(:hue hue-help)
(:lightness lightness-help)
(:both hue-lightness-help)
))
)))
(setf (left-fn-of apply-button)
#'(lambda ()
(let ((mat (qk::sel (eval `(,slot ,self)))))
(case highlight-by
(:hue
(let ((low-hue (slider-low-level-of hue-slider))
(hi-hue (slider-high-level-of hue-slider))
(lightness (slider-lightness-of hue-slider))
)
(setf (q::eref mat 1 1) low-hue)
(setf (q::eref mat 1 2) hi-hue)
(setf (q::eref mat 0 0) lightness)
(setf (q::eref mat 2 2) :hue)
))
(:lightness
(let* ((base-one (- (max-level lightness-slider)
(min-level lightness-slider)))
(low-light (/ (slider-low-level-of lightness-slider) base-one))
(hi-light (/ (slider-high-level-of lightness-slider) base-one))
(hue (slider-hue-of lightness-slider))
)
(setf (q::eref mat 0 1) low-light)
(setf (q::eref mat 0 2) hi-light)
(setf (q::eref mat 1 0) hue)
(setf (q::eref mat 2 2) :lightness)
))
(:both
(let* ((low-hue (slider-low-level-of hue-slider))
(hi-hue (slider-high-level-of hue-slider))
(base-one (- (max-level lightness-slider)
(min-level lightness-slider)))
(low-light (/ (slider-low-level-of lightness-slider) base-one))
(hi-light (/ (slider-high-level-of lightness-slider) base-one))
)
(setf (q::eref mat 1 1) low-hue)
(setf (q::eref mat 1 2) hi-hue)
(setf (q::eref mat 0 1) low-light)
(setf (q::eref mat 0 2) hi-light)
(setf (q::eref mat 2 2) :both)
)))
(eval `(setf (,slot ,self) ,mat))
)))
(setf (left-fn-of done-button) ;window closes
#'(lambda ()
(sleep 0.5)
(wb::close-canvas vw)
))
(setf vw (make-view-window :left left :right (+ left width)
:bottom bottom :top (+ bottom height)
:title prompt-user-string))
(setf vp (make-viewport vw 0 1))
(draw-view layout :viewport vp :draw? T)
(funcall (left-fn-of lightness-toggle) lightness-toggle)
))
| 29,853 | Common Lisp | .l | 532 | 35.304511 | 119 | 0.463221 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | da5df3cac02500cca794faeddfe3af66ab0c039a62ece8c50233f095f90e8236 | 33,767 | [
-1
] |
33,768 | sweep.lsp | rwoldford_Quail/source/statistics/basic-statistics/sweep.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; sweep.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (C) 1994 Statistical Computing Laboratory, University Of Waterloo
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1994
;;;
;;;
;;;--------------------------------------------------------------------------------
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute)
(export '(sweep)))
(defun sweep (fun ref-object
&key
(slices NIL)
(order :row)
(copy? NIL)
(broom #'-))
"Sweeps the result of applying fun from each slice of ref-object using ~
the function broom. ~
This is done by calling the function fun on each slice to get a result ~
for that slice. Then that slice is replaced by the result of ~
calling broom on slice and result. an on subtracting the ~
the result from that slice. ~
Returns the swept ref-object, or if copy? is non-NIL the swept copy of ~
ref-object and a list of the values swept from each slice. ~
(:required ~
(:arg fun A unary function that can be applied to an arbitrary slice of ~
a ref-object.) ~
(:arg ref-object The refable object whose slices will be swept.) ~
)~
(:key ~
(:arg slices NIL ~
The integer or list of fixed dimensions that identifies a slice.~
For example if slices is 0 then a slice is defined to be the set of all ~
elements of a ref-object having a common value of the zeroth index. ~
There will be as many slices as the size of the zeroth dimension of the ~
ref-object. ~
Similarly, if slices is '(0 1) then a slice of a ref-object ~
is the set of all elements ~
having common zeroth and first index and there will be as many slices ~
as there are pairs of zeroth and first indices. ~
If NIL then the whole of the ref-object is taken to be the slice. ~
Slices may also be the keyword :elements in which case the elements ~
are accessed directly as opposed to a ref of them.) ~
(:arg order :row The order in which iteration is to take place over ~
the slices.) ~
(:arg copy? NIL A logical flag indicating whether a copy of ref-object is to ~
be swept rather than the original ref-object.) ~
(:arg broom #'- A function of two arguments to be called on the slice and the ~
result.) ~
)~
(:returns Sweep returns two values. The first is either the original or ~
a copy of the ref-object after sweeping. The second is a refable object ~
like ref-object whose elements are the items ~
swept from each slice. The dimensions of this last item are determined to match ~
those of the set of all slices.)~
(:see-also collapse map-slices doslices collect-slices row-major-ops ~
column-major-ops)~
"
(if (eq order :col) (setf order :column))
(when (numberp slices) (setf slices (list slices)))
(if copy? (setf ref-object (sel ref-object)))
(let (swept-value swept-values)
(if (listp slices)
;; then sort out the right size to return
(let ((complement-dims (iseq (length (dimensions-of ref-object)))))
(loop
for i in slices
do (setf complement-dims (remove i complement-dims)))
(setf swept-values
(sel (column-major-ref-slice
ref-object
complement-dims
0)))
)
(setf swept-values
(make-sequence 'list (number-of-slices ref-object slices))))
(cond
((eq order :row)
(loop
for i from 0
to (- (number-of-slices ref-object slices) 1)
as slice = (row-major-ref-slice ref-object slices i)
do
(setf swept-value (funcall fun slice))
(setf (row-major-ref-slice ref-object slices i)
(funcall broom slice swept-value))
(setf (row-major-eref swept-values i) swept-value)
))
((eq order :column)
(loop
for i from 0
to (- (number-of-slices ref-object slices) 1)
as slice = (column-major-ref-slice ref-object slices i)
do
(setf swept-value (funcall fun slice))
(setf (column-major-ref-slice ref-object slices i)
(funcall broom slice swept-value))
(setf (column-major-eref swept-values i) swept-value)
))
(T
(quail-error "Illegal order given to sweep -- ~s ~%~
Order must be one of (:column :row)." order)))
(values ref-object swept-values))
)
| 4,779 | Common Lisp | .l | 112 | 34.9375 | 85 | 0.582455 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 0a7d825b70dbfeb3e654e7785a4201ac4181e931ed5b061d1957027434c5061c | 33,768 | [
-1
] |
33,769 | summary-statistics.lsp | rwoldford_Quail/source/statistics/basic-statistics/summary-statistics.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; summary-statistics.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1990 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1991, 1994.
;;; M.E. Lewis 1991.
;;;
;;;
;;;----------------------------------------------------------------------------
;;;
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute)
(export '(sum mean sd var cov ;;trim
median quartile iqr five-num-sum range)))
(defun sum (ref-thing)
"Returns the sum of all elements of the argument."
(reduce-slices
#'+
ref-thing))
(defgeneric mean (x)
(:documentation "Returns the mean of the argument."))
(defmethod-multi mean ((x (symbol number list array ref-array)))
(/ (sum x) (number-of-elements x)))
#|
(defun trim (x &optional (fraction 0.0))
"Returns two values: x trimmed on each end ~
by half the value of the optional argument fraction, ~
and the leftover part of x. ~
The optional argument should be a non-negative fraction < 1.0 ."
(cond
((= fraction 0.0) x)
((and (> fraction 0.0)
(< fraction 1.0))
(let* ((s-x (sort x #'<= :copy? T)) ;<---- wasteful. need a function that pushes
(n (number-of-elements x)) ; the highest and lowest numbers to either end
(lower-indexes
(loop for i from 0 to (- (floor (* n fraction)) 1)
collect i))
(upper-indexes
(loop for i from (- (ceiling (* n (- 1 fraction))) 1) to n
collect i))
(index-list (append lower-indexes upper-indexes)))
(values
(ref s-x (concatenate 'list '(:c) index-list))
(ref s-x index-list))))
((= fraction 1.0) NaN)
((or (< fraction 0.0) (> fraction 1.0))
(quail-error "TRIM: The fraction argument must be between 0.0 ~
and 1.0 inclusively. ~
~s is not"
fraction))))
|#
(defgeneric sd (x)
(:documentation "Returns the standard-deviation of the argument."))
(defmethod-multi sd ((x (symbol number list array ref-array)))
(let ((n-1 (- (number-of-elements x) 1)))
(sqrt (/ (sum (expt (- x (mean x)) 2)) n-1))))
(defmethod sd ((x t))
(sqrt (var x)))
(defgeneric var (x)
(:documentation "Returns the variance of the argument."))
(defmethod-multi var ((x (symbol number list array ref-array)))
(let ((n-1 (- (number-of-elements x) 1)))
(/ (sum (expt (- x (mean x)) 2)) n-1)))
(defgeneric cov (x)
(:documentation "Returns the covariance of the argument."))
(defmethod cov ((x matrix))
(let* ((diff (sweep #'mean x :slices 1 :copy? T)))
(/ (.* (tp diff) diff)
(- (nrows x) 1))))
;;;
;;;
;;; Other functions / methods:
;;;
;;; median (x)
;;; quartiles (x)
;;; five-num (x) i.e. (min q1 med q3 max) or some more bizarre Tukeyism
;;;
;;; cov (x) x - a matrix ... ideally returns a symmetric-matrix or a number
;;; and then cor (x) for correlation
;;;
(defgeneric quartile (thing &optional which)
(:documentation
"Returns the quartile of the argument. Which quartile ~
depends on the value of the optional argument which.~
(:optional (:arg which 1 Specifies which quartile 1 2 or 3.))~
(:see-also quantile-at median)~
(:elaboration Default behaviour evaluates the quantile at .25 .5 or .75.)"))
(defmethod quartile ((thing t) &optional (which 1))
"Returns the quartile of the argument. Which quartile ~
depends on the value of the optional argument which.~
(:optional (:arg which 1 Specifies which quartile 1 2 or 3.))~
(:see-also quantile-at median)~
(:elaboration Default behaviour evaluates the quantile at .25 .5 or .75.)"
(if (and (numberp which)
(member which '(1 2 3) :test #'=))
(quantile-at thing (float (/ which 4.0)))
(quail-error "QUARTILE: Which must be one of 1, 2, or 3, not ~s" which)))
(defgeneric median (thing)
(:documentation "Returns the median of the argument.~
(:required (:arg thing Any of a variety of things.)) ~
(:see-also quantile-at quartile) ~
(:elaboration Default behaviour evaluates the quantile at .5.)")
)
(defmethod median ((thing t))
"Returns the median of the argument.~
(:required (:arg thing Any of a variety of things.)) ~
(:see-also quantile-at quartile) ~
(:elaboration Evaluates the quantile at .5.)"
(quantile-at thing 0.5))
(defgeneric iqr (thing)
(:documentation
"Calculates the inter-quartile range of the argument, that is the ~
absolute difference of the third and fourth quartiles. ~
(:see-also quartile range)"))
(defmethod iqr ((thing t))
"Calculates the inter-quartile range of the argument, that is the ~
absolute difference of the third and fourth quartiles. ~
(:see-also quartile range)"
(- (quantile-at thing 0.75)
(quantile-at thing 0.25)))
(defgeneric five-num-sum (thing)
(:documentation
"Calculates the five number summary min quartiles 1 2 and 3 and the max ~
as appropriate for the argument. ~
(:see-also quantile-at) ~
(:elaboration Default calculation is by quantile-at.)"
))
(defmethod five-num-sum ((thing t))
"Calculates the five number summary min quartiles 1 2 and 3 and the max ~
as appropriate for the argument. ~
(:see-also quantile-at) ~
(:elaboration Default calculation is by quantile-at.)"
(quantile-at thing '(0.0 0.25 0.5 0.75 1.0)))
(defgeneric range (thing)
(:documentation
"Calculates the range of thing, that is the ~
absolute difference maximum and minimum values. ~
(:see-also iqr)"))
(defmethod-multi range ((thing (sequence array dimensioned-ref-object)))
"Calculates the range of thing, that is the ~
absolute difference maximum and minimum values. ~
(:see-also iqr)"
(- (max thing) (min thing)))
(defmethod-multi range ((thing prob-measure))
"Calculates the range of thing, that is the ~
absolute difference maximum and minimum values. ~
(:see-also iqr)"
(- (upper-bound-of thing) (lower-bound-of thing)))
| 6,485 | Common Lisp | .l | 156 | 35.461538 | 90 | 0.599295 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 3bb81190eca3bbe64ae9afbdff97ec9432ea2cc801379245a22f2c372ce041ca | 33,769 | [
-1
] |
33,770 | system.lsp | rwoldford_Quail/source/probability/generators/system.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; system.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1991 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1991.
;;;
;;;--------------------------------------------------------------------------------
(in-package :quail-kernel)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(system-generator
*CL-system-random-number-generator*
)))
;;;-------------------------------------------------------------------------------------------
;;;
;;; System defined random number generator. See CLtL for definition
;;; N.B. CLtL allows random to be IMPLEMENTATION DEPENDENT !!!!!!
;;;
;;;-------------------------------------------------------------------------------------------
(defclass system-generator
(random-number-generator)
((random-state :reader random-state-of
:initarg :random-state
:initform (make-random-state t))
(maximum-value :reader maximum-value-of
:initarg :maximum-value
:initform most-positive-fixnum)))
(defmethod next ((generator system-generator))
(setf (current-value-of generator)
(random (maximum-value-of generator)
(random-state-of generator))))
(defmethod max-pseudo-rand-of ((generator system-generator))
(maximum-value-of generator))
(defparameter *CL-system-random-number-generator*
(make-instance 'system-generator)
"The default random number generator used by this Common Lisp implementation.")
| 1,815 | Common Lisp | .l | 41 | 37.536585 | 95 | 0.46954 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | df51124994fe4b78ea2ec2fe6f87c3f376fe4060f947a53da3291125793a1448 | 33,770 | [
-1
] |
33,771 | congruential.lsp | rwoldford_Quail/source/probability/generators/congruential.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; congruential.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1991 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1991.
;;;
;;;--------------------------------------------------------------------------------
(in-package :quail-kernel)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(linear-congruential-generator
multiplicative-generator hull-dobel-gen lewis-goodman-miller-gen
full-periodp
)))
;;;---------------------------------------------------------------------------------------
;;;
;;; Standard linear congruential generator shell. No smarts built in for efficiency.
;;; Best used for classroom demonstrations only.
;;;
;;;---------------------------------------------------------------------------------------
(defclass linear-congruential-generator
(random-number-generator)
((multiplier :reader multiplier-of
:initarg :multiplier)
(modulus :reader modulus-of
:initarg :modulus)
(increment :reader increment-of
:initarg :increment)))
(defmethod next ((generator linear-congruential-generator))
(setf (current-value-of generator)
(mod (+ (increment-of generator)
(* (current-value-of generator)
(multiplier-of generator)))
(modulus-of generator))))
(defmethod max-pseudo-rand-of ((generator linear-congruential-generator))
(modulus-of generator))
(defmethod full-periodp ((g linear-congruential-generator))
(let* ((c (increment-of g))
(a (multiplier-of g))
(m (modulus-of g)))
(if (not (coprimep c m))
(error "Modulus = ~s Increment = ~s ... These must be relatively prime!"
c m))
(if (and (= (mod m 4) 0)
(not (= 1 (mod a 4))))
(error "Since 4 divides the modulus (~s), then the multiplier (~s) must be = 1 mod 4."
m a))
(loop for factor in (factor m) when (not (= 1 (mod a factor))) do
(error "The multiplier (~s) is not = 1 mod ~s and ~s is a prime factor of the modulus ~s"
a factor factor m)
finally (return t))))
;;;----------------------------------------------------------------------------------
;;;
;;; Now some classic generators taken from
;;; Ripley, B.D. (1983) "Computer Generation of Random Variables: A Tutorial"
;;; International Statistical Review, 51, pp. 301-319.
;;;
;;; The generators are named as they were identified by Ripley on page 307.
;;; Note all will be slow since the arithmetic is done with bignums in most
;;; CL implementations.
;;;
;;;----------------------------------------------------------------------------------
;;;----------------------------------------------------------------------------------
;;;
;;; The generator called hull-dobell
;;;
;;; modulus = 2^35
;;; multiplier = 2^7 +1
;;; increment = 1
;;;
;;; References:
;;;
;;; Hull, T.E. & A.R. Dobell (1964) "Mixed congruential random number generation for
;;; binary machines" J. ACM 11, pp. 31-40.
;;;
;;; MacLaren, M.D. & G. Marsaglia (1965) "Uniform random number generators" J.ACM 12,
;;; pp. 83-89.
;;;
;;;----------------------------------------------------------------------------------
(defclass hull-dobell-gen (linear-congruential-generator)
((modulus :reader modulus-of
:initform 34359738368
:allocation :class)
(multiplier :reader multiplier-of
:initform 129
:allocation :class)
(increment :reader increment-of
:initform 1
:allocation :class)))
;;;---------------------------------------------------------------------------------------
;;;
;;; Standard multiplicative generator shell. No smarts built in for efficiency.
;;; Best used for classroom demonstrations only.
;;;
;;;---------------------------------------------------------------------------------------
(defclass multiplicative-generator
(linear-congruential-generator)
((increment :reader increment-of
:initform 0
:allocation :class)))
;;;
;;; Make sure zero never gets to be a seed unless explicitly over-written
;;; via setf after initialization is complete.
;;;
(defmethod initialize-instance :after
((generator multiplicative-generator) &key)
(let ((seed (seed-of generator)))
(if (= seed 0)
(setf (seed-of generator)
(loop until (/= seed 0)
do
(setf seed
(mod (+ 1
(* 2
(get-internal-real-time)
(get-universal-time)))
(modulus-of generator)))
finally (return seed)))))
(qrestart generator))
(defmethod next ((generator multiplicative-generator))
(setf (current-value-of generator)
(mod (* (current-value-of generator)
(multiplier-of generator))
(modulus-of generator))))
;;;----------------------------------------------------------------------------------
;;;
;;; The generator called lewis-goodman-miller after
;;; Lewis, P.A.P., Goodman, A.S. & J.M. Miller (1969) " A pseudo-random number
;;; generator for the System/360" I.B.M. Systems Journal, 8, pp. 136-145.
;;;
;;; modulus = 2^31 - 1 = 2147483647
;;; multiplier = 7^5 = 16807
;;; increment = 0
;;;
;;; Also proposed as a portable standard multiplicative generator
;;; from Park & Miller, 1988, CACM 31, pp. 1192-1201.
;;; We use Park & Miller's algorithm to ensure that no multiplication results
;;; are kept small.
;;;
;;;-----------------------------------------------------------------------------
(defclass lewis-goodman-miller-gen
(multiplicative-generator)
((multiplier :reader multiplier-of
:initform 16807
:allocation :class)
(modulus :reader modulus-of
:initform 2147483647
:allocation :class)))
(defmethod next ((generator lewis-goodman-miller-gen))
(setf (current-value-of generator)
(let* ((y (or (current-value-of generator)
(seed-of generator)))
(gamma-of-y (- (* 16807
(mod y 127773))
(* 2836 (floor y 127773)))))
(if (> gamma-of-y 0)
gamma-of-y
(+ gamma-of-y 2147483647)))))
| 6,941 | Common Lisp | .l | 163 | 34.546012 | 100 | 0.480347 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 551f656677473313b5f3a8913e285085e8acbb800bae6483b4c5f2b610907cfe | 33,771 | [
-1
] |
33,772 | random.lsp | rwoldford_Quail/source/probability/generators/random.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; random.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1991 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1991.
;;;
;;;--------------------------------------------------------------------------------
(in-package :quail-kernel)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(random-number-generator rand seed-of max-pseudo-rand-of qrestart)))
(defclass random-number-generator (quail-object)
((seed :accessor seed-of
:initarg :seed
:initform NIL)
(current-value :accessor current-value-of
:initform NIL)))
(defgeneric rand (generator &optional quantity)
(:documentation
"Return the next pseudo-random number from this generator. ~
If quantity is an integer greater then 1, then a vector containing ~
that meny elements in the pseudo-random sequence is given."))
(defgeneric next (generator)
(:documentation
"Return the next pseudo-random number from this generator."))
(defgeneric qrestart (generator)
(:documentation
"Restarts the pseudo-random-number generator from its initial state."))
(defgeneric max-pseudo-rand-of (generator)
(:documentation
"Restarts the maximum pseudo-random-number that can be possibly generated ~
by this generator."))
;;;----------------------------------------------------------------------------------
;;;
;;; The methods
;;;
;;;----------------------------------------------------------------------------------
(defmethod rand ((generator random-number-generator) &optional (quantity 1))
(if (not (numberp quantity))
(quail-error "Quantity ~s is not a positive integer!" quantity))
(if (> quantity 1)
(let ((result (array nan :dimensions (list quantity))))
(dotimes (i quantity)
(setf (eref result i) (float (next generator))))
result)
(float (next generator))))
(defmethod next ((generator random-number-generator))
(missing-method 'next generator))
(defmethod qrestart ((generator random-number-generator))
(setf (current-value-of generator) (seed-of generator)))
(defmethod max-pseudo-rand-of ((generator random-number-generator))
(missing-method 'max-pseudo-rand-of generator))
(defmethod initialize-instance :after
((generator random-number-generator) &key)
(if (null (seed-of generator))
(setf (seed-of generator)
(mod (* (get-internal-real-time)
(get-universal-time))
(max-pseudo-rand-of generator))))
(qrestart generator))
| 2,833 | Common Lisp | .l | 65 | 37.923077 | 133 | 0.564835 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | d41b4f217d1fdad734ef4c45b3d8c5af537170a08b150312b0442eccd89ba08d | 33,772 | [
-1
] |
33,773 | default.lsp | rwoldford_Quail/source/probability/generators/default.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; default.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1991 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1991.
;;;
;;;--------------------------------------------------------------------------------
(in-package :quail-kernel)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(*default-random-number-generator*)))
;;;--------------------------------------------------------------------------------
;;;
;;; Need a system-wide default generator.
;;; Change this as necessary
;;;
;;;--------------------------------------------------------------------------------
(defparameter *default-random-number-generator*
(make-instance 'lewis-goodman-miller-gen)
"The default random number generator to be used when none is specified.")
| 1,062 | Common Lisp | .l | 25 | 38.6 | 102 | 0.364878 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 6e1b8e60673ca3f75d7d112a51d7e5614bd06eee958764c44d81ce8ebbc7f4aa | 33,773 | [
-1
] |
33,774 | permute.lsp | rwoldford_Quail/source/probability/random/permute.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; permute.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1994 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1994
;;;
;;;
;;;--------------------------------------------------------------------------------
;;;
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(permute permute-object)))
(defun permute (object
&key
(slices :elements)
(copy? nil)
(type :exterior))
"Randomly permutes the elements or slices of object.~
The default is that this is destructive to the original object.~
(:required ~
(:arg object The object whose contents are to be permuted.) ~
)~
(:key ~
(:arg slices :elements ~
The integer or list of fixed dimensions that identifies a slice.~
For example if slices is 0 then a slice is defined to be the set of all ~
elements of a ref-object having a common value of the zeroth index. ~
There will be as many slices as the size of the zeroth dimension of the ~
ref-object. ~
Similarly, if slices is '(0 1) then a slice of a ref-object ~
is the set of all elements ~
having common zeroth and first index and there will be as many slices ~
as there are pairs of zeroth and first indices. ~
If NIL then the whole of the ref-object is taken to be the slice. ~
Slices may also be the keyword :elements in which case the elements ~
are accessed directly as opposed to a ref of them.
In any case the permutation applies over all possible slices.)~
(:arg copy? NIL If non-NIL a copy is first made of object and the ~
the copy is permuted. If NIL, the contents of the original object are ~
destructively rearranged.)~
(:arg type :exterior Two types of random permutation ~
are possible: :interior and :exterior. ~
The interior one permutes the order of ~
the elements within the specified slices.
The exterior one permutes the order of ~
the slices and not the elements within each one.) ~
)~
(:see-also order permute-object random-discrete-uniform random-value) ~
(:elaboration The method of permutation is a simple swapping algorithm based ~
on as many discrete uniforms as there are slices.)~
(:returns The randomly permuted object.)"
(cond
((numberp slices) (setf slices (list slices)))
((and slices (listp slices))
(setf slices (cl:sort (remove-duplicates slices) #'<))))
(permute-object
(if copy? (sel object) object)
slices
type)
)
(defgeneric permute-object (object slices type)
(:documentation
"Randomly permutes the elements or slices of object.~
This is destructive to the original object.~
(:required ~
(:arg object The object whose contents are to be permuted.) ~
(:arg slices :elements ~
The integer or list of fixed dimensions that identifies a slice.~
For example if slices is 0 then a slice is defined to be the set of all ~
elements of a ref-object having a common value of the zeroth index. ~
There will be as many slices as the size of the zeroth dimension of the ~
ref-object. ~
Similarly, if slices is '(0 1) then a slice of a ref-object ~
is the set of all elements ~
having common zeroth and first index and there will be as many slices ~
as there are pairs of zeroth and first indices. ~
If NIL then the whole of the ref-object is taken to be the slice. ~
Slices may also be the keyword :elements in which case the elements ~
are accessed directly as opposed to a ref of them.~
In any case the permutation applies over all possible slices.)~
(:arg type :exterior Two types of random permutation ~
are possible: :interior and :exterior. ~
The interior one permutes the order of ~
the elements within the specified slices. ~
The exterior one permutes the order of ~
the slices and not the elements within each one.) ~
)~
(:elaboration The method of permutation is a simple swapping algorithm based ~
on as many discrete uniforms as there are slices.)~
(:returns The randomly permuted object.)"))
(defmethod permute-object (object
slices
type)
"Missing method for all unclassified cases."
(missing-method 'permute-object
object
slices
type)
)
(defmethod-multi permute-object ((object (symbol number character))
slices
type)
"Returns object since permuting doesn't quite make sense here."
(declare (ignore slices type))
object)
(defmethod-multi permute-object ((object (dimensioned-ref-object sequence array))
(slices T)
(type (eql :interior)))
"Implements the interior sort as an exterior sort for every slice. "
(doslices (slice object slices object)
(permute-object slice :elements :exterior)
)
object)
(defmethod-multi permute-object ((object (dimensioned-ref-object sequence array))
(slices T)
(type (eql :exterior)))
"Implements the exterior sort by simple swapping algorithm."
(with-CL-functions (+ * / - = )
(let ((n-1 (- (number-of-slices object slices) 1))
x
swap)
(do ((i n-1 (- i 1)))
((= i 0))
(setf x (random-discrete-uniform :from 0 :to i))
(setf swap (sel (column-major-ref-slice object slices i)))
(setf (column-major-ref-slice object slices i)
(column-major-ref-slice object slices x))
(setf (column-major-ref-slice object slices x) swap)
)))
object
)
#| Too clever by half
Robson's method stinks
"(:elaboration The method of permutation used depends on the number of slices ~
to be permuted. If this number is small, then the one-pass decoding algorithm ~
of Robson is used. If it is large then a simple swapping algorithm based ~
on as many discrete uniforms as there are slices is used.)~
(:references Devroye, Luc (1986) Non-Uniform Random Variate Generation, ~
Springer-Verlag.) ~
"
(with-CL-functions (+ * / - = floor log)
(let* ((n (number-of-slices object slices))
(log-max (log most-positive-fixnum))
(n-log (* n (log (/ (1+ n) 2.0)))))
;; Test based on Jensen's inequality
(if (< n-log log-max)
;; Then the number of slices is small enough to use the
;; decoding algorithm of Robson.
(let ((x (random-discrete-uniform
:from 1
:to (factorial n)))
z
swap)
(do ((i n (- i 1)))
((= i 1))
(multiple-value-setq (x z) (floor x i))
(setf z (+ z 1))
(setf swap
(sel (column-major-ref-slice object slices (- i 1))))
(setf (column-major-ref-slice object slices (- i 1))
(column-major-ref-slice object slices (- z 1)))
(setf (column-major-ref-slice object slices (- z 1)) swap)
))
;; Else do simple swapping.
(let ((n-1 (- n 1))
x
swap)
(do ((i n-1 (- i 1)))
((= i 0))
(setf x (random-discrete-uniform :from 0 :to i))
(setf swap (sel (column-major-ref-slice object slices i)))
(setf (column-major-ref-slice object slices i)
(column-major-ref-slice object slices x))
(setf (column-major-ref-slice object slices x) swap)
)))
object
))
)
|#
| 8,088 | Common Lisp | .l | 185 | 35.075676 | 91 | 0.592211 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 1c817c4219e3bf230271528ba82b4e23218225b5a185d3615a5ace0b1afd3a42 | 33,774 | [
-1
] |
33,775 | init-dist.lsp | rwoldford_Quail/source/probability/distributions/init-dist.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; init-dist.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1993 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1993
;;;
;;;
;;;--------------------------------------------------------------------------------
;;;
;;; Initialize a bunch of variables
;;;
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(*distributions*)))
(defvar *distributions*
(list
(setf *uniform* (make-instance 'uniform))
(setf *gamma-dist* (make-instance 'gamma-dist :shape 0.5))
(setf *exponential-dist* (make-instance 'exponential-dist))
(setf *chi-squared* (make-instance 'chi-squared :df 1))
(setf *student* (make-instance 'student :df 1))
(setf *gaussian-dist* (make-instance 'gaussian-dist))
(setf *cauchy* (make-instance 'cauchy-dist))
(setf *binomial* (make-instance 'binomial-dist :upper-bound 1 :p 0.5))
(setf *bernoulli* (make-instance 'bernoulli :p 0.5))
(setf *negative-binomial* (make-instance 'negative-binomial
:lower-bound 1 :p 0.5))
(setf *geometric* (make-instance 'geometric :p 0.5))
(setf *hypergeometric* (make-instance
'hypergeometric :total-successes 10
:total-failures 5 :sample-size 7))
(setf *discrete-uniform* (make-instance 'discrete-uniform))
(setf *beta-dist* (make-instance 'beta-dist :shape1 1 :shape2 1))
(setf *poisson* (make-instance 'poisson-dist :mean 1))
(setf *K-dist* (make-instance 'K-dist :df 1))
(setf *F-dist* (make-instance 'F-dist :df-num 1.0 :df-den 1.0))
(setf *pareto* (make-instance 'pareto :shape 1.0))
(setf *weibull* (make-instance 'weibull :shape 1.0))
)
"A collection of instances of selected distributions.")
| 2,326 | Common Lisp | .l | 46 | 38.652174 | 84 | 0.510253 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | ea619920d65d20e2e23bc16dd41c21dd36ec716863baa6c1446d0ba9805eb703 | 33,775 | [
-1
] |
33,776 | show.lsp | rwoldford_Quail/source/probability/distributions/show.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; show.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Copyright (c) Statistical Computing Laboratory
;;; University of Waterloo
;;; Canada.
;;;
;;;
;;; Authors:
;;; R.W. Oldford 1993
;;;
;;;
;;;
;;;----------------------------------------------------------------------------------
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute) (export '(show)))
(defmethod show ((distribution prob-measure) &rest grid-plot-args
&key
(draw? T)
(cdf? T)
(pdf? T)
(color wb::*white-color*)
(title NIL)
(nlines 30)
(from NIL)
(to NIL)
&allow-other-keys)
(unless (numberp from) (setf from (max -5.0 (lower-bound-of distribution))))
(unless (numberp to) (setf to (min 5.0 (upper-bound-of distribution))))
(unless title (setf title (format NIL "The ~s." (class-name (class-of distribution)))))
(let
(the-plot)
(setf
the-plot
(cond
((and pdf? cdf?)
(let*
((pdf
(function-plot
:function
#'(lambda (x) (pdf-at distribution x))
:domain
(list from to)
:nlines nlines
:left-view t :bottom-view t
:left-label "density" :bottom-label "y"
:viewed-object distribution
:title "Density"
:color color
:draw? NIL
:link? T
))
(cdf
(function-plot
:function
#'(lambda (x) (cdf-at distribution x))
:domain
(list from to)
:nlines
nlines
:left-view t :bottom-view t
:left-label "probability" :bottom-label "y"
:viewed-object distribution
:title "Cumulative distribution"
:color color
:draw? NIL
:link? T
)
)
(view-layout (grid-layout :subviews (list pdf cdf)
:nrows 1 :box-views? t
:gap-x 0.1 :gap-y 0.1)))
(apply #'grid-plot :interior-view view-layout :gap-x 0.1 :gap-y 0.1
:title title
:draw? draw?
grid-plot-args)))
(pdf?
(let*
((pdf
(function-plot
:function
#'(lambda (x) (pdf-at distribution x))
:domain
(list from to)
:nlines nlines
:left-view t :bottom-view t
:left-label "density" :bottom-label "y"
:viewed-object distribution
:title "Density"
:color color
:draw? NIL
:link? T
))
(view-layout (grid-layout :subviews (list pdf)
:nrows 1 :box-views? t
:gap-x 0.1 :gap-y 0.1)))
(apply #'grid-plot :interior-view view-layout :gap-x 0.1 :gap-y 0.1
:title title
:draw? draw?
grid-plot-args))
)
(cdf?
(let*
((cdf
(function-plot
:function
#'(lambda (x) (cdf-at distribution x))
:domain
(list from to)
:nlines nlines
:left-view t :bottom-view t
:left-label "probability" :bottom-label "y"
:viewed-object distribution
:title "Cumulative distribution"
:color color
:draw? NIL
:link? T
))
(view-layout (grid-layout :subviews (list cdf)
:nrows 1 :box-views? t
:gap-x 0.1 :gap-y 0.1)))
(apply #'grid-plot :interior-view view-layout :gap-x 0.1 :gap-y 0.1
:title title
:draw? draw?
grid-plot-args))
)
))
(loop for s-v in (sub-views-of (interior-view-of the-plot))
do (draw-view (interior-view-of s-v)
:color color))
)
)
| 4,563 | Common Lisp | .l | 135 | 20.577778 | 91 | 0.401319 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | ff804409d72223e7eda961069df76d6fa83f8fa662ebdb31f02df6b5627ed8ed | 33,776 | [
-1
] |
33,777 | beta.lsp | rwoldford_Quail/source/probability/distributions/beta.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; beta.lisp
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
;;; Copyright (c) 1993 Statistical Computing Laboratory, University of Waterloo
;;;
;;;
;;; Authors:
;;; Stat 440/840 students 1992.
;;; R.W. Oldford 1993
;;;
;;;
;;;--------------------------------------------------------------------------------
;;;
;;; Methods for The Continuous Beta Distribution
;;; Written by John & Garth
;;;
(in-package :quail)
(eval-when (:compile-toplevel :load-toplevel :execute)
(export '(beta-dist density-beta quantile-beta
random-beta dist-beta)))
(defclass beta-dist (continuous-dist)
((shape1 :reader shape1-of
:initarg :shape1)
(shape2 :reader shape2-of
:initarg :shape2)
(1/beta :accessor 1/beta
:documentation "Just a holder of 1/beta(a,b).")
(lower-bound :reader lower-bound-of
:initarg :lower-bound
:initform 0)
(upper-bound :reader upper-bound-of
:initarg :upper-bound
:initform 1)
(gamma1 :accessor gamma1-of
:initarg :gamma1-of
:documentation "A gamma(shape1) distribution for random-values.")
(gamma2 :accessor gamma2-of
:initarg :gamma2-of
:documentation "A gamma(shape2) distribution for random-values."))
(:documentation "The Beta distribution with shape parameters 'shape1' ~
and 'shape2'. ")
)
(defmethod (setf lower-bound-of)
(new-value (self beta-dist))
"Resetting of the lower bound is not allowed."
(when (/= new-value 0)
(quail-error "ERROR: lower-bound-of a beta distribution must be zero, ~
not ~s" new-value)
)
)
(defmethod (setf upper-bound-of)
(new-value (self beta-dist))
"Resetting of the upper bound is not allowed."
(when (/= new-value 1)
(quail-error "ERROR: upper-bound-of a beta distribution must be 1, ~
not ~s" new-value)
)
)
(defmethod (setf shape1-of)
(new-value (self beta-dist))
"Resetting the shape1 of the beta-dist."
(with-CL-functions (= <= exp + -)
(cond
((= new-value (shape1-of self)) new-value)
((<= new-value 0)
(quail-error "Shape1 parameter of a beta must be greater than zero, not~
~s ." new-value))
(T
(setf (shape-of (gamma1-of self)) new-value)
(let ((b (shape2-of self)))
(setf (1/beta self)
(exp (- (log-gamma (+ new-value b))
(log-gamma new-value)
(log-gamma b)))))
(setf (slot-value self 'shape1) new-value)
)
)
)
)
(defmethod (setf shape2-of)
(new-value (self beta-dist))
"Resetting the shape2 of the beta-dist."
(with-CL-functions (= <= exp + -)
(cond
((= new-value (shape2-of self)) new-value)
((<= new-value 0)
(quail-error "Shape2 parameter of a beta must be greater than zero, not~
~s ." new-value))
(T
(setf (shape-of (gamma2-of self)) new-value)
(let ((a (shape1-of self)))
(setf (1/beta self)
(exp (- (log-gamma (+ a new-value))
(log-gamma a)
(log-gamma new-value)))))
(setf (slot-value self 'shape2) new-value)
)
)
)
)
;;;********************************************************************
; THE BETA DISTRIBUTION
;
; B(shape1,shape2) = Gamma(shape1)*Gamma(shape2)/(Gamma(shape1+shape2)
;
; pdf = B(shape1,shape2)^-1 * x^(shape1 - 1)*(1-x)^(shape2 - 1)
;
; cdf: The Incomplete Beta Function
;
; Random Values calculated with thanks to the guys who wrote Gamma
;
;;;**********************************************************************
;;;
;;;
;;; Initialize-instance :after sets up the B(shape1,shape2) for each instance
;;;
(defmethod initialize-instance :after ((distribution beta-dist) &key)
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(inline log-gamma))
(with-CL-functions (+ * / - exp expt sqrt > < =)
(let ((a (shape1-of distribution))
(b (shape2-of distribution)))
(cond
((and (> a 0) (> b 0))
(<- (1/beta distribution)
;;; (/ 1.0 (beta a b))
(exp (- (log-gamma (+ a b))
(log-gamma a)
(log-gamma b))))
(<- (gamma1-of distribution)
(make-instance 'gamma-dist :shape a))
(<- (gamma2-of distribution)
(make-instance 'gamma-dist :shape b))
)
(T
(quail-error "shape1 = ~s and shape2 = ~s must be >0."
a
b))))
))
(defmethod cdf-at ((distribution beta-dist) x)
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(inline incomplete-beta))
(with-CL-functions (+ * / - exp expt sqrt > < =)
(cond ((<= x 0) 0)
((>= x 1) 1)
(T (incomplete-beta (shape1-of distribution) (shape2-of distribution) x))))
)
;;; Pdf-at Calculated Numerically
;;;
(defmethod pdf-at ((distribution beta-dist) (x number))
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
)
(with-CL-functions (+ * / - exp expt sqrt > < =)
(cond ((= 1.0 (shape1-of distribution) (shape2-of distribution))
1.0)
((or (<= x 0) (>= x 1)) 0)
(T (* (1/beta distribution)
(expt x (- (shape1-of distribution) 1))
(expt (- 1 x) (- (shape2-of distribution) 1)))))))
;;;
;;; Random-Value: We all know that Gamma(shape1)/(Gamma(shape2)+Gamma(shape1))
;;; is distributed Beta(shape1,scale)... Soo Thats how we calculate are random values
;;; Notice if shape1 = scale then our random value from gamma1 = gamma2...
;;; this gives us a random value of 1/2 from the beta every time... Not too random
;;; thus the cond.
;;;
(defmethod random-value ((distribution beta-dist) &optional (n 1))
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(inline incomplete-gamma))
(with-CL-functions (+ * / - exp expt sqrt > < = /=)
(let ((g1 (gamma1-of distribution))
(g2 (gamma2-of distribution)))
(if (> n 1)
(array
(loop for i from 1 to n
collect
(let ((u (random-value g1))
(v (random-value g2)))
(/ u (+ u v)))))
(let ((u (random-value g1))
(v (random-value g2)))
(/ u (+ u v)))
)
)
))
(defmethod quantile-at ((distribution beta-dist) (p number) &key (start NIL))
(declare (optimize (speed 3) (safety 0)
(space 0) (compilation-speed 0))
(inline illinois))
(with-CL-functions (+ * / - exp expt sqrt > < = /=)
(let ((alpha (shape1-of distribution))
(beta (shape2-of distribution))
(step (/ (- (upper-bound-of distribution)
(lower-bound-of distribution))
10.0))
bracket-point)
(unless (numberp start)
(let* ((approx-normal (quantile-gaussian p))
(temp1 (/ 1.0 9.0 beta))
(temp2 (+ 1.0 (- temp1) (* approx-normal (sqrt temp1))))
(approx-chi (* 2.0 beta (expt temp2 3)))
(temp3 (+ (* 4.0 alpha) (* 2.0 beta) -2.0)))
(cond
((minusp approx-chi)
(setf start (- 1.0
(expt (* beta (- 1.0 p)
(beta alpha beta))
(/ 1.0 beta)))))
((<= temp3 approx-chi)
(setf start (expt (* alpha p (beta alpha beta))
(/ 1.0 beta))))
(T (setf start (/ (- temp3 approx-chi) (+ temp3 approx-chi)))))))
(flet ((G-fun (x) (- (cdf-at distribution x) p)))
(cond
((minusp (G-fun start))
(setf bracket-point (+ start step))
(loop for i from 0.0 by step
until (plusp (G-fun bracket-point))
do (incf bracket-point step))
(illinois #'G-fun start bracket-point))
((plusp (G-fun start))
(setf bracket-point (- start step))
(loop for i from 0.0 by step
until (minusp (G-fun bracket-point))
do (decf bracket-point step))
(illinois #'G-fun bracket-point start))
(T start))
))))
(defvar *beta-dist*
NIL
"An instance of a beta-dist representing the beta-dist distribution ~
with shape parameters shape1 and shape2. ~
This instance is used by the standard beta-dist functions random-beta, ~
quantile-beta, etc.")
(defun density-beta (x &key (a 1) (b 1))
"Returns the value of a beta-dist density at x. ~
(:required ~
(:arg x The point at which to evaluate the density.)) ~
(:key ~
(:arg a 1 The first shape parameter of the beta-dist distribution.) ~
(:arg b 1 The second shape parameter of the beta-dist distribution.))"
(declare (special *beta-dist*))
(let ((saved-a (shape1-of *beta-dist*))
(saved-b (shape2-of *beta-dist*))
result)
(setf (shape1-of *beta-dist*) a)
(setf (shape2-of *beta-dist*) b)
(setf result (pdf-at *beta-dist* x))
(setf (shape1-of *beta-dist*) saved-a)
(setf (shape2-of *beta-dist*) saved-b)
result
)
)
(defun quantile-beta (p &key (a 1) (b 1))
"Returns the value of a beta-dist quantile at p. ~
(:required ~
(:arg p The probability at which to evaluate the quantile.)) ~
(:key ~
(:arg a 1 The first shape parameter of the beta-dist distribution.) ~
(:arg b 1 The second shape parameter of the beta-dist distribution.))"
(declare (special *beta-dist*))
(let ((saved-a (shape1-of *beta-dist*))
(saved-b (shape2-of *beta-dist*))
result)
(setf (shape1-of *beta-dist*) a)
(setf (shape2-of *beta-dist*) b)
(setf result (quantile-at *beta-dist* p))
(setf (shape1-of *beta-dist*) saved-a)
(setf (shape2-of *beta-dist*) saved-b)
result
)
)
(defun random-beta (&key (n 1) (a 1) (b 1))
"Returns n pseudo-random values from the beta-dist with shape ~
parameters a and b. ~
(:key ~
(:arg n 1 The number of pseudo-random values to return.) ~
(:arg a 1 The first shape parameter of the beta-dist distribution.) ~
(:arg b 1 The second shape parameter of the beta-dist distribution.))
(:returns A vector of n pseudo-random values.)"
(declare (special *beta-dist*))
(let ((saved-a (shape1-of *beta-dist*))
(saved-b (shape2-of *beta-dist*))
result)
(setf (shape1-of *beta-dist*) a)
(setf (shape2-of *beta-dist*) b)
(setf result (random-value *beta-dist* n))
(setf (shape1-of *beta-dist*) saved-a)
(setf (shape2-of *beta-dist*) saved-b)
result
)
)
(defun dist-beta (x &key (a 1)(b 1))
"Calculates and returns the value of the beta distribution function ~
at x. (i.e. Prob(X <= x) .) ~
(:required ~
(:arg x Where to evaluate the cumulative distribution function.)) ~
(:key ~
(:arg a 1 The first shape parameter of the beta-dist distribution.) ~
(:arg b 1 The second shape parameter of the beta-dist distribution.)) "
(declare (special *beta-dist*))
(let ((saved-a (shape1-of *beta-dist*))
(saved-b (shape2-of *beta-dist*))
result)
(setf (shape1-of *beta-dist*) a)
(setf (shape2-of *beta-dist*) b)
(setf result (cdf-at *beta-dist* x))
(setf (shape1-of *beta-dist*) saved-a)
(setf (shape2-of *beta-dist*) saved-b)
result
)
)
| 12,290 | Common Lisp | .l | 320 | 29.671875 | 86 | 0.523686 | rwoldford/Quail | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:43:28 AM (Europe/Amsterdam) | 39afd1f4efc1dd0c4be1723b98e74613065d4a5c044f88678228ee0db4fc7a16 | 33,777 | [
-1
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.