id
int64
0
45.1k
file_name
stringlengths
4
68
file_path
stringlengths
14
193
content
stringlengths
32
9.62M
size
int64
32
9.62M
language
stringclasses
1 value
extension
stringclasses
6 values
total_lines
int64
1
136k
avg_line_length
float64
3
903k
max_line_length
int64
3
4.51M
alphanum_fraction
float64
0
1
repo_name
stringclasses
779 values
repo_stars
int64
0
882
repo_forks
int64
0
108
repo_open_issues
int64
0
90
repo_license
stringclasses
8 values
repo_extraction_date
stringclasses
146 values
sha
stringlengths
64
64
__index_level_0__
int64
0
45.1k
exdup_ids_cmlisp_stkv2
sequencelengths
1
47
11,029
transpose.lisp
mnasoft_math/src/matr/methods/transpose.lisp
;;;; ./src/matr/methods/transpose.lisp (in-package :math/matr) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; transpose (defmethod transpose ((mm <matrix>)) " @b(Пример использования:) @begin[lang=lisp](code) (transpose (matr-new 2 3 '(1 2 3 4 5 6))) => Matr 3х2 [ 1 4 ] [ 2 5 ] [ 3 6 ] @end(code)" (let ((rez (make-instance '<matrix> :dimensions (nreverse (dimensions mm))))) (loop :for i :from 0 :below (rows mm) :do (loop :for j :from 0 :below (cols mm) :do (setf (mref rez j i) (mref mm i j)))) rez)) (defmethod transpose ((mm cons)) "Выполняет транспонирование" (apply #'mapcar #'list mm))
816
Common Lisp
.lisp
22
30.772727
100
0.477212
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
6dcf283221740dae0f509eb452b39b8b31dc331764d59112c81ba59f2d62b2f8
11,029
[ -1 ]
11,030
equivalent.lisp
mnasoft_math/src/matr/methods/equivalent.lisp
;;;; ./src/matr/methods/equivalent.lisp (in-package :math/matr) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; equivalent (defmethod equivalent ((m1 <matrix>) (m2 <matrix>) &key (test #'math/core:semi-equal)) (let ((rez t)) (if (and (= (rows m1) (rows m2)) (= (cols m1) (cols m2))) (loop :for r :from 0 :below (rows m1) :do (loop :for c :from 0 :below (cols m1) :do (setf rez (and rez (funcall test (mref m1 r c ) (mref m2 r c) ))))) (setf rez nil)) rez)) (defmethod equivalent ((a1 array) (a2 array) &key (test #'math/core:semi-equal)) (declare (type (array * (* *)) a1 a2)) (when (not (equal (array-dimensions a1) (array-dimensions a2))) (return-from equivalent nil)) (reduce #'(lambda (el1 el2) (and el1 el2)) (apply #'append (loop :for i :from 0 :below (array-dimension a1 0) :collect (loop :for j :from 0 :below (array-dimension a1 1) :collect (funcall test (aref a1 i j) (aref a2 i j))))) :initial-value t)) (defmethod equivalent ((m1 <matrix>) (a2 array) &key (test #'math/core:semi-equal)) (declare (type (array * (* *)) a2)) (equivalent m1 (make-instance '<matrix> :data a2) :test test)) (defmethod equivalent ((a1 array) (m2 <matrix>) &key (test #'math/core:semi-equal)) (declare (type (array * (* *)) a1)) (equivalent (make-instance '<matrix> :data a1) m2 :test test)) ;;;; (defmethod equivalent ((lst1 cons) (m2 <matrix>) &key (test #'math/core:semi-equal))) ;;;; (defmethod equivalent ((m1 <matrix>) (lst2 cons) &key (test #'math/core:semi-equal))) ;;;; (defmethod equivalent ((lst1 cons) (a2 array) &key (test #'math/core:semi-equal))) ;;;; (defmethod equivalent ((a1 array) (lst2 cons) &key (test #'math/core:semi-equal)))
1,796
Common Lisp
.lisp
36
46.194444
100
0.59122
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
4b7e1b4214e8ac5893f482400ddf6347a9bb37f5df18afbd40a078a9ed33a272
11,030
[ -1 ]
11,031
squarep.lisp
mnasoft_math/src/matr/methods/squarep.lisp
;;;; ./src/matr/methods/squarep.lisp (in-package :math/matr) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; squarep (defmethod squarep ((mm <matrix>)) " @b(Пример использования:) @begin[lang=lisp](code) (defparameter *mm* (make-instance '<matrix> :dimensions '(2 3))) (squarep *mm*) => NIL (defparameter *mm* (make-instance '<matrix> :dimensions '(3 3))) (squarep *mm*) => T @end(code)" (= (cols mm) (rows mm) )) (defmethod squarep ((a array)) " @b(Пример использования:) @begin[lang=lisp](code) (defparameter *aa* (make-array '(2 3) :initial-contents '((1 2 3)(4 5 6)))) (squarep *aa*) => NIL (defparameter *aa* (make-array '(3 3) :initial-contents '((1 2 3)(4 5 6) (7 8 9)))) (squarep *aa*) => T @end(code)" (= (cols a) (rows a))) (defmethod squarep ((lst cons)) " @b(Пример использования:) @begin[lang=lisp](code) (squarep '((1 2 3)(4 5 6))) => NIL (squarep '((1 2 3)(4 5 6) (7 8 9))) => T @end(code)" (= (cols lst) (rows lst)))
1,095
Common Lisp
.lisp
31
31.096774
100
0.54491
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
9e90e20d1ddc8689d26ac9d4ec2cfe5255f997cd352cb839d0254a0c5dbde4c1
11,031
[ -1 ]
11,032
mref.lisp
mnasoft_math/src/matr/methods/mref.lisp
;;;; ./src/matr/methods/mref.lisp (in-package :math/matr) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; mref (defmethod mref ((mm <matrix>) i j) " @b(Пример использования:) @begin[lang=lisp](code) (mref (matr-new 2 3 '(1 2 3 4 5 6)) 1 2) => 6 @end(code)" (aref (matrix-data mm) i j)) (defmethod mref ((mm cons) i j) (nth j (nth i mm))) (defmethod mref ((mm array) i j) (aref mm i j)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; (setf mref) (defmethod (setf mref) (value (mm <matrix>) i j) (setf (aref (matrix-data mm) i j) value) mm) (defmethod (setf mref) (value (mm cons) i j) (setf (nth j (nth i mm)) value) mm) (defmethod (setf mref) (value (mm array) i j) (setf (aref mm i j) value) mm)
863
Common Lisp
.lisp
25
31.56
100
0.46979
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
cdc326c8381c003790aae09cf2b5bf1e54d4dca8e293dcc3245c03a9ce50c300
11,032
[ -1 ]
11,033
rotate.lisp
mnasoft_math/src/matr/methods/rotate.lisp
;;;; ./src/matr/methods/rotate.lisp (in-package :math/matr) (defmethod rotate-x ((α number)) " @b(Пример использования:) @begin[lang=lisp](code) (progn (defparameter *p* (make-instance 'math/matr:<matrix> :dimensions '(1 4))) (setf (math/matr:row *p* 0) '(10.0 20.0 30.0 1.0)) (multiply *p* (rotate-y (dtr 90.0)))) @end(code)" (let ((matrix (make-instance '<matrix> :dimensions '(4 4)))) (setf (row matrix 0) `(1.0 0.0 0.0 0.0)) (setf (row matrix 1) `(0.0 ,(cos α) ,(- (sin α)) 0.0)) (setf (row matrix 2) `(0.0 ,(sin α) ,(cos α) 0.0)) (setf (row matrix 3) `(0.0 0.0 0.0 1.0)) matrix)) (defmethod rotate-y ((β number)) " @b(Пример использования:) @begin[lang=lisp](code) @end(code) " (let ((matrix (make-instance '<matrix> :dimensions '(4 4)))) (setf (row matrix 0) `( ,(cos β) 0.0 ,(sin β) 0.0)) (setf (row matrix 1) `( 0.0 1.0 0.0 0.0)) (setf (row matrix 2) `(,(- (sin β)) 0.0 ,(cos β) 0.0)) (setf (row matrix 3) `( 0.0 0.0 0.0 1.0)) matrix)) (defmethod rotate-z ((γ number)) " @b(Пример использования:) @begin[lang=lisp](code) @end(code)" (let ((matrix (make-instance '<matrix> :dimensions '(4 4)))) (setf (row matrix 0) `(,(cos γ) ,(- (sin γ)) 0.0 0.0)) (setf (row matrix 1) `(,(sin γ) ,(cos γ) 0.0 0.0)) (setf (row matrix 2) `( 0.0 0.0 1.0 0.0)) (setf (row matrix 3) `( 0.0 0.0 0.0 1.0)) matrix)) (defmethod rotate-v ((θ number) (v cons)) " @b(Пример использования:) @begin[lang=lisp](code) @end(code)" (let ((matrix (make-instance '<matrix> :dimensions '(4 4))) (x (first v)) (y (second v)) (z (third v))) (setf (row matrix 0) `(,(+ (cos θ) (* (- 1 (cos θ)) x x)) ,(- (* (- 1 (cos θ)) x y) (* (sin θ) z)) ,(+ (* (- 1 (cos θ)) x z) (* (sin θ) y)) 0.0)) (setf (row matrix 1) `(,(+ (* (- 1 (cos θ)) y x) (* (sin θ) z)) ,(+ (cos θ) (* (- 1 (cos θ)) y y)) ,(- (* (- 1 (cos θ)) y z) (* (sin θ) x)) 0.0)) (setf (row matrix 2) `(,(- (* (- 1 (cos θ)) z x) (* (sin θ) y)) ,(+ (* (- 1 (cos θ)) z y) (* (sin θ) x)) ,(+ (cos θ) (* (- 1 (cos θ)) z z)) 0.0)) (setf (row matrix 3) `( 0.0 0.0 0.0 1.0)) matrix)) (defmethod rotate-around ((point-1 cons) (point-2 cons) θ) " @b(Пример использования:) @begin[lang=lisp](code) @end(code)" (let ((rotate-p1-p2 (rotate-v θ (normalize (mapcar #'- point-2 point-1)))) (move-p1-p0 (move-v (mapcar #'- point-1))) (move-p0-p1 (move-v point-1))) (multiply (multiply move-p1-p0 rotate-p1-p2) move-p0-p1)))
2,867
Common Lisp
.lisp
59
42.322034
155
0.48913
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
f288ff3644b420af404e84abcf5b1d28c76b88d8c65661767a86452eff17dc4d
11,033
[ -1 ]
11,034
copy.lisp
mnasoft_math/src/matr/methods/copy.lisp
;;;; ./src/matr/methods/copy.lisp (in-package :math/matr) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; copy (defmethod copy ((mm-ref <matrix>)) (make-instance '<matrix> :data (cl-utilities:copy-array (matrix-data mm-ref)))) (defmethod copy ((mm-ref array)) " @b(Пример использования:) @begin[lang=lisp](code) (let* ( (a1 (make-array '(2 3) :initial-contents '((1 2 3)(4 5 6)))) (a2 (copy a1))) (setf (mref a2 1 1) 11.55) (values a2 a1) ) @end(code)" (cl-utilities:copy-array mm-ref))
609
Common Lisp
.lisp
18
29.277778
100
0.504394
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e6aab5d50a2f968dc1d3b4d129cb3740c9134af64b86c1027f2825dfb81e6be9
11,034
[ -1 ]
11,035
swap-cols.lisp
mnasoft_math/src/matr/methods/swap-cols.lisp
;;;; ./src/matr/methods/swap-cols.lisp (in-package :math/matr) (defmethod swap-cols* ((mm <matrix>) i j) (assert (and (< -1 i (cols mm)) (< -1 j (cols mm)))) (when (/= i j) (let ((col-i (col mm i)) (col-j (col mm j))) (setf (col mm i) col-j (col mm j) col-i))) mm) (defmethod swap-cols ((mm <matrix>) i j) (swap-cols* (copy mm) i j))
362
Common Lisp
.lisp
12
26.833333
54
0.554598
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
5fa212af9692c2645ac10b78482eee679e6b8d3bd29291c2006a1155c1cb9328
11,035
[ -1 ]
11,036
anti-diagonal.lisp
mnasoft_math/src/matr/methods/anti-diagonal.lisp
;;;; ./src/matr/methods/anti-diagonal.lisp (in-package :math/matr) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; anti-diagonal (defmethod anti-diagonal ((mm <matrix>)) "@b(Пример использования:) @begin[lang=lisp](code) (defparameter *mm* (make-instance '<matrix> :initial-contents '((1d0 2d0 3d0) (4d0 5d0 6d0) (7d0 8d0 9d0)))) => Matr 3х3 [ 1.0d0 2.0d0 3.0d0 ] [ 4.0d0 5.0d0 6.0d0 ] [ 7.0d0 8.0d0 9.0d0 ] (anti-diagonal *mm*) => (3.0d0 5.0d0 7.0d0) @end(code)" (assert (squarep mm) (mm) "Матрица не является квадратной~%~S" mm) (loop :for c :from 0 :below (cols mm) :for r :downfrom (- (rows mm) 1) :to 0 :collect (mref mm c r))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; (setf anti-diagonal) (defmethod (setf anti-diagonal) (elements (mm <matrix>) ) (assert (squarep mm) (mm) "Матрица не является квадратной~%~S" mm) (loop :for c :from 0 :below (cols mm) :for r :downfrom (- (rows mm) 1) :to 0 :for e :in elements :by #'cdr :do (setf (mref mm c r) e)) mm)
1,306
Common Lisp
.lisp
34
31.823529
100
0.476949
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
11097a33b167020a77a7688d4718edd3766d9be244a491c4c1c59813c0f8ef21
11,036
[ -1 ]
11,037
multiply.lisp
mnasoft_math/src/matr/methods/multiply.lisp
;;;; ./src/matr/methods/multiply.lisp (in-package :math/matr) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; multiply (defmethod multiply ((a <matrix> ) (b <matrix>)) " @b(Пример использования:) @begin[lang=lisp](code) (multiply (matr-new 2 3 '(1.0 2.0 3.0 4.0 5.0 6.0)) (matr-new 3 2 '(1.0 2.0 3.0 4.0 5.0 6.0))) => Matr 2х2 [ 22.0 28.0 ] [ 49.0 64.0 ] (multiply (matr-new 3 2 '(1.0 2.0 3.0 4.0 5.0 6.0)) (matr-new 2 3 '(1.0 2.0 3.0 4.0 5.0 6.0))) => Matr 3х3 [ 9.0 12.0 15.0 ] [ 19.0 26.0 33.0 ] [ 29.0 40.0 51.0 ] @end(code) " (let ((a_n (rows a)) (a_m (cols a)) (b_n (rows b)) (b_m (cols b)) (c nil)) (assert (= a_m b_n) (a_m b_n) "Запрещенные размеры матриц для перемножения: A[~A,~A] x B[~A,~A]" a_n a_m b_n b_m) (setf c (make-instance '<matrix> :dimensions (list a_n b_m) :initial-element 0)) (do ((i 0 (1+ i)) (a-row nil)) ((>= i a_n)) (setf a-row (row a i)) (do ((j 0 (1+ j)) (b-col nil)) ((>= j b_m)) (setf b-col (col b j)) (setf (mref c i j) (apply #'+ (mapcar #'* a-row b-col))))) c)) (defmethod multiply ((a number ) (b <matrix>)) " @b(Пример использования:) @begin[lang=lisp](code) (multiply 10 (matr-new 2 3 '(1.0 2.0 3.0 4.0 5.0 6.0))) => Matr 2х3 [ 10.0 20.0 30.0 ] [ 40.0 50.0 60.0 ] @end(code)" (let ((rez (make-instance '<matrix> :dimensions (dimensions b)))) (loop :for i :from 0 :below (rows b) :do (loop :for j :from 0 :below (cols b) :do (setf (mref rez i j) (* a (mref b i j))))) rez)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod multiply ((a number ) (v cons)) " @b(Пример использования:) @begin[lang=lisp](code) (multiply 10 '(1 2 3)) => (10 20 30) @end(code)" (loop :for i :in v :collect (* a i)))
2,070
Common Lisp
.lisp
67
25.597015
117
0.468849
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
41cb8fec195a59ac45098e2f53d5815b88e630da5a0d910b897ea734bcb6285a
11,037
[ -1 ]
11,038
prepend.lisp
mnasoft_math/src/matr/methods/prepend.lisp
;;;; ./src/matr/methods/prepend.lisp (in-package :math/matr) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; prepend (defmethod prepend-col ((col cons) (matrix cons)) " @b(Пример использования:) @begin[lang=lisp](code) (prepend-col '(10 11 12) '((1 2 3) (4 5 6) (7 8 9))) => ((10 1 2 3) (11 4 5 6) (12 7 8 9)) @end(code)" (let ((rez nil) (r nil)) (dolist (l matrix (reverse rez)) (setf r (car col) col (cdr col)) (push (cons r l) rez)))) (defmethod prepend-row ((row cons) (matrix cons)) " @b(Пример использования:) @begin[lang=lisp](code) (prepend-row '(10 11 12) '((1 2 3) (4 5 6) (7 8 9))) =>((10 11 12) ( 1 2 3) ( 4 5 6) ( 7 8 9)) (prepend-row '(10 11) '((1 2 3) (4 5 6) (7 8 9))) =>((10 11 NIL) ( 1 2 3) ( 4 5 6) ( 7 8 9)) (prepend-row '(10 11 12 13) '((1 2 3) (4 5 6) (7 8 9))) =>((10 11 12) ( 1 2 3) ( 4 5 6) ( 7 8 9)) @end(code)" (transpose (prepend-col row (transpose matrix)))) (defmethod prepend-rows ((rows cons) (matrix cons)) " @b(Пример использования:) @begin[lang=lisp](code) (prepend-rows '((10 20 30) (11 22 33)) '((11 12 13) (12 13 14) (13 14 15))) @end(code)" (reduce #'(lambda (x y) (prepend-row y x)) (reverse rows) :initial-value matrix))
1,920
Common Lisp
.lisp
61
19.540984
100
0.36394
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
9eeadecffdce196243e96d59f3a52f1a9b9d563f5d1433bce0bda83e2b5b8035
11,038
[ -1 ]
11,039
swap-rows.lisp
mnasoft_math/src/matr/methods/swap-rows.lisp
;;;; ./src/matr/methods/swap-rows.lisp (in-package :math/matr) (defmethod swap-rows* ((mm <matrix>) i j) (assert (and (< -1 i (rows mm)) (< -1 j (rows mm)))) (when (/= i j) (let ((row-i (row mm i)) (row-j (row mm j))) (setf (row mm i) row-j (row mm j) row-i))) mm) (defmethod swap-rows ((mm <matrix>) i j) (swap-rows* (copy mm) i j))
364
Common Lisp
.lisp
12
27
54
0.551429
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
4d3b31e193e88c623ae86e07831e873fe143a3e931bbfe65f429e5261ce9712a
11,039
[ -1 ]
11,040
average.lisp
mnasoft_math/src/matr/methods/average.lisp
;;;; ./src/matr/methods/average.lisp (in-package :math/matr) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; average - Вычисление среднего значения ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod average-value ((2d-list cons)) " @b(Пример использования:) @begin[lang=lisp](code) (average-value '((1.0 1.5 2.0) (2.0 2.5 3.0))) => 2.0 @end(code)" (math/stat:average-value (unite-rows 2d-list))) (defmethod average-not-nil-value ((2d-list cons)) (math/stat:average-not-nil-value (unite-rows 2d-list))) ;;;; (defmethod average-row-value ((2d-list cons)) " @b(Пример использования:) @begin[lang=lisp](code) (average-row-value '((1.0 1.5 2.0) (2.0 2.5 3.0))) => (1.5 2.5) @end(code)" (mapcar #'math/stat:average-value 2d-list)) (defmethod average-row-not-nil-value ((2d-list cons)) (mapcar #'math/stat:average-not-nil-value 2d-list)) ;;;; (defmethod average-col-value ((2d-list cons)) " @b(Пример использования:) @begin[lang=lisp](code) (average-col-value '((3.0 2.1 4.5) (2.0 2.5 3.2))) => (2.5 2.3 3.85) @end(code)" (average-row-value (transpose 2d-list))) (defmethod average-col-not-nil-value ((2d-list cons)) " @b(Пример использования:) @begin[lang=lisp](code) (average-col-not-nil-value '((nil 2.1 4.5) (2.0 nil 3.2))) => (2.0 2.1 3.85) @end(code)" (average-row-not-nil-value (transpose 2d-list)))
1,655
Common Lisp
.lisp
39
35.384615
100
0.540613
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
b1414fe974de86b53354dbee1ae890c2b174614e75cbcad793d05143c8812e1a
11,040
[ -1 ]
11,041
temp.lisp
mnasoft_math/src/gnuplot/temp.lisp
(in-package :math/gnuplot) (require :ltk) (force-output *gnuplot*) (format *gnuplot* "quit~%") (force-output *gnuplot*) (close *gnuplot*)
146
Common Lisp
.lisp
6
22
27
0.719697
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
cdfc39509e834c306ae999854bd5e7a6371ba6c3f73612c92b370e9501f97e7a
11,041
[ -1 ]
11,042
gnuplot.lisp
mnasoft_math/src/gnuplot/gnuplot.lisp
;;;; ./src/gnuplot/package.lisp (defpackage :math/gnuplot (:use #:cl #:math/core) (:export gnuplot-splot gnuplot-plot table-apply make-table *default-gnuplot-direcroty* *palette-defined-01* *pm3d-map* *palette-defined* gnuplot-data-splot gnuplot-data-plot gnuplot-data-to-file make-plot-data-file rgb *term-pngcairo* *term-pdfcairo* )) (in-package :math/gnuplot) (defparameter *default-gnuplot-direcroty* (ensure-directories-exist #P"~/gnuplot/") "Каталог для вывода по умолчанию.") ;;;; (directory-namestring *default-gnuplot-direcroty*) (defun file-name (f-name &optional (f-ext "")) "Определяет имя файла в каталоге поумолчанию." (assert (stringp f-name)) (assert (stringp f-ext)) (if (string= "" f-ext) (concatenate 'string (directory-namestring *default-gnuplot-direcroty*) f-name f-ext) (concatenate 'string (directory-namestring *default-gnuplot-direcroty*) f-name "." f-ext))) (defun find-font-family (&key (family "Times New Roman")) "@b(Описание:) функция @b(find-font-family) возвращает имя шрифта, установленного в систему похожего на тот, что указан. @b(Пример использования:) @begin[lang=lisp](code) (find-font-family :family \"Arial\") (find-font-family :family \"Courier New\") (find-font-family :family \"Times New Roman\") @end(code) " (org.shirakumo.font-discovery:family (org.shirakumo.font-discovery:find-font :family family))) (defun rgb (aa rr gg bb) "@b(Описание:) функция @b(rgb) возвращает строковое представление цвета. @b(Переменые:) @begin(list) @iterm(aa = 0..255 яркость;) @iterm(rr = 0..255 насыщенность красного;) @iterm(gg = 0..255 насыщенность зеленого;) @iterm(bb = 0..255 насыщенность синего.) @end(list) " (assert (and (<= 0 aa 255) (<= 0 rr 255) (<= 0 gg 255) (<= 0 bb 255))) (format nil "#~X~X~X~X" aa rr gg bb)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defclass <term> () ((no-enhanced :initarg no-enhanced :initform :enhanced) (mono/color :initarg mono/color :initform :mono) (font :initarg font :initform (find-font-family :family "Times New Roman")) (fontscale :initarg fontscale :initform 12) (linewidth :initarg linewidth :initform 0.5) (rounded/butt/square :initarg rounded/butt/square :initform :rounded) (dashlength :initarg dashlength :initform 1.0) (background :initarg background :initform (rgb #xFF #xFF #xFF #xFF)) (size :initarg size :initform '(15 10)) (size-units :initarg size-units :initform :cm :documentation "По умолчанию - пиксели|пиксели=72*in|пиксели=72/25.4*cm") )) (defclass term-pdfcairo (<term>) ()) (defclass term-pngcairo (<term>) ((no-transparent :initarg no-transparent :initform :no-transparent) (no-crop :initarg no-crop :initform :no-crop) (pointscale :initarg pointscale :initform 1.0)) (:documentation " @b(Пример использования:) @begin[lang=gnuplot](code) set term pngcairo {{no}enhanced} {mono|color} {{no}transparent} {{no}crop} {background <rgbcolor>} {font <font>} {fontscale <scale>} {linewidth <lw>} {rounded|butt|square} {dashlength <dl>} {pointscale <ps>} {size <XX>{unit},<YY>{unit}} @end(code) ")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defparameter *term-pdfcairo* (make-instance 'term-pdfcairo)) (defparameter *term-pngcairo* (make-instance 'term-pngcairo)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod print-object ((term term-pdfcairo) os) (format os "~a" (with-output-to-string (stream) (format stream "set term pdfcairo") (block no-enhanced (when (eq :enhanced (slot-value term 'no-enhanced)) (format stream " enhanced")) (when (eq :no-enhanced (slot-value term 'no-enhanced)) (format stream " noenhanced"))) (block mono/color (when (eq :mono (slot-value term 'mono/color)) (format stream " mono")) (when (eq :color (slot-value term 'mono/color)) (format stream " color"))) (block font-fontscale (when (and (slot-value term 'font) (slot-value term 'fontscale)) (format stream " font \"~a, ~d\"" (slot-value term 'font) (slot-value term 'fontscale)))) (when (slot-value term 'linewidth) (format stream " linewidth ~a" (slot-value term 'linewidth))) (block rounded/butt/square (when (eq :rounded (slot-value term 'rounded/butt/square)) (format stream " rounded")) (when (eq :butt (slot-value term 'rounded/butt/square)) (format stream " butt")) (when (eq :square (slot-value term 'rounded/butt/square)) (format stream " square"))) (when (slot-value term 'dashlength) (format stream " dashlength ~a" (slot-value term 'dashlength))) (when (slot-value term 'background) (format stream " background ~s" (slot-value term 'background))) (block size/size-units (when (and (slot-value term 'size) (slot-value term 'size-units) (eq :in (slot-value term 'size-units))) (format stream " size ~ain,~ain" (first (slot-value term 'size)) (second (slot-value term 'size)))) (when (and (slot-value term 'size) (slot-value term 'size-units) (eq :cm (slot-value term 'size-units))) (format stream " size ~acm,~acm" (first (slot-value term 'size)) (second (slot-value term 'size))))) (format stream ";~%")))) (defmethod print-object ((term term-pngcairo) os) (format os "~a" (with-output-to-string (stream) (format stream "set term pngcairo") (block no-enhanced (when (eq :enhanced (slot-value term 'no-enhanced)) (format stream " enhanced")) (when (eq :no-enhanced (slot-value term 'no-enhanced)) (format stream " noenhanced"))) (block mono/color (when (eq :mono (slot-value term 'mono/color)) (format stream " mono")) (when (eq :color (slot-value term 'mono/color)) (format stream " color"))) (block font-fontscale (when (and (slot-value term 'font) (slot-value term 'fontscale)) (format stream " font \"~a, ~d\"" (slot-value term 'font) (slot-value term 'fontscale)))) (when (slot-value term 'linewidth) (format stream " linewidth ~a" (slot-value term 'linewidth))) (block rounded/butt/square (when (eq :rounded (slot-value term 'rounded/butt/square)) (format stream " rounded")) (when (eq :butt (slot-value term 'rounded/butt/square)) (format stream " butt")) (when (eq :square (slot-value term 'rounded/butt/square)) (format stream " square"))) (when (slot-value term 'dashlength) (format stream " dashlength ~a" (slot-value term 'dashlength))) (when (slot-value term 'background) (format stream " background ~s" (slot-value term 'background))) (block no-transparent (when (eq :no-transparent (slot-value term 'no-transparent)) (format stream " notransparent")) (when (eq :transparent (slot-value term 'no-transparent)) (format stream " transparent"))) (block no-crop (when (eq :no-crop (slot-value term 'no-crop)) (format stream " nocrop")) (when (eq :crop (slot-value term 'no-crop)) (format stream " crop"))) (block pointscale (when (slot-value term 'pointscale) (format stream " pointscale ~a" (slot-value term 'pointscale)))) (block size/size-units (when (and (slot-value term 'size) (null (slot-value term 'size-units))) (format stream " size ~a,~a" (first (slot-value term 'size)) (second (slot-value term 'size)))) (when (and (slot-value term 'size) (slot-value term 'size-units) (eq :in (slot-value term 'size-units))) (format stream " size ~ain,~ain" (first (slot-value term 'size)) (second (slot-value term 'size)))) (when (and (slot-value term 'size) (slot-value term 'size-units) (eq :cm (slot-value term 'size-units))) (format stream " size ~acm,~acm" (first (slot-value term 'size)) (second (slot-value term 'size))))) (format stream ";~%") ))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod output ((term term-pdfcairo) (f-name string) os) (format os "~a" (with-output-to-string (stream) (format stream "set output '~a'" (file-name f-name "pdf"))))) ;;;; (get-output-stream-string stream) (format os "~a" ) (defmethod output ((term term-pngcairo) (f-name string) os) (format os "~a" (with-output-to-string (stream) (format stream "set output '~a'" (file-name f-name "png"))))) ;;;; (get-output-stream-string stream) (format os "~a" ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (format nil "~a" *term-pngcairo*) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; ./src/gnuplot/gnuplot.lisp (defun make-2d-list-by-func (func &key (x-from 0) (x-to 1) (steps 100)) (mapcar #'(lambda (el) (list el (funcall func el))) (split-range x-from x-to steps))) (defun make-table (lst-1 lst-2) "@b(Описание:) make-table выполняет формирование списка точек, разделенного на группы. @b(Пример использования:) @begin[lang=lisp](code) (make-table (split-range 1.0 0.0 2) (split-range -3 0 3)) => (((1.0 -3.0) (1.0 -2.0) (1.0 -1.0) (1.0 0.0)) ((0.5 -3.0) (0.5 -2.0) (0.5 -1.0) (0.5 0.0)) ((0.0 -3.0) (0.0 -2.0) (0.0 -1.0) (0.0 0.0))) @end(code) " (assert (consp lst-1)) (assert (consp lst-2)) (assert (not (find-if-not #'numberp lst-1))) (assert (not (find-if-not #'numberp lst-2))) (labels ((v-lst (val lst) (mapcar #'(lambda (el) (list val el)) lst))) (mapcar #'(lambda (el-1) (v-lst el-1 lst-2)) lst-1))) (defun table-apply (table func &rest second-and-others) "@b(Описание:) функция @b(table-apply) @b(Пример использования:) @begin[lang=lisp](code) (make-table (split-range 1 4 3) (split-range 5 7 2)) => (((1.0 5.0) (1.0 6.0) (1.0 7.0)) ((2.0 5.0) (2.0 6.0) (2.0 7.0)) ((3.0 5.0) (3.0 6.0) (3.0 7.0)) ((4.0 5.0) (4.0 6.0) (4.0 7.0))) (table-apply (make-table (split-range 1 4 3) (split-range 5 7 2)) #'* 10.) => (((1.0 5.0 50.0) (1.0 6.0 60.0) (1.0 7.0 70.0)) ((2.0 5.0 100.0) (2.0 6.0 120.0) (2.0 7.0 140.0)) ((3.0 5.0 150.0) (3.0 6.0 180.0) (3.0 7.0 210.0)) ((4.0 5.0 200.0) (4.0 6.0 240.0) (4.0 7.0 280.0))) (table-apply (make-table (split-range 1 4 3) (split-range 5 7 2)) #'vector) => (((1.0 5.0 #(1.0 5.0)) (1.0 6.0 #(1.0 6.0)) (1.0 7.0 #(1.0 7.0))) ((2.0 5.0 #(2.0 5.0)) (2.0 6.0 #(2.0 6.0)) (2.0 7.0 #(2.0 7.0))) ((3.0 5.0 #(3.0 5.0)) (3.0 6.0 #(3.0 6.0)) (3.0 7.0 #(3.0 7.0))) ((4.0 5.0 #(4.0 5.0)) (4.0 6.0 #(4.0 6.0)) (4.0 7.0 #(4.0 7.0)))) @end(code) " (assert (consp table)) (mapcar #'(lambda (el) (mapcar #'(lambda (el-1) (append el-1 (list (apply func (append el-1 second-and-others))))) el)) table)) (defun table-apply-0 (table func &rest second-and-others &key ) "Пример использования: (table-apply-0 (make-table (split-range 1 4 3) (split-range 5 7 2)) #'vector) => ((#(1.0 5.0) #(1.0 6.0) #(1.0 7.0)) (#(2.0 5.0) #(2.0 6.0) #(2.0 7.0)) (#(3.0 5.0) #(3.0 6.0) #(3.0 7.0)) (#(4.0 5.0) #(4.0 6.0) #(4.0 7.0))) " (assert (consp table)) (mapcar #'(lambda (el) (mapcar #'(lambda (el-1) (apply func (append el-1 second-and-others))) el)) table)) (defun table-apply-1 (table func &rest second-and-others) "Пример использования: ;;(table-apply-1 (make-table (split-range 1 4 3) (split-range 5 7 2)) #'* 10.) => (((1.0 5.0 50.0) (1.0 6.0 60.0) (1.0 7.0 70.0)) ((2.0 5.0 100.0) (2.0 6.0 120.0) (2.0 7.0 140.0)) ((3.0 5.0 150.0) (3.0 6.0 180.0) (3.0 7.0 210.0)) ((4.0 5.0 200.0) (4.0 6.0 240.0) (4.0 7.0 280.0)))" (assert (consp table)) (mapcar #'(lambda (el) (mapcar #'(lambda (el-1) (append el-1 (list (apply func (cons (apply #' vector el-1) second-and-others))))) el)) table)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; "@b(Описание:) обобщенная функция @b(gnuplot-data-to-file) выводит данные @b(data) в файл с именем @b(f-name), расположенный в каталоге поумолчанию (см. переменную *default-gnuplot-direcroty*)."(defgeneric gnuplot-data-to-file (f-name data)) (defmethod gnuplot-data-to-file (f-name (data cons)) "@b(Описание:) метод @b(gnuplot-data-to-file) выводит данные @b(data) в файл с именем @b(f-name), расположенный в каталоге поумолчанию (см. переменную *default-gnuplot-direcroty*). Данные должны быть представлены 2d-list. @b(Пример использования:) @begin[lang=lisp](code) (gnuplot-data-to-file \"data\" (loop :for i :from 0 :to 4 :by 1/10 :collect (list i (* i i)))) @end(code) " (with-open-file (os (file-name f-name "data") :direction :output :if-exists :supersede :external-format :utf8) (mapc #'(lambda (el) (format os "~{~F ~}~%" el)) data) (format t "'~A'" (file-name f-name "data")))) ;;;; (gnuplot-data-to-file "data-2d-list" (loop :for i :from 0 :to 4 :by 1/10 :collect (list i (* i i)))) (defmethod gnuplot-data-to-file (f-name (data array)) "@b(Описание:) метод @b(gnuplot-data-to-file) выводит данные @b(data) в файл с именем @b(f-name), расположенный в каталоге поумолчанию (см. переменную *default-gnuplot-direcroty*). Данные должны быть представлены 2d-array. @b(Пример использования:) @begin[lang=lisp](code) (gnuplot-data-to-file \"data\" (loop :for i :from 0 :to 4 :by 1/10 :collect (list i (* i i)))) (gnuplot-data-to-file \"data\" (make-array '(5 2) :initial-contents '((0 0)(1 1)(2 4)(3 9)(4 16)))) @end(code) " (assert (= (array-rank data) 2)) (with-open-file (os (file-name f-name "data") :direction :output :if-exists :supersede :external-format :utf8) (loop :for i :from 0 :below (array-dimension data 0) :do (loop :for j :from 0 :below (array-dimension data 1) :do (format os "~F " (aref data i j))) (format os "~%" )) (format t "'~A'" (file-name f-name "data")))) ;;;; (gnuplot-data-to-file "data-array" (make-array '(5 2) :initial-contents '((0 0)(1 1)(2 4)(3 9)(4 16)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defparameter *palette-defined* "set palette defined (0.05 'blue', 0.2 'cyan', 0.4 'green', 0.6 'yellow', 0.8 'orange', 1.0 'red')" "STUB") (defparameter *palette-defined-01* "set palette defined (0 'blue', 0.1 'white', 0.2 'cyan', 0.3 'white', 0.4 'green', 0.5 'white', 0.6 'yellow', 0.7 'white', 0.8 'orange', 0.9 'white', 1 'red')" "STUB") (defparameter *pm3d-map* "set pm3d map" "STUB") (defun gnuplot-splot (f-name &key (terminal "set terminal pdfcairo enhanced font 'Arial,14' size 13.5 cm, 5.0 cm ") (output (concatenate 'string "set output '" f-name ".pdf'")) (preamble nil) (palette *palette-defined*) (pm3d *pm3d-map*) (splot (concatenate 'string "splot '" (file-name f-name "data") "' u 2:1:3"))) "Осуществляет подготовку данных, содержащихся в файле f-name с расширением data. Данные в файле должны иметь формат gp-list." (assert (probe-file (file-name f-name "data"))) (with-open-file (gp (file-name f-name "gp") :direction :output :if-exists :supersede :external-format :utf8) (when terminal (format gp "~A~%" terminal)) (when preamble (format gp "~A~%" preamble)) (when output (format gp "~A~%" output)) (when palette (format gp "~A~%" palette)) (when pm3d (format gp "~A~%" pm3d)) (when splot (format gp "~A~%" splot))) (with-open-file (sh (file-name f-name "sh") :direction :output :if-exists :supersede :external-format :utf8) (format sh "#!/bin/bash~%" ) (format sh "gnuplot ~A.gp~%" f-name)) (uiop:run-program (concatenate 'string "sh" " " f-name "." "sh") :ignore-error-status t)) (defun gnuplot-data-splot ( f-name data &key (terminal "set terminal pdfcairo enhanced font 'Arial,14' size 13.5 cm, 5.0 cm ") (output (concatenate 'string "set output '" (file-name f-name "pdf'"))) (preamble nil) (palette *palette-defined*) (pm3d *pm3d-map*) (splot (concatenate 'string "splot '" (file-name f-name "data")"' u 2:1:3"))) "STUB" (assert (consp data)) (assert (consp (first data))) (assert (consp (first (first data)))) (with-open-file (os (file-name f-name "data") :direction :output :if-exists :supersede :external-format :utf8) (format os "# ~8A ~8A ~8A~%" "X" "Y" "Z" ) (format os "~{~{~{~8F ~}~%~}~%~}" data )) (with-open-file (gp (file-name f-name "gp") :direction :output :if-exists :supersede :external-format :utf8) (when terminal (format gp "~A~%" terminal)) (when preamble (format gp "~A~%" preamble)) (when output (format gp "~A~%" output)) (when palette (format gp "~A~%" palette)) (when pm3d (format gp "~A~%" pm3d)) (when splot (format gp "~A~%" splot))) (with-open-file (sh (file-name f-name "sh") :direction :output :if-exists :supersede :external-format :utf8) (format sh "#!/bin/bash~%" ) (format sh "gnuplot ~A~%" (file-name f-name "gp"))) (uiop:run-program (concatenate 'string "sh" " " (file-name f-name "sh")) :ignore-error-status t)) ;;;; set terminal pngcairo size 1000,600 enhanced font 'Verdana,10' ;;;; set output 'introduction.png' ;;;; set palette defined (0 'blue', 0.1 'white', 0.2 'cyan', 0.3 'white', 0.4 'green', 0.5 'white', 0.6 'yellow', 0.7 'white', 0.8 'orange', 0.9 'white', 1 'red') ;;;; set pm3d map ;;;; splot '~/splot.data' u 2:1:3 ;;;; exit ;;;; gnuplot splot 'splot.data' u 1:2:3 w l ;;;; splot "grid" u 1:2:3 w l ;;;; splot "matrix" nonuniform matrix u 1:2:3 w l ;;;; pos( k, origin, spacing ) = origin + k*spacing ;;;; splot "packedmatrix" matrix u (pos($1,0,1)):(pos($2,-1,1)):3 w l (defun gnuplot-data-plot (f-name data &key (terminal (format nil "~a" *term-pdfcairo*)) (output (concatenate 'string "set output '" (file-name f-name "pdf") "'")) (preamble "set xrange [0:4]") (plot (concatenate 'string "plot '" (file-name f-name "data")"' u 1:2 with lines"))) "@b(Описание:) функция @b(gnuplot-data-plot) @b(Пример использования:) @begin[lang=lisp](code) ;;;; Пример 1 (math:gnuplot-data-plot \"plot2\" (mapcar #'(lambda (x) (list x (sin x)(sqrt x)) ) (math:split-range 0.0 10 1000) ) :plot \"plot 'plot2.data' u 1:2 with lines lt 1, 'plot2.data' u 1:3 with lines lt 2 \") @end(code) " (assert (consp data)) (assert (consp (first data))) (with-open-file (os (file-name f-name "data") :direction :output :if-exists :supersede :external-format :utf8) (format os "# ~8A ~8A~%" "X" "Y" ) (format os "~{~{~8F ~}~%~}" data )) (with-open-file (gp (file-name f-name "gp") :direction :output :if-exists :supersede :external-format :utf8) (when terminal (format gp "~A~%" terminal)) (when preamble (format gp "~A~%" preamble)) (when output (format gp "~A~%" output)) (when plot (format gp "~A~%" plot))) (with-open-file (sh (file-name f-name "sh") :direction :output :if-exists :supersede :external-format :utf8) (format sh "#!/bin/bash~%" ) (format sh "gnuplot ~A~%" (file-name f-name "gp"))) (uiop:run-program (concatenate 'string "sh" " " (file-name f-name "sh")) :ignore-error-status t)) ;;;; (gnuplot-data-plot "123" (make-2d-list-by-func #'(lambda (el) (* el el)) :x-from 0 :x-to 4 :steps 100)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun gnuplot-plot (f-name &key (terminal (format nil "~a" *term-pdfcairo*)) (preamble "set xrange [0:2.5]") (output (concatenate 'string "set output '" (file-name f-name ".pdf") "'")) (plot (concatenate 'string "plot '" (file-name f-name ".data") "' u 2:1"))) "STUB" (with-open-file (gp (file-name f-name ".gp") :direction :output :if-exists :supersede :external-format :utf8) (when terminal (format gp "~A~%" terminal)) (when preamble (format gp "~A~%" preamble)) (when output (format gp "~A~%" output)) (when plot (format gp "~A~%" plot))) (with-open-file (sh (file-name f-name "sh") :direction :output :if-exists :supersede :external-format :utf8) (format sh "#!/bin/bash~%" ) (format sh "gnuplot ~A~%" (file-name f-name "gp"))) (uiop:run-program (concatenate 'string "sh" " " (file-name f-name "sh")) :ignore-error-status t)) (defmethod plot ((f-name string) (term <term>) (data cons) &key (preamble "set xrange [0:2.5]") (plot (concatenate 'string "plot '" (file-name f-name ".data") "' u 2:1"))) (with-open-file (gp (file-name f-name ".gp") :direction :output :if-exists :supersede :external-format :utf8) (format gp "~a~%" term) (format gp "~a~%" (output term)) (when preamble (format gp "~A~%" preamble)) (when output (format gp "~A~%" output)) (when plot (format gp "~A~%" plot))) (with-open-file (sh (file-name f-name "sh") :direction :output :if-exists :supersede :external-format :utf8) (format sh "#!/bin/bash~%" ) (format sh "gnuplot ~A~%" (file-name f-name "gp"))) (uiop:run-program (concatenate 'string "sh" " " (file-name f-name "sh")) :ignore-error-status t)) (defun make-plot-data-file (f-name data) "@b(Описание:) функция @b(make-plot-data-file) выполняет вывод данных @b(data) в файл с именем f-name и расширением data. @b(Пример использования:) @begin[lang=lisp](code) ;;;; Пример 1 (make-plot-data-file \"plot2\" (mapcar #'(lambda (x) (list x (sin x) (sqrt x))) (math:split-range 0.0 10 1000))) @end(code) " (assert (consp data)) (assert (consp (first data))) (with-open-file (os (concatenate 'string f-name "." "data") :direction :output :if-exists :supersede :external-format :utf8) (format os "~{~{~8F ~}~%~}" data ))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defclass gnuplot-vector () ((orign :accessor gnuplot-vector-origin :initform (vector 0.0 0.0 0.0) :initarg :orign) (direction :accessor gnuplot-vector-direction :initform (vector 1.0 0.0 0.0) :initarg :direction))) (defmethod print-object ((v gnuplot-vector) s) (format s "~{~A ~}" (coerce (gnuplot-vector-origin v) 'list )) (format s "~{~A ~}" (coerce (gnuplot-vector-direction v) 'list ))) (defgeneric move (obj displacement)) (defgeneric move (obj displacement)) (defmethod move ((obj gnuplot-vector) (displacement vector)) (with-slots (orign) obj (assert (= (length displacement) (length orign ))) (loop :for i :from 0 :below (length (gnuplot-vector-origin obj)) :do (setf (svref orign i) (+ (svref orign i) (svref displacement i)))) obj)) ;;;; (defmethod rotate ((obj gnuplot-vector) (angle number) (o vector))) ;(make-instance 'matrix :dimensions '(3 3)) ;(make-instance 'vector ;(defparameter *gp-v* (make-instance 'gnuplot-vector )) ;(move *gp-v* #(-10. -10. -10.)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
25,990
Common Lisp
.lisp
511
41.925636
162
0.560062
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
93afbbb0a87315b5908f05e79404099497416529df14351a5adf5f7394f8cebd
11,042
[ -1 ]
11,043
approximation-gnuplot.lisp
mnasoft_math/src/gnuplot/example/approximation-gnuplot.lisp
;;;; approximation.lisp (in-package :math) (defparameter *arr-2xN* (make-array '(5 2) :initial-contents '((-2.0 0.91553) (-1.0 1.15765) (0.0 1.68105) (1.0 1.15759) (2.0 0.9213)))) (defparameter *a-rez* (math:gauss-1-approximation-array *arr-2xN* :dx0 1.0 :delta 0.000001 :iterations 100)) (defun g-1-0 (x) (spline-1d x 1.0 *a-rez*)) (gnuplot-data-to-file (make-2d-list-by-func 'g-1-0 :x-from -25/10 :x-to 25/10 :steps 100) "~/apr.data") (defmethod gnuplot-data-to-file ((ar array) f-name) (with-open-file (os f-name :direction :output :if-exists :supersede ) (loop :for i :from 0 :below (array-dimension ar 0) :do (loop :for j :from 0 :below (array-dimension ar 1) :do (format os "~F " (aref ar i j))) (format os "~%" )))) (gnuplot-data-to-file *arr-2xn* "~/pts.data") (make-2d-list-by-func 'g-1-0 :x-from -25/10 :x-to 25/10 :steps 100) (defun g-1-0 (x) (spline-1d x 1.0 *arr-2xN*)) (gnuplot-list-to-file (make-2d-list-by-func 'g-1-0 :x-from -25/10 :x-to 25/10 :steps 100) "~/gauss-1.0.data") (let ((dx 1.5)) (gnuplot-list-to-file (loop :for x :from 0 :to 4 :by 1/50 :collect (list x (spline-1d x dx *arr-2xN*))) "d:/PRG/msys/home/namatv/test.data") (gnuplot-list-to-file (loop :for x :from 0 :to 4 :by 1/50 :collect (list x (spline-1d x dx *arr-2xN* :w-func #'exp-smoothing))) "d:/PRG/msys/home/namatv/test1.data") (gnuplot-list-to-file (loop :for x :from 0 :to 4 :by 1/50 :collect (list x (spline-1d x dx *arr-2xN* :w-func #'cauchy-smoothing))) "d:/PRG/msys/home/namatv/test2.data") (gnuplot-list-to-file (loop :for x :from 0 :to 4 :by 1/50 :collect (list x (spline-1d x dx *arr-2xN* :w-func #'hann-smoothing))) "d:/PRG/msys/home/namatv/test3.data") (gnuplot-list-to-file (loop :for x :from 0 :to 4 :by 1/50 :collect (list x (spline-1d x dx *arr-2xN* :w-func #'mann-w-1d))) "d:/PRG/msys/home/namatv/test4.data") ) gnuplot plot "test.data" with lines, "test1.data" with lines, "test2.data" with lines, "test3.data" with lines, "test4.data" with lines; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (math/gnuplot:gnuplot-data-plot "y-x2" (let* ((nod-pts #(-2.0 -1.0 -0.5 0.0 0.5 1.0 2.0)) (nod-rez #( 4.0 1.0 0.25 0.0 0.25 1.0 4.0)) (base-dists-1_5 1.5 ) (base-dists-1_0 1.0 ) (base-dists-0_6 0.6 ) (base-dists-0_4 0.4 ) (func (make-refine-smoothing nod-pts nod-rez base-dists-1_5))) (loop :for i :from -2 :to 2 :by 1/10 :collect (list (* 1.0 i) (* 1.0 i i) (funcall func (* 1.0 i)) (* 100 (1- (/ (* 1.0 i i) (funcall func (* 1.0 i)))))))))
2,639
Common Lisp
.lisp
51
48
136
0.597271
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
25c48e1e836973ce9c23cbcb2926e3537aff142ed9e0a74040d4339932823b8d
11,043
[ -1 ]
11,044
smooth.lisp
mnasoft_math/src/smooth/smooth.lisp
;;;; smoothing.lisp ;;;; ./src/smooth/smooth.lisp (defpackage :math/smooth (:use #:cl) (:export gauss-smoothing exp-smoothing cauchy-smoothing hann-smoothing) (:export weight-func-list weight-func-p)) (in-package :math/smooth) (defun gauss-smoothing (d) "@b(Описание:) функция @b(gauss-smoothing) @b(Пример использования:) @begin[lang=lisp](code) (loop :for d :from 0 :to 4 :by 1/10 :collect (list d (gauss-smoothing d))) @end(code)" (exp (* -1 d d))) (defun exp-smoothing (d) "@b(Описание:) функция @b(exp-smoothing) @b(Пример использования:) @begin[lang=lisp](code) (loop :for d :from 0 :to 4 :by 1/10 :collect (list d (exp-smoothing d))) @end(code)" (exp (* -1 d))) (defun cauchy-smoothing (d) "@b(Описание:) функция @b(cauchy-smoothing) @b(Пример использования:) @begin[lang=lisp](code) (loop :for d :from 0 :to 4 :by 1/10 :collect (list d (cauchy-smoothing d))) @end(code)" (/ 1 (+ 1 (* d d)))) (defun hann-smoothing (d) "@b(Описание:) функция @b(hann-smoothing) @b(Пример использования:) @begin[lang=lisp](code) (loop :for d :from 0 :to 4 :by 0.1 :do (format t \"~{~5F~^ ~}~%\" (list d (gauss-smoothing d) (exp-smoothing d) (cauchy-smoothing d) (hann-smoothing d)))) @end(code)" (if (< d 1) (* 1/2 ( + 1 ( cos (* pi d)))) 0)) (defun weight-func-list () (list #'gauss-smoothing #'exp-smoothing #'cauchy-smoothing #'hann-smoothing)) (defun weight-func-p (func) (if (member func (weight-func-list)) t nil))
1,721
Common Lisp
.lisp
55
24.745455
48
0.616601
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
ad30ecfeaed5c71f3d8ce74059def811dbb7335162695c384120f2e4c17a334b
11,044
[ -1 ]
11,045
series.lisp
mnasoft_math/src/series/series.lisp
;;;; ./src/series/series.lisp (defpackage :math/series (:use #:cl ) (:export <arithmetic> <arithmetic>-a <arithmetic>-d <geometric> <geometric>-b <geometric>-q summ item first-by-number&summ scale-by-number&summ ) (:documentation "@b(Описание:) пакет @b(math/series) определяет некоторые операции с прогрессиями.")) (in-package :math/series) (defclass <series> () ()) (defclass <arithmetic> (<series>) ((a :accessor <arithmetic>-a :initform 0.0 :initarg :a :documentation "Первый член арифметической прогрессии (нумерация начинается с нуля).") (d :accessor <arithmetic>-d :initform 1.2 :initarg :d :documentation "Разность арифметической прогрессии."))) (defclass <geometric> () ((b :accessor <geometric>-b :initform 1 :initarg :b :documentation "Первый член геометрической прогрессии (нумерация начинается с нуля).") (q :accessor <geometric>-q :initform 1.2 :initarg :q :documentation "Знаменатель геометрической прогрессии.")) (:documentation "@b(Описание:) класс @b(<geometric>) представляет геометрическую прогрессию.")) (defmethod print-object ((series <arithmetic>) stream) (print-unreadable-object (series stream :type t) (format stream "~A, ~A+~A, ..., ~A+~A*i" (<arithmetic>-a series) (<arithmetic>-a series) (<arithmetic>-d series) (<arithmetic>-a series) (<arithmetic>-d series)))) (defmethod print-object ((series <geometric>) stream) (print-unreadable-object (series stream :type t) (format stream "~A, ~A*~A, ..., ~A+~A^i" (<geometric>-b series) (<geometric>-b series) (<geometric>-q series) (<geometric>-b series) (<geometric>-q series)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defgeneric summ (series n) (:documentation "@b(Описание:) обобщенная_функция @b(summ) возвращает сумму @b(n) членов прогрессии.")) (defgeneric item (series i) (:documentation "@b(Описание:) обобщенная_функция @b(item) возвращает значение @b(i)-того члена прогрессии.")) (defgeneric items-by-summ (series summ) (:documentation "@b(Описание:) обобщенная функция @b(items-by-summ) возвращает количество членов прогрессии, чтобы их сумма равнялась @b(summ).")) (defgeneric first-by-number&summ (series n S) (:documentation "@b(Описание:) обобщенная функция @b(first-by-number&summ) возвращает первый член прогрессии, такой чтобы сумма n членов равнялась @b(S). При этом прогрессия сама поргрессия @b(series) изменяется.")) (defgeneric scale-by-number&summ (series n S &key from to) (:documentation "@b(Описание:) обобщенная_функция @b(scale-by-number&summ) возвращает масштаб (разность для арифмеической прогрессии или степень для геометрической прогрессии) такую, чтобы сумма @b(n) членов прогрессии равнялась @b(S).")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod summ ((series <geometric>) (n integer)) " @b(Пример использования:) @begin[lang=lisp](code) (summ (make-instance '<geometric> :b 2 :q 1.2) 5) => 14.883203 @end(code)" (let ((b (<geometric>-b series)) (q (<geometric>-q series))) (/ (* b (- (expt q n) 1))(- q 1)))) (defmethod summ ((series <arithmetic>) (n integer)) "@b(Пример использования:) @begin[lang=lisp](code) (summ (make-instance '<arithmetic> :a 2 :d 1.2) 5) ; => 22.0 @end(code)" (let ((a (<arithmetic>-a series)) (d (<arithmetic>-d series))) (* 1/2 n (+ (* 2 a) (* d (- n 1)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod item ((series <geometric>) (i integer)) (let ((b (<geometric>-b series)) (q (<geometric>-q series))) (* b (expt q i)))) (defmethod item ((series <arithmetic>) (i integer)) (let ((a (<geometric>-a series)) (d (<geometric>-d series))) (+ a (expt d i)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod items-by-summ ((series <geometric>) S) "@b(Описание:) функция @b(n) количество членов геометрической прогрессии, чтобы их сумма равнялась @b(S)." (let ((b (<geometric>-b series)) (q (<geometric>-q series))) (/ (log (+ 1 (/ (* S (- q 1)) b))) (log q)))) (defmethod items-by-summ ((series <arithmetic>) S) "@b(Описание:) функция @b(n) количество членов геометрической прогрессии, чтобы их сумма равнялась @b(S)." (let* ((a (<arithmetic>-a series)) (d (<arithmetic>-d series)) (eq (make-instance 'math/equation:<quadric> :a (/ d 2) :b (- a (/ d 2) ) :c (- S)))) (apply #'max (math/equation:roots eq)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod first-by-number&summ ((series <geometric>) n S) (let ((q (<geometric>-q series))) (setf (<geometric>-b series) (/ (* S (- q 1)) (- (expt q n) 1))))) (defmethod first-by-number&summ ((series <arithmetic>) n S) (let ((d (<arithmetic>-d series))) (setf (<arithmetic>-a series) (+ (/ (- S (* d n n 1/2)) n) (* d 1/2))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod scale-by-number&summ ((series <geometric>) n S &key (from 0.001) (to 1000.)) (let ((b (<geometric>-b series))) (setf (<geometric>-q series) (math/half-div:h-div from to #'(lambda (q) (- (/ (* b (- (expt q n) 1)) (- q 1)) S)))))) (defmethod scale-by-number&summ ((series <arithmetic>) n S &key from to) (declare (ignore from to)) (let ((a (<arithmetic>-a series))) (setf (<arithmetic>-d series) (/ (- (/ (* 2 S) n) (* 2 a)) (- n 1))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; #+nil (loop :for i :from 0 :to 4 :summing (item *g* i) :into total :finally (return total)) #+nil (defparameter *g* (make-instance '<geometric> :b 1.0 :q 1.2)) #+nil (defparameter *a* (make-instance '<arithmetic> :a 0.0 :d 1.2))
7,088
Common Lisp
.lisp
158
33.240506
100
0.568713
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e6836e3be0fe183cc3830e1912b476d9aca13af183ba2607eb80e415f3940633
11,045
[ -1 ]
11,046
geom.lisp
mnasoft_math/src/geom/geom.lisp
;;;; ./src/geom/geom-doc.lisp (defpackage :math/geom (:use #:cl) (:export triangle-area-by-sides regular-triangle-area-by-side regular-triangle-side-by-area) (:export regular-tetrahedron-volume-by-side regular-tetrahedron-side-by-volume) (:export diameter-by-radius radius-by-diameter) (:export circle-area-by-radius circle-area-by-diameter) (:export equivalent-diameter) ) (in-package :math/geom) (defun triangle-area-by-sides (a b c) "@b(Описание:) функция @b(triangle-area-by-sides) возвращает площадь треугольника со сторонами @b(a), @b(b), @b(c). @b(Пример использования:) @begin[lang=lisp](code) (triangle-area-by-sides 1.0 1.0 1.0) => 0.4330127 ; (/ (sqrt 3) 4) (triangle-area-by-sides 2.0 2.0 2.0) => 1.7320508 ; (sqrt 3) (triangle-area-by-sides 3.0 4.0 5.0) => 6.0 (triangle-area-by-sides 1.0 2.0 3.0) => 0.0 @end(code)" (let ((p (/ (+ a b c) 2))) (sqrt (* p (- p a) (- p b) (- p c))))) (defun regular-triangle-area-by-side (a) "@b(Описание:) функция @b(triangle-area-by-sides) возвращает площадь правильного треугольника со стороной @b(a). @b(Пример использования:) @begin[lang=lisp](code) (regular-triangle-area-by-side 1.0 1.0 1.0) => 0.4330127 ; (/ (sqrt 3) 4) (regular-triangle-area-by-side 2.0 2.0 2.0) => 1.7320508 ; (sqrt 3) @end(code)" (triangle-area-by-sides a a a)) (defun regular-triangle-side-by-area (s) "@b(Описание:) функция @b(regular-triangle-side-by-area) длину стороны правильного треугольника с площадью @b(s). @b(Пример использования:) @begin[lang=lisp](code) (regular-triangle-side-by-area 0.4330127) => 1.0 (regular-triangle-side-by-area 1.7320508) => 2.0 @end(code)" (sqrt (/ s (/ (sqrt 3) 4)))) (defun regular-tetrahedron-volume-by-side (a) "@b(Описание:) функция @b(regular-tetrahedron-volume-by-side) возвращает объем правильного тетраэдра с ребром @b(a). @b(Пример использования:) @begin[lang=lisp](code) (regular-tetrahedron-volume-by-side 1.00) => 0.11785113 (regular-tetrahedron-volume-by-side 10.0) => 117.85112 @end(code)" (* 1/12 a a a (sqrt 2))) (defun regular-tetrahedron-side-by-volume (v) "@b(Описание:) функция @b(regular-tetrahedron-volume-by-side) возвращает объем правильного тетраэдра с ребром @b(a). @b(Пример использования:) @begin[lang=lisp](code) (regular-tetrahedron-side-by-volume 1.00) => 2.039649 (regular-tetrahedron-side-by-volume 10.0) => 4.3942904 @end(code)" (expt (/ (* 12 v) (sqrt 2)) 1/3)) (defun diameter-by-radius (radius) (* radius 2)) (defun radius-by-diameter (diameter) (/ diameter 2)) (defun circle-area-by-radius (radius) "@b(Описание:) функция @b(circle-area-by-radius) " (* pi radius radius)) (defun circle-area-by-diameter (diameter) (circle-area-by-radius (radius-by-diameter diameter))) (defun equivalent-diameter (area perimeter) " @link[uri=\"https://ru.wikipedia.org/wiki/Гидравлический_диаметр/\"](Гидравлический_диаметр) @link[uri=\"https://en.wikipedia.org/wiki/Hydraulic_diameter/\"](Hydraulic_diameter) " (* 4 (/ area perimeter)))
3,545
Common Lisp
.lisp
79
35.974684
93
0.688645
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
5b285500e78fd4e23ea7a941c6f7b920f7d7303fe1ab476c75f2caa79bc4edad
11,046
[ -1 ]
11,047
stat.lisp
mnasoft_math/src/stat/stat.lisp
;;;; statistics.lisp (defpackage :math/stat (:use #:cl #:math/core) (:intern remove-first remove-last) (:export make-random-value-list ) (:export average dispersion dispersion-not-nil standard-deviation standard-deviation-not-nil variation-coefficient variation-coefficient-not-nil ) (:export max-value average-value min-value) (:export min-not-nil-value average-not-nil-value max-not-nil-value) (:export grubbs-max grubbs grubbs-min) (:export delta-max-value delta-min-value) (:export clean-max-flagrant-error clean-min-flagrant-error clean-flagrant-error) (:export aver-max-min aver-dmax-dmin) (:export factorial permutations combinations )) (in-package :math/stat) (defun factorial (x) "Факториал x." (gsll:factorial x)) (defun permutations (n) "Количество перестановок" (gsll:factorial n)) (defun combinations (i n) "Количество сочетаний из n по i." (/ (factorial n) (factorial i) (factorial (- n i)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun remove-first (lst) (cdr lst)) (defun remove-last (lst) (butlast lst)) (defun average (&rest x) "@b(Описание:) функция @b(average) возврвщает среднее значение для перечня величин. @b(Пример использования:) @begin[lang=lisp](code) (average 1.1 1.0 0.9 1.2 0.8) => 1.0 @end(code)" (assert (< 0 (length x))) (/ (apply #'+ x) (length x))) (defun average-value (x) "@b(Описание:) функция @b(average-value) возвращает среднее значение для списка величин. @b(Пример использования:) @begin[lang=lisp](code) (average-value '(1.1 1.0 0.9 1.2 0.8)) => 1.0 @end(code)" (apply #'average x)) ;;;; (assert (< 0 (length x))) (/ (apply #'+ x) (length x)) (defun average-not-nil-value (x) "@b(Описание:) функция @b(average-not-nil-value) возвращает среднее значение для списка величин. @b(Переменые:) @begin(list) @item(x - список, содержащий числа или nil.) @end(list) @b(Пример использования:) @begin[lang=lisp](code) (average-not-nil-value '(1.1 1.0 nil 0.9 nil 1.2 nil 0.8)) => 1.0 @end(code) " (apply #'average (exclude-nil-from-list x))) (defun min-value (x) "@b(Описание:) функция @b(min-value) возвращает максимальное значение для списка величин. @b(Пример использования:) @begin[lang=lisp](code) (min-value '(1.1 1.0 0.9 1.2 0.8)) => 0.8 @end(code)" (apply #'min x)) (defun delta-min-value (x) "@b(Описание:) функция @b(delta-min-value) возвращает отклонение минимальной величины от среднего значения для списка величин. @b(Пример использования:) @begin[lang=lisp](code) (delta-min-value '(1.1 1.0 0.9 1.2 0.8)) -0.19999999 @end(code)" (- (min-value x) (apply #'average x))) (defun min-not-nil-value (x) "@b(Описание:) функция min-not-nil-value возвращает минимальное значение для списка величин. @b(Переменые:) @begin(list) @item(x - список, содержащий числовые значения или nil.) @end(list) @b(Пример использования:) @begin[lang=lisp](code) (min-not-nil-value '(nil 20 nil 5 nil 10)) => 5 @end(code)" (min-value (exclude-nil-from-list x))) (defun max-value (x) "@b(Описание:) функция max-value возвращает максимальное значение для списка величин @b(Пример использования:) @begin[lang=lisp](code) (max-value '(1.1 1.0 0.9 1.2 0.8)) => 1.2 @end(code)" (apply #'max x)) (defun delta-max-value (x) "Возвращает отклонение максимальной величины от среднего значения для списка величин. @b(Пример использования:) @begin[lang=lisp](code) (delta-max-value '(1.1 1.0 0.9 1.2 0.8)) => 0.20000005 @end(code)" (- (max-value x) (apply #'average x))) (defun max-not-nil-value (x) "@b(Описание:) функция max-not-nil-value возвращает максимальное значение для списка величин. @b(Переменые:) @begin(list) @item(x - список, содержащий числовые значения или nil.) @end(list) @b(Пример использования:) @begin[lang=lisp](code) (max-not-nil-value '(nil 20 nil 5 nil 10)) => 20 @end(code)" (max-value (exclude-nil-from-list x))) (defun dispersion (x) "@b(Описание:) функция dispersion возвращает дисперсию для списка величин. @b(Пример использования:) @begin[lang=lisp](code) (dispersion '(1.1 1.0 0.9 1.2 0.8)) => 0.025000006 @end(code)" (let* ((x-sr (apply #'average x)) (n-1 (1- (length x))) (summ (apply #'+ (mapcar #'(lambda (el) (square (- el x-sr))) x)))) (/ summ n-1))) (defun dispersion-not-nil (x) (dispersion (exclude-nil-from-list x))) (defun standard-deviation (x) "@b(Описание:) функция standard-deviation возвращает среднеквадратичное (стандартное) отклонение для списка величин. @b(Переменые:) @begin(list) @item(x - список, содержащий числовые значения.) @end(list) @b(Пример использования:) @begin[lang=lisp](code) (standard-deviation '(1.1 1.0 0.9 1.2 0.8)) => 0.1581139 @end(code)" (sqrt (dispersion x))) (defun standard-deviation-not-nil (x) (standard-deviation (exclude-nil-from-list x))) (defun variation-coefficient (x) "@b(Описание:) возвращает @link[uri=\"https://ru.wikipedia.org/wiki/Коэффициент_вариации\"](коэффициент вариации) для списка величин. @b(Пример использования:) @begin[lang=lisp](code) (variation-coefficient '(1.1 1.0 0.9 1.2 0.8)) @end(code) " (/ (standard-deviation x) (apply #'average X))) (defun variation-coefficient-not-nil (x) (variation-coefficient (exclude-nil-from-list x))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defparameter *G-t* '((3 1.155 1.155) (4 1.496 1.481) (5 1.764 1.715) (6 1.973 1.887) (7 2.139 2.020) (8 2.274 2.126) (9 2.387 2.215) (10 2.482 2.290) (11 2.564 2.355) (12 2.636 2.412) (13 2.699 2.462) (14 2.755 2.507) (15 2.806 2.549) (16 2.852 2.585) (17 2.894 2.620) (18 2.932 2.651) (19 2.968 2.681) (20 3.001 2.709) (21 3.031 2.733) (22 3.060 2.758) (23 3.087 2.781) (24 3.112 2.802) (25 3.135 2.822) (26 3.157 2.841) (27 3.178 2.859) (28 3.199 2.876) (29 3.218 2.893) (30 3.236 2.908) (31 3.253 2.924) (32 3.270 2.938) (33 3.286 2.952) (34 3.301 2.965) (35 3.301 2.965) ;; Принято как для 34 (36 3.330 2.991) (37 3.330 2.991) ;; Принято как для 36 (38 3.356 3.014) (39 3.356 3.014) ;; Принято как для 38 (40 3.381 3.036)) "Критические значения Gt для критерия Граббса. |----+-------------------------------------| | n | Одно наибольшее или одно наименьшее | | | значение при уровне значимости q | |----+------------------+------------------| | | сыше 1% | свыше 5% | |----+-------------------------------------| | 3 | 1.155 | 1.155 | ............................................ ............................................ ............................................ | 40 | 3.381 | 3.036 | |----+------------------+------------------| см. ГОСТ Р 8.736-2011 " ) (defun grubbs (n &optional (q 0.05)) "@b(Описание:) функция grubbs вычисляет значение критерия Граббса (см. п. 6.1 см. ГОСТ Р 8.736-2011). @b(Переменые:) @begin(list) @item(n - количество повторяющихся измерений величины.) @item(q - уровень значимости в доях.) @end(list) @b(Пример использования:) @begin[lang=lisp](code) (let ((lst '(10.0 10.1 10.15 10.2 10.8 9.9 9.85 9.9 10.1))) (grubbs (length lst))) => 2.215 @end(code)" (assert (<= 3 n 40) nil "Количество значений должно быть между 3 и 40") (assert (>= q 0.01) nil "Уровень значимости q должен быть больше 0.01") (let ((arg-num (if (>= q 0.05) #'third #'second))) (funcall arg-num (assoc n *G-t*)))) (defun grubbs-max (x) "@b(Описание:) функция grubbs-max возврвщает значения критерия Граббса для максимального значения списка величин. @b(Переменые:) @begin(list) @item(x - список, содержащий числовые значения.) @end(list) @b(Пример использования:) @begin[lang=lisp](code) (let ((lst '(10.0 10.1 10.15 10.2 10.8 9.9 9.85 9.9 10.1))) (grubbs-max lst)) => 2.4095862 @end(code)" (/ (- (max-value x) (apply #'average x)) (standard-deviation x))) (defun grubbs-min (x) "@b(Описание:) функция grubbs-min возврвщает значения критерия Граббса для минимального значения списка величин. @b(Переменые:) @begin(list) @item(x - список, содержащий числовые значения.) @end(list) @b(Пример использования:) @begin[lang=lisp](code) (let ((lst '(10.0 10.1 10.15 10.2 10.8 9.9 9.7 9.9 10.1))) (grubbs-min lst)) => 1.2863455 @end(code)" (/ (- (apply #'average x) (min-value x) ) (standard-deviation x))) (defun clean-flagrant-error (x) "@b(Описание:) функция @b(clean-flagrant-error) удаляет из статистики грубые промахи. @b(Пример использования:) @begin[lang=lisp](code) (let ((lst '(10.0 10.1 10.15 10.2 12.0 9.9 5.0 9.9 10.1))) (clean-flagrant-error lst)) (9.9 9.9 10.0 10.1 10.1 10.15 10.2) @end(code)" (labels ((remove-last (x) "Удаляет из списка последний элемент" (reverse (cdr (reverse x)))) (remove-first (x) "Удаляет из списка первый элемент" (cdr x)) ) (do* ((lst (sort (copy-list x) #'<)) (n (length lst) (1- n)) (gr-1 (grubbs-max lst) (grubbs-max lst)) (gr-2 (grubbs-min lst) (grubbs-min lst)) (exiting nil)) (exiting lst) (cond ((> gr-1 (grubbs n)) (setf lst (remove-last lst))) ((> gr-2 (grubbs n)) (setf lst (remove-first lst))) (t (setf exiting t)))))) (defun make-random-value-list (mid-value &key (std-deviation 1.0) (n 40) (top-level 1000000)) "@b(Описание:) функция @b(make-random-value-list) возвращает список случайных величин: @b(Переменые:) @begin(list) @item(mid-value - среднее значение; ) @item(std-deviation - стандартное отклонение;) @item(n - количество точек; ) @item(top-level - дискретизация точек) @end(list) " (let ((x nil)) (dotimes (i n) (push (+ mid-value (* std-deviation 3.4725 (/ (- (random top-level) (/ (- top-level 1) 2)) top-level ))) x)) (values x (apply #'average x) (standard-deviation x)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun clean-min-flagrant-error (x) "@b(Описание:) функция @b(clean-min-flagrant-error) удаляет из статистики грубые промахи." (do* ((lst (sort (copy-list x) #'<)) (n (length lst) (1- n)) (gr-2 (grubbs-min lst) (grubbs-min lst)) (exiting nil)) (exiting lst) (cond ((> gr-2 (grubbs n)) (setf lst (remove-first lst))) (t (setf exiting t))))) (defun clean-max-flagrant-error (x) "@b(Описание:) функция @b(clean-max-flagrant-error) удаляет из статистики грубые промахи." (do* ((lst (sort (copy-list x) #'<)) (n (length lst) (1- n)) (gr-1 (grubbs-max lst) (grubbs-max lst)) (exiting nil)) (exiting lst) (cond ((> gr-1 (grubbs n)) (setf lst (remove-last lst))) (t (setf exiting t))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun aver-max-min (seq) "@b(Описание:) функция @b(aver-max-min) возвращает список, состоящий из: @begin(list) @item(среднего значения величины;) @item(максимального значения величины;) @item( минимального значения величины.) @end(list) @b(Пример использования:) @begin[lang=lisp](code) (aver-max-min '(7.3869333 9.938901 8.541331 10.828626 9.348187 11.323172)) => (9.561192 11.323172 7.3869333) @end(code)" (let ((mid-v (math/stat:average-value seq)) (max-v (math/stat:max-value seq)) (min-v (math/stat:min-value seq))) (list mid-v max-v min-v))) (defun aver-dmax-dmin (seq &optional (significant-digits +significant-digits+)) "@b(Описание:) функция @b(aver-max-min) возвращает список, состоящий из: @begin(list) @item(из среднего значения величины;) @item(отклонения максимального занчения в выборке от среднего;) @item(отклонения минимального занчения в выборке от среднего.) @end(list) Входящие в список величины округляются до количества значащих цифр равных @b(significant-digits). @b(Пример использования:) @begin[lang=lisp](code) (aver-dmax-dmin '(17.3869333 19.938901 12.41331 11.828626 10.348187 12.323172)) => (14.04 5.9 -3.69) @end(code)" (let* ((mid-v (math/stat:average-value seq)) (max-v (math/stat:max-value seq)) (min-v (math/stat:min-value seq))) (list (round-to-significant-digits mid-v significant-digits) (round-to-significant-digits (- max-v mid-v) significant-digits mid-v) (round-to-significant-digits (- min-v mid-v) significant-digits mid-v))))
15,346
Common Lisp
.lisp
381
30.005249
100
0.619323
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
6dab5074a8db6e4dd2270bc512664b004950d43d2bc0e064ea91f0969f79addd
11,047
[ -1 ]
11,048
docs.lisp
mnasoft_math/src/docs/docs.lisp
(defpackage :math/docs (:use #:cl ) (:export make-all) (:documentation " Пакет @b(math/docs) содержит функции генерирования и публикации документации. @b(Пример использования:) @begin[lang=lisp](code) (ql:quickload :math/docs) (math/docs:make-all) @end(code) ")) (in-package :math/docs) (defun make-document () (loop :for j :from 1 :for i :in '(;; 1 (:math :math) (:math/ls-rotation :math/ls-rotation) (:math/geom :math/geom) (:math/appr :math/appr) (:math/matr :math/matr) (:math/ls-gauss :math/ls-gauss) (:math/smooth :math/smooth) (:math/coord :math/coord) (:math/stat :math/stat) (:math/core :math/core) (:math/gnuplot :math/gnuplot) (:math/rnd :math/rnd) (:math/series :math/series) (:math/stat :math/stat) (:math/docs :math/docs) #+nil (:math/x-o :math/x-o) ) :do (progn (apply #'mnas-package:document i) (format t "~A ~A~%" j i)))) (defun make-graphs () (loop :for j :from 1 :for i :in '(:math :math/ls-rotation :math/geom :math/appr :math/matr :math/ls-gauss :math/smooth :math/coord :math/stat :math/core :math/gnuplot :math/rnd :math/series :math/stat :math/docs #+nil :math/x-o ) :do (progn (mnas-package:make-codex-graphs i i) (format t "~A ~A~%" j i)))) (defun make-all (&aux (of (if (find (uiop:hostname) mnas-package:*intranet-hosts* :test #'string= :key #'first) '(:type :multi-html :template :gamma) '(:type :multi-html :template :minima)))) (let* ((sys-symbol :math) (sys-string (string-downcase (format nil "~a" sys-symbol)))) (mnas-package:make-html-path sys-symbol) (make-document) (mnas-package:make-mainfest-lisp `(,sys-symbol) (string-capitalize sys-string) '("Mykola Matvyeyev") (mnas-package:find-sources sys-symbol) :output-format of) (codex:document sys-symbol) (make-graphs) (mnas-package:copy-doc->public-html sys-string) (mnas-package:rsync-doc sys-string) :make-all-finish)) ;;;; (make-all)
2,631
Common Lisp
.lisp
84
21.892857
75
0.510751
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
09d52bb0d1248ff94ec9a1882e1329c93797292683e63583b1358f3ead590a4f
11,048
[ -1 ]
11,049
x-o.lisp
mnasoft_math/src/x-o/x-o.lisp
;;;; x-o.lisp (defpackage :math/x-o (:use #:cl #:math/matr) (:export play)) (in-package :math/x-o) (defclass <x-o> (<matrix>) ()) (defmethod matr-name-* ((mm <x-o>)) "X-O") (defmethod print-object ((x-o <x-o>) s) (print-unreadable-object (x-o s :type t) (when (and (matrix-data x-o) (arrayp (matrix-data x-o))) (format s "~{~A~^х~}" (array-dimensions (matrix-data x-o))) (loop :for i :from 0 :below (array-dimension (matrix-data x-o) 0) :do (format s "~%[") (loop :for j :from 0 :below (array-dimension (matrix-data x-o) 1) :do (format s " ~A " (aref (matrix-data x-o) i j))) (format s "]"))))) (defmethod initialize-instance ((mm <x-o>) &key (rows 3) (cols 3) ) (setf (matrix-data mm) (make-array (list rows cols) :initial-element 0))) (defmethod x-o-reset ((mm <x-o>)) (loop :for i :from 0 :below (array-dimension (matrix-data mm) 0) :do (loop :for j :from 0 :below (array-dimension (matrix-data mm) 1) :do (setf (aref (matrix-data mm) i j) 0)))) (defparameter *xo* (make-instance '<x-o> )) ;;;;; (defun mate-value (value lst) (every #'(lambda (el) (eq value el)) lst)) (defun check-value (value lst) (let ((v-y (count-if #'(lambda (el) (= value el)) lst)) (v-n (- (count-if-not #'(lambda (el) (= value el)) lst) (count-if #'(lambda (el) (= 0 el)) lst)))) (and (<= v-n 0) (= v-y 2)))) (defun half-check-value (value lst) (let ((v-y (count-if #'(lambda (el) (= value el)) lst)) (v-n (- (count-if-not #'(lambda (el) (= value el)) lst) (count-if #'(lambda (el) (= 0 el)) lst)))) (and (<= v-n 0) (= v-y 1)))) (defmethod x-o-lines ((mm <x-o>)) (append (loop :for r :from 0 :below (rows mm) :collect (row mm r)) (loop :for c :from 0 :below (cols mm) :collect (col mm c)) (list (main-diagonal mm) (anti-diagonal mm)))) (defmethod x-o-winp ((mm <x-o>) player) "Определяет для расстановки <x-o> выиграл-ли игрок player" (let ((lst (mapcar #'(lambda (el) (mate-value player el) ) (x-o-lines mm)))) (some #'(lambda (el) el) lst))) (defmethod x-o-check-num ((mm <x-o>) player) "Определяет количество шахов" (let ((lst (mapcar #'(lambda (el) (check-value player el) ) (x-o-lines mm)))) (count t lst))) (defmethod x-o-1/2-check-num ((mm <x-o>) player) "Определяет количество полушахов" (let ((lst (mapcar #'(lambda (el) (half-check-value player el) ) (x-o-lines mm)))) (count t lst))) (defmethod free-fields ((mm <x-o>)) "Возвращает свободные поля" (let ((rez nil)) (loop :for i :from 0 :below (array-dimension (matrix-data mm) 0) :do (loop :for j :from 0 :below (array-dimension (matrix-data mm) 1) :do (when (= 0 (aref (matrix-data mm) i j)) (push (list i j) rez)))) rez)) (defmethod game-over-p ((mm <x-o>)) "Возвращает статус игры" (let* ((first-winner (x-o-winp mm 1)) (second-winner (x-o-winp mm 2)) (game-error (and first-winner second-winner))) (cond (game-error (format t "~%game-error: player-1 and player-2 both are winners!?") t) (first-winner (print mm) (format t "~%player-1 win!") t) (second-winner (print mm) (format t "~%player-2 win!") t) ((null (free-fields mm)) (print mm) (format t "~%Game over. No winners!") t) (t nil)))) (defun get-random-element (lst) (when lst (nth (random (length lst)) lst))) (defmethod step-check-rule-back (rule (mm <x-o>) player r c) (let ((rez (funcall rule (setf (mref mm r c) player) player))) (setf (mref mm r c) 0) (list rez r c))) (defmethod check-rule (rule chek-for-payer (mm <x-o>) move-player r c) (let ((rez (funcall rule (setf (mref mm r c) move-player) chek-for-payer))) (setf (mref mm r c) 0) (list rez r c))) (defmethod map-check-rule (rule check-for-payer (mm <x-o>) move-player) (mapcar #'(lambda (el) (check-rule rule check-for-payer mm move-player (first el) (second el))) (free-fields mm))) (defmethod map-step-check-rule-back (rule (mm <x-o>) player) (mapcar #'(lambda (el) (step-check-rule-back rule mm player (first el) (second el))) (free-fields mm))) (defmethod may-win-next-step ((mm <x-o>) player) (let* ((rez (map-step-check-rule-back #'x-o-winp mm player )) (win-coords nil )) (mapcar #'(lambda (el) (when (first el) (push (cdr el) win-coords))) rez) win-coords)) (defun other-player (player) (case player (1 2) (2 1))) (defparameter *player* 1) (defun next-player () (setf *player* (other-player *player*))) (defun collect-as-first-rank (triple-lst) (when triple-lst (let ((key (first (first triple-lst)))) (loop :for i :in triple-lst :when (= key (first i )) :collect i)))) (defun rank-union (triple-lst-1 triple-lst-2) (union triple-lst-1 triple-lst-2 :key #'cdr :test #'equal)) (defun rank-intersection (triple-lst-1 triple-lst-2) (intersection triple-lst-1 triple-lst-2 :key #'cdr :test #'equal)) (defmethod move ((mm <x-o>) player) (unless (game-over-p mm) (let* ((may-win (may-win-next-step mm player)) (min-check (collect-as-first-rank (sort (map-check-rule 'x-o-check-num (other-player player) mm player ) #'< :key #'first))) (min-1/2-check (collect-as-first-rank (sort (map-check-rule 'x-o-1/2-check-num (other-player player) mm player ) #'< :key #'first))) (max-check (collect-as-first-rank (sort (map-check-rule 'x-o-check-num player mm player ) #'> :key #'first))) (max-1/2-check (collect-as-first-rank (sort (map-check-rule 'x-o-1/2-check-num player mm player ) #'> :key #'first))) (mv (cdr (cond (may-win (cons t (get-random-element may-win))) ((get-random-element (reduce #'rank-intersection (list min-check min-1/2-check max-check max-1/2-check)))) ((get-random-element (reduce #'rank-intersection (list min-check min-1/2-check max-check)))) ((get-random-element (reduce #'rank-intersection (list min-check min-1/2-check)))) ((get-random-element min-check))))) (row (first mv)) (col (second mv))) (setf (mref mm row col)player)))) (defun xo-dialog (mm) (do ((rr nil) (done nil)) (done) (if (game-over-p mm) (x-o-reset *xo*) (progn (print mm) (format t "~%Current player - ~A" *player*) (format t "~%[help reset pl pl1 pl2 exit]<row col>:") (game-over-p mm) (setf rr (read-line)) (print rr) (cond ((string= rr "help") (format t" help - Вывод настоящй справки; reset - Перезапуск игры; pl - Программа выполняет допустимый ход за текущего игрока; pl1 - Программа выполняет допустимый ход за первого игрока; pl2 - Программа выполняет допустимый ход за второго игрока; exit - Выход из игры player - 1 или 2; row - [0..2] строка, в которую помещается ход игрока player; col - [0..2] столбец, в который помещается ход игрока player.")) ((string= rr "exit") (setf done t)) ((string= rr "reset") (x-o-reset mm)) ((string= rr "pl") (move mm *player*) (next-player)) ((string= rr "pl1") (move mm 1) (setf *player* 2)) ((string= rr "pl2") (move mm 2) (setf *player* 1)) (t (multiple-value-bind (rr cc) (values-list (eval (read-from-string (concatenate 'string "(list " rr ")")))) (setf (mref mm rr cc) *player*)) (next-player))))))) (defun play () "@b(Описание:) функция @b(play) запускает на выполнение консольную игру крестики-нолики. " (x-o-reset *xo*) (setf *player* 1) (xo-dialog *xo*)) ;;;; (play)
8,049
Common Lisp
.lisp
181
37.718232
112
0.605909
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
2779c208c98003fc0c0d8b9340f0dcdf1f363011b6a1ff741beefdd5b90638d0
11,049
[ -1 ]
11,050
list-matr-tests.lisp
mnasoft_math/src/tests/list-matr-tests.lisp
;;;; tests/matrix.lisp (in-package :math/tests) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def-suite list-matr-tests :description "Мастер-набор всех тестов системы math/matr для матриц типа 2d-list." :in all) (in-suite list-matr-tests) (def-fixture fix-2dlist-m1-3x5 () (let ((m1-3x5 '((14 55 68 16 20) (41 20 4 57 2) (85 54 96 3 91))) (m1-3x5+row-5 '((14 55 68 16 20) (41 20 4 57 2) (85 54 96 3 91) (11 12 13 14 15))) (row-5+m1-3x5 '((11 12 13 14 15) (14 55 68 16 20) (41 20 4 57 2) (85 54 96 3 91))) (m1-3x5+col-3 '((14 55 68 16 20 11) (41 20 4 57 2 12) (85 54 96 3 91 13))) (col-3+m1-3x5 '((11 14 55 68 16 20) (12 41 20 4 57 2) (13 85 54 96 3 91))) (m1-5x3 '((14 41 85) (55 20 54) (68 4 96) (16 57 3) (20 2 91))) (row-5 '(11 12 13 14 15)) (col-3 '(11 12 13 )) (m1-3x5-nil '((14 55 68 nil 20) (nil 20 4 57 2) (85 nil 96 3 nil))) (m1-5x3-nil '((14 nil 85) (55 20 nil) (68 4 96) (nil 57 3) (20 2 nil)))) (declare (ignore m1-3x5 m1-3x5+row-5 row-5+m1-3x5 m1-3x5+col-3 col-3+m1-3x5 m1-5x3 row-5 col-3 m1-3x5-nil m1-5x3-nil)) (&body))) (def-test list-matr-rows-cols-dimensions-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (= (math/matr:cols m1-3x5) 5)) (is-true (= (math/matr:rows m1-3x5) 3)) (is-true (equal (math/matr:dimensions m1-3x5) '(3 5))))) (def-test list-matr-row-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (equal (math/matr:row 0 m1-3x5) (first m1-3x5))) (is-true (equal (math/matr:row 1 m1-3x5) (second m1-3x5))) (is-true (equal (math/matr:row 2 m1-3x5) (third m1-3x5))))) (def-test list-matr-col-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (equal (math/matr:col 0 m1-3x5) '(14 41 85))) (is-true (equal (math/matr:col 1 m1-3x5) '(55 20 54))) (is-true (equal (math/matr:col 2 m1-3x5) '(68 4 96))) (is-true (equal (math/matr:col 3 m1-3x5) '(16 57 3))) (is-true (equal (math/matr:col 4 m1-3x5) '(20 2 91))))) (def-test unite-rows-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (= (length (math/matr:unite-rows m1-3x5)) 15)) (is-true (= (length (math/matr:unite-rows m1-3x5-nil)) 15)) (is-true (equal (math/matr:unite-rows m1-3x5) '(14 55 68 16 20 41 20 4 57 2 85 54 96 3 91))) (is-true (equal (math/matr:unite-rows m1-3x5-nil) '(14 55 68 nil 20 nil 20 4 57 2 85 nil 96 3 nil))))) (def-test average-value-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (= (math/matr:average-value m1-3x5) 626/15)))) (def-test average-not-nil-value-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (= (math/matr:average-not-nil-value m1-3x5) 626/15)) (is-true (= (math/matr:average-not-nil-value m1-3x5-nil) 424/11)))) (def-test average-row-value-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (equal (math/matr:average-row-value m1-3x5) '(173/5 124/5 329/5))) )) (def-test average-row-not-nil-value-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (equal (math/matr:average-row-not-nil-value m1-3x5) '(173/5 124/5 329/5))) (is-true (equal (math/matr:average-row-not-nil-value m1-3x5-nil) '(157/4 83/4 184/3))) )) (def-test average-col-value-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (equal (math/matr:average-col-value m1-3x5) '(140/3 43 56 76/3 113/3))))) (def-test average-col-not-nil-value-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (equal (math/matr:average-col-not-nil-value m1-3x5) '(140/3 43 56 76/3 113/3))) (is-true (equal (math/matr:average-col-not-nil-value m1-3x5-nil) '(99/2 75/2 56 30 11))) )) (def-test max-row-not-nil-value-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (equal (math/matr:max-row-not-nil-value m1-3x5) '(68 57 96))) (is-true (equal (math/matr:max-row-not-nil-value m1-3x5-nil) '(68 57 96))))) (def-test max-col-not-nil-value-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (equal (math/matr:max-col-not-nil-value m1-3x5) '(85 55 96 57 91))) (is-true (equal (math/matr:max-col-not-nil-value m1-3x5-nil) '(85 55 96 57 20))))) (def-test transpose-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (equal (math/matr:transpose m1-3x5) m1-5x3)) (is-true (equal (math/matr:transpose m1-5x3) m1-3x5)) (is-true (equal (math/matr:transpose m1-3x5-nil) m1-5x3-nil)) (is-true (equal (math/matr:transpose m1-5x3-nil) m1-3x5-nil)))) (def-test detach-last-col-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (equal (math/matr:detach-last-col m1-3x5+col-3) m1-3x5)) )) (def-test get-last-col-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (equal (math/matr:get-last-col m1-3x5+col-3) col-3)))) (def-test prepend-row-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (equal (math/matr:prepend-row row-5 m1-3x5) row-5+m1-3x5)) )) (def-test prepend-col-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (equal (math/matr:prepend-col col-3 m1-3x5) col-3+m1-3x5)) )) (def-test append-row-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (equal (math/matr:append-row row-5 m1-3x5) m1-3x5+row-5)))) (def-test append-col-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (equal (math/matr:append-col col-3 m1-3x5) m1-3x5+col-3)))) (def-test make-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (equal (math/matr:make 3 5 (math/matr:unite-rows m1-3x5)) m1-3x5)) (is-true (equal (math/matr:make 2 3 '(1 2 3)) '((1 2 3) (nil nil nil)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def-test lv-print-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (string= (math/matr:lv-print col-3 :stream nil) " 11.0 12.0 13.0 ")))) (def-test lm-print-test () "Проверка размеров матрицы." (with-fixture fix-2dlist-m1-3x5 () (is-true (string= (math/matr:lm-print m1-3x5 :stream nil) " 14.0 55.0 68.0 16.0 20.0 41.0 20.0 4.0 57.0 2.0 85.0 54.0 96.0 3.0 91.0 "))))
7,469
Common Lisp
.lisp
174
35.701149
100
0.606638
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
de20cc95677be6de7fa2cd354a567fae991aa8688b2359ab113272c515735991
11,050
[ -1 ]
11,051
package.lisp
mnasoft_math/src/tests/package.lisp
;;;; tests/package.lisp (defpackage :math/tests (:use #:cl #:fiveam) (:export #:run-tests) (:documentation " @b(Описание:) Пакет @b(math/tests) предназначен для проверки изменений, внесенных в пакеты, связаные с :math. Загузка пакета осуществляется через загрузку системы: @b(Пример использования:) @begin[lang=lisp](code) (ql:quickload :math/tests) @end(code) Для выполнения всех тестов выполните: @b(Пример использования:) @begin[lang=lisp](code) (run-tests) @end(code) ")) (in-package :math/tests) (defun run-tests () (run! 'all)) ;;;;(run-tests)
758
Common Lisp
.lisp
21
25.190476
60
0.735675
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
f4218ae1fa1e0dce06a925b9ab4758c0ff198e4beb6d18646da39a37466b605f
11,051
[ -1 ]
11,052
ls-gauss.lisp
mnasoft_math/src/tests/ls-gauss.lisp
;;;; ./src/tests/ls-gauss.lisp (in-package :math/tests) (def-suite ls-gauss :description "Мастер-набор тестов по решению СЛАУ (системы линейных алгебраических уравнений." :in all) (in-suite ls-gauss) (def-test linear-system-convert-to-triangular-test () "Пример использования: (test-convert-to-triangular)" (let ((m1 (make-instance 'math/matr:<matrix> :initial-contents '((0.0 0.0 4.0 12.0) (2.0 0.0 2.0 8.0) (0.0 3.0 0.0 6.0)))) (m1-tr (make-instance 'math/matr:<matrix> :initial-contents '(( 1.0 0.0 1.0 4.0 ) ( 0.0 1.0 0.0 2.0 ) ( 0.0 0.0 1.0 3.0 ))))) (is-true (math/matr:equivalent m1-tr (math/ls-gauss:convert-to-triangular m1))))) (def-test backward-run-test () "Пример использования: (test-matr-obrhod)" (let ((m1 (make-instance 'math/matr:<matrix> :initial-contents '(( 1.0 0.0 1.0 4.0 ) ( 0.0 1.0 0.0 2.0 ) ( 0.0 0.0 1.0 3.0 )))) (m1-obrhod (make-instance 'math/matr:<matrix> :initial-contents '(( 1.0 2.0 3.0 ))))) (is-true (math/matr:equivalent m1-obrhod (math/ls-gauss:backward-run m1))))) (def-test ls-gauss-solve-x-test () "Пример использования: (test-solve-x)" (let ((m1 (make-instance 'math/matr:<matrix> :initial-contents '((1 2 3 14) (2 1 1 7) (3 0 1 2)))) (m1-gau (make-instance 'math/matr:<matrix> :initial-contents '(( 1/3 16/3 1 ))))) (is-true (math/matr:equivalent (math/ls-gauss:solve-x m1) m1-gau)))) (def-test ls-gauss-solve-x () (is-true (math/core:semi-equal (let ((m '((1 2 3 14) (2 1 1 7) (3 0 1 6)))) (math/ls-gauss:solve-x m)) #(1 2 3))) (loop :for i :from 1 :to 9 :do (let* ((m (math/rnd:make-2d-list i)) (v (math/rnd:make-1d-list i)) (m-v (math/rnd:make-ls-system m v))) (when (not (math/ls-gauss:singular-p m-v)) (is-true (math/core:semi-equal (math/ls-gauss:solve-x m-v) v))))))
2,188
Common Lisp
.lisp
67
24.80597
60
0.561871
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
7191b1edddf4e3b426b9ea3fb008ae58d87a267c12ac6b502b0b5dd737282fa1
11,052
[ -1 ]
11,053
coord.lisp
mnasoft_math/src/tests/coord.lisp
;;;; tests/array.lisp (in-package :math/tests) (def-suite coord :description "Мастер-набор всех тестов проекта math/matr для матрицы типа coord." :in all) (in-suite coord) (def-test coord-dtr-rtd () (loop :for (degree radian) :in `((0 0) (15 ,(* pi 1/12)) (30 ,(* pi 2/12)) (45 ,(* pi 3/12)) (60 ,(* pi 4/12)) (75 ,(* pi 5/12)) (90 ,(* pi 6/12))) :do (is-true (math/core:semi-equal (math/coord:dtr degree) radian)) (is-true (math/core:semi-equal (math/coord:rtd radian) degree)))) (def-test coord-polar-cartesian () (loop :for (polar cartesian) :in '(((10d0 0.0d0) (10.0d0 0.0d0)) ((10d0 0.5235987755982988d0) ( 8.660254037844387d0 5.0d0)) ((10d0 1.0471975511965976d0) ( 5.0d0 8.660254037844386d0)) ((10d0 1.5707963267948966d0) ( 6.123233995736766d-16 10.0d0)) ((10d0 2.0943951023931953d0) (-5.0d0 8.660254037844387d0)) ((10d0 2.6179938779914944d0) (-8.660254037844387d0 5.0d0)) ((10d0 3.141592653589793d0) (-10.0d0 0.0d0))) :do (is-true (math/core:semi-equal (math/coord:polar->cartesian polar) cartesian)) (is-true (math/core:semi-equal (math/coord:cartesian->polar cartesian) polar)))) (def-test coord-spherical-cartesian () (loop :for cartesian :in '(( 10d0 10.0d0 10.0d0) (-10d0 10.0d0 10.0d0) ( 10d0 -10.0d0 10.0d0) ( 10d0 10.0d0 -10.0d0)) :do (is-true (math/core:semi-equal (math/coord:spherical->cartesian (math/coord:cartesian->spherical cartesian)) cartesian))) (is-true (math/core:semi-equal (math/coord:spherical->cartesian `(100.0d0 0.0d0 ,(* pi 1/2))) '(100.0d0 0.0d0 0.0d0))) (is-true (math/core:semi-equal (math/coord:spherical->cartesian `(100.0d0 ,(* pi 1/3) ,(* pi 1/3))) '(43.301270189221945d0 75.0d0 50.0d0))))
2,230
Common Lisp
.lisp
51
33.137255
93
0.528169
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
626c35aef45168d19f6354508bae9af2c39d3fa95ce38692a898c446b9add856
11,053
[ -1 ]
11,054
2d-array.lisp
mnasoft_math/src/tests/2d-array.lisp
;;;; ./src/tests/2d-array.lisp (in-package :math/tests) (def-suite 2d-array :description "Мастер-набор всех тестов проекта math/matr для матрицы типа 2d-array." :in all) (in-suite 2d-array) (def-test array-get-row-test () "Проверка доступа к строкам." (let ((arr (make-array '(5 2) :initial-contents '((0 1) (2 3) (4 5) (6 7) (8 9)))) (arr-1 (make-array '(5 2 3) :initial-element 0))) ;;;(signal (row -1 arr)) ; => error ;;;(signal (row 5 arr)) ; => error (is-true (math/core:semi-equal (math/matr:row 0 arr) '(0 1))) (is-true (math/core:semi-equal (math/matr:row 2 arr) '(4 5))) (is-true (math/core:semi-equal (math/matr:row 4 arr) '(8 9)))))
868
Common Lisp
.lisp
27
23
70
0.534974
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e2cb2e51b52a6a1663f57475e677a1b683a53eb299bc8616277d4b58db2e69ac
11,054
[ -1 ]
11,055
ls-rotation.lisp
mnasoft_math/src/tests/ls-rotation.lisp
;;;; ./src/tests/ls-rotation.lisp (in-package :math/tests) (def-suite ls-rotation :description "Мастер-набор всех тестов math/ls-rotation решение системы линейных уравнений методом вращения." :in all) (in-suite ls-rotation) (def-test ls-rotation-solve-x () (is-true (math/core:semi-equal (let ((m '((1 2 3 14) (2 1 1 7) (3 0 1 6)))) (math/ls-rotation:solve-x m)) #(1 2 3))) (loop :for i :from 1 :to 9 :do (let* ((m (math/rnd:make-2d-list i)) (v (math/rnd:make-1d-list i)) (m-v (math/rnd:make-ls-system m v))) (when (not (math/ls-gauss:singular-p m-v)) (is-true (math/core:semi-equal (math/ls-rotation:solve-x m-v) v))))))
817
Common Lisp
.lisp
24
25.291667
73
0.576976
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
6330102cb01e49ee25ba361c67220a8905d66d2ce132567e2e908fe08dc95f49
11,055
[ -1 ]
11,056
half-div.lisp
mnasoft_math/src/tests/half-div.lisp
;;;; tests/array.lisp (in-package :math/tests) (def-suite half-div :description "Мастер-набор всех тестов проекта math/matr для матрицы типа 2d-array." :in all) (in-suite half-div) (def-test h-div-h-div-lst () (is-true (math/core:semi-equal 1382.7728 (math/half-div:h-div-lst 2.0d0 100000.0d0 #'(lambda (x y) (- (* x (log x)) y)) 0 '(t 10000.) :eps 1d-10 :iters 50)))) (def-test h-div-h-div () (is-true (math/core:semi-equal 1382.7728 (math/half-div:h-div 2.0 100000.0 #'(lambda (x) (- (* x (log x)) 10000.)) :iters 50))))
895
Common Lisp
.lisp
24
20.791667
70
0.419315
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
ccd50b97f1a288ac0e228259fb32df2022c82eccaf3eeef627dfc8d4ff912867
11,056
[ -1 ]
11,057
ls-gsll.lisp
mnasoft_math/src/tests/ls-gsll.lisp
;;;; ./math/src/tests/ls-gsll.lisp (in-package :math/tests) (def-suite ls-gsll :description "Мастер-набор всех тестов math/ls-gsll решение системы линейных уравнений при помощи библиотеки gsll." :in all) (in-suite ls-gsll) (def-test ls-gsll-solve-x () (is-true (math/core:semi-equal (let ((m '((1 2 3 14) (2 1 1 7) (3 0 1 6)))) (math/ls-gsll:solve-x m)) #(1 2 3))) (loop :for i :from 1 :to 9 :do (let* ((m (math/rnd:make-2d-list i)) (v (math/rnd:make-1d-list i)) (m-v (math/rnd:make-ls-system m v))) (when (not (math/ls-gauss:singular-p m-v)) (is-true (math/core:semi-equal (math/ls-gsll:solve-x m-v) v))))))
808
Common Lisp
.lisp
24
24.75
69
0.564972
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
848ae7d57eadbebe64f9c5ef31d05583db74cf1064fb44f07df2caea6a68d72d
11,057
[ -1 ]
11,058
array.lisp
mnasoft_math/src/tests/array.lisp
;;;; tests/array.lisp (in-package :math/tests) (def-suite 2d-array :description "Мастер-набор всех тестов проекта math/matr для матрицы типа 2d-array." :in all) (in-suite 2d-array) (def-test array-get-row () "Проверка доступа к строкам." (let ((arr (make-array '(5 2) :initial-contents '((0 1) (2 3) (4 5) (6 7) (8 9)))) (arr-1 (make-array '(5 2 3) :initial-element 0))) ;;;(signal (row -1 arr)) ; => error ;;;(signal (row 5 arr)) ; => error (is-true (equalp (math:row 0 arr) #(0 1))) (is-true (equalp (math:row 2 arr) #(4 5))) (is-true (equalp (math:row 4 arr) #(8 9))) ;;; (is-true (equal (row 2 arr-1))) ))
754
Common Lisp
.lisp
23
25.695652
70
0.570997
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
65df11780cb81aa023c9fa8cbac7ea450631ebed173baabae8db4b2454321714
11,058
[ -1 ]
11,059
matrix.lisp
mnasoft_math/src/tests/matrix.lisp
;;;; (in-package :math/tests) (defun make-<matrix>-int (rows cols) "@b(Описание:) функция @b(make-<matrix>-int) возвращает матрицу с количеством строк rows=1..9 и столбцов cols=1..9 и ининциализирует элементы целыми значениями. @b(Пример использования:) @begin[lang=lisp](code) (make-<matrix>-int 2 3) => Matr 2х3 [ 11 12 13 ] [ 21 22 23 ] @end(code)" (assert (< 0 rows 10)) (assert (< 0 cols 10)) (let ((matr (make-instance 'math/matr:<matrix> :initial-element 0 :dimensions (list rows cols)))) (loop :for i :from 0 :below rows :do (loop :for j :from 0 :below cols :do (setf (math/matr:mref matr i j) (+ 11 (* 10 i) j)))) matr)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def-suite matrix-tests :description "Мастер-набор всех тестов проекта math." :in all) (in-suite matrix-tests) (def-fixture fix-<matrix>-m1-3x5 () (let ((m1-3x5 (make-<matrix>-int 3 5))) (&body))) (def-fixture fix-<matrix>-m2-3x5 () (let ((m2-3x5 (make-<matrix>-int 3 5))) (&body))) (def-fixture fix-a1-a2-a3-a4-2x2 () (let ((a1 (make-array '(2 2) :initial-contents '((10.00000 10.0000) (11.00000 11.0000)))) (a2 (make-array '(2 2) :initial-contents '((10.00000 10.00000) (11.000000 11.000001)))) (a3 (make-array '(2 2) :initial-contents '(( 9.999999 9.999999) (10.999999 10.999999)))) (a4 (make-array '(2 2) :initial-contents '((10.00100 10.0010) (11.00100 11.0010))))) (&body))) (def-test matrix-size-test () "Проверка размеров матрицы." (with-fixture fix-<matrix>-m1-3x5 () (is-true (= (math/matr:cols m1-3x5) 5)) (is-true (= (math/matr:rows m1-3x5) 3)) (is-true (equal (math/matr:dimensions m1-3x5) '(3 5))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def-test matrix-mref-test () "Проверка доступа к элементам матрицы." (with-fixture fix-<matrix>-m1-3x5 () (is-true (= (math/matr:mref m1-3x5 0 0 ) 11)) (is-true (= (math/matr:mref m1-3x5 0 1 ) 12)) (is-true (= (math/matr:mref m1-3x5 0 2 ) 13)) (is-true (= (math/matr:mref m1-3x5 0 3 ) 14)) (is-true (= (math/matr:mref m1-3x5 0 4 ) 15)) ;;;; (is-true (= (math/matr:mref m1-3x5 1 0 ) 21)) (is-true (= (math/matr:mref m1-3x5 1 1 ) 22)) (is-true (= (math/matr:mref m1-3x5 1 2 ) 23)) (is-true (= (math/matr:mref m1-3x5 1 3 ) 24)) (is-true (= (math/matr:mref m1-3x5 1 4 ) 25)) ;;;; (is-true (= (math/matr:mref m1-3x5 2 0 ) 31)) (is-true (= (math/matr:mref m1-3x5 2 1 ) 32)) (is-true (= (math/matr:mref m1-3x5 2 2 ) 33)) (is-true (= (math/matr:mref m1-3x5 2 3 ) 34)) (is-true (= (math/matr:mref m1-3x5 2 4 ) 35)))) (def-test matrix-mref-set-test () "Проверка доступа к элементам матрицы." (with-fixture fix-<matrix>-m1-3x5 () (setf (math/matr:mref m1-3x5 0 0) -11 (math/matr:mref m1-3x5 0 1) -12 (math/matr:mref m1-3x5 0 2) -13 (math/matr:mref m1-3x5 0 3) -14 (math/matr:mref m1-3x5 0 4) -15 ;;;; (math/matr:mref m1-3x5 1 0) -21 (math/matr:mref m1-3x5 1 1) -22 (math/matr:mref m1-3x5 1 2) -23 (math/matr:mref m1-3x5 1 3) -24 (math/matr:mref m1-3x5 1 4) -25 ;;;; (math/matr:mref m1-3x5 2 0) -31 (math/matr:mref m1-3x5 2 1) -32 (math/matr:mref m1-3x5 2 2) -33 (math/matr:mref m1-3x5 2 3) -34 (math/matr:mref m1-3x5 2 4) -35) (is-true (= (math/matr:mref m1-3x5 0 0 ) -11)) (is-true (= (math/matr:mref m1-3x5 0 1 ) -12)) (is-true (= (math/matr:mref m1-3x5 0 2 ) -13)) (is-true (= (math/matr:mref m1-3x5 0 3 ) -14)) (is-true (= (math/matr:mref m1-3x5 0 4 ) -15)) ;;;; (is-true (= (math/matr:mref m1-3x5 1 0 ) -21)) (is-true (= (math/matr:mref m1-3x5 1 1 ) -22)) (is-true (= (math/matr:mref m1-3x5 1 2 ) -23)) (is-true (= (math/matr:mref m1-3x5 1 3 ) -24)) (is-true (= (math/matr:mref m1-3x5 1 4 ) -25)) ;;;; (is-true (= (math/matr:mref m1-3x5 2 0 ) -31)) (is-true (= (math/matr:mref m1-3x5 2 1 ) -32)) (is-true (= (math/matr:mref m1-3x5 2 2 ) -33)) (is-true (= (math/matr:mref m1-3x5 2 3 ) -34)) (is-true (= (math/matr:mref m1-3x5 2 4 ) -35)))) (def-test matrix-equivalent-test () "Проверка эквивалентности матриц." (with-fixture fix-<matrix>-m1-3x5 () (with-fixture fix-<matrix>-m2-3x5 () (with-fixture fix-a1-a2-a3-a4-2x2 () (is-true (math/matr:equivalent m1-3x5 m2-3x5)) (is-true (math/matr:equivalent m2-3x5 m1-3x5)) (is-true (math/matr:equivalent a1 a2)) (is-false (math/matr:equivalent a1 a2 :test #'equal)) (is-true (math/matr:equivalent a1 a3)) (is-false (math/matr:equivalent a1 a4)) (is-true (math/matr:equivalent (make-instance 'math/matr:<matrix> :data a1) (make-instance 'math/matr:<matrix> :data a2))) (is-true (math/matr:equivalent (make-instance 'math/matr:<matrix> :data a1) (make-instance 'math/matr:<matrix> :data a3))) (is-false (math/matr:equivalent (make-instance 'math/matr:<matrix> :data a1) (make-instance 'math/matr:<matrix> :data a4))))))) (def-test matrix-get-row () "Проверка доступа к строкам." (with-fixture fix-<matrix>-m1-3x5 () (is-true (equal (math/matr:row m1-3x5 0) '(11 12 13 14 15))) (is-true (equal (math/matr:row m1-3x5 1) '(21 22 23 24 25))) (is-true (equal (math/matr:row m1-3x5 2) '(31 32 33 34 35)))) ) (def-test matrix-set-row-tests () "Пример использования: (test-matrix-set-row)" (with-fixture fix-<matrix>-m1-3x5 () (let ((m-cp (math/matr:copy m1-3x5))) (setf (math/matr:row m-cp 0) '(1 2 3 4 5) (math/matr:row m-cp 2) '(5 4 3 2 1)) (is-true (math/matr:equivalent (make-instance 'math/matr:<matrix> :initial-contents '(( 1 2 3 4 5) (21 22 23 24 25) ( 5 4 3 2 1))) m-cp)) (is-false (math/matr:equivalent m1-3x5 m-cp)) (is-true (equal (math/matr:row m-cp 0) '(1 2 3 4 5))) (is-true (equal (math/matr:row m-cp 2) '(5 4 3 2 1)))))) (def-test matrix-get-col-test () "Проверка доступа к столбцам." (with-fixture fix-<matrix>-m1-3x5 () (is-true (equal (math/matr:col m1-3x5 0) '(11 21 31))) (is-true (equal (math/matr:col m1-3x5 1) '(12 22 32))) (is-true (equal (math/matr:col m1-3x5 2) '(13 23 33))) (is-true (equal (math/matr:col m1-3x5 3) '(14 24 34))) (is-true (equal (math/matr:col m1-3x5 4) '(15 25 35))))) (def-test matrix-set-col-test () "Пример использования" (with-fixture fix-<matrix>-m1-3x5 () (let ((m-cp (math/matr:copy m1-3x5))) (setf (math/matr:col m-cp 0) '(1 2 3) (math/matr:col m-cp 4) '(3 2 1)) (is-true (math/matr:equivalent (make-instance 'math/matr:<matrix> :initial-contents '(( 1 12 13 14 3) ( 2 22 23 24 2) ( 3 32 33 34 1))) m-cp)) (is-false (math/matr:equivalent m1-3x5 m-cp)) (is-true (equal (math/matr:col m-cp 0) '(1 2 3 )))))) (def-test matrix-main-diagonal-test () "Проверка извлечения элементов главной диагонали." (let ((m-3x5 (make-<matrix>-int 3 5)) (m-5x5 (make-<matrix>-int 5 5)) (m-5x3 (make-<matrix>-int 5 3))) (is-true (equal (math/matr:main-diagonal m-3x5) '(11 22 33))) (is-true (equal (math/matr:main-diagonal m-5x5) '(11 22 33 44 55))) (is-true (equal (math/matr:main-diagonal m-5x3) '(11 22 33))))) (def-test matrix-squarep-test () "Проверка матрицы на квадратность." (is-true (math/matr:squarep (make-<matrix>-int 1 1))) (is-true (math/matr:squarep (make-<matrix>-int 2 2))) (is-false (math/matr:squarep (make-<matrix>-int 1 2))) (is-true (math/matr:squarep (make-<matrix>-int 3 3))) (is-false (math/matr:squarep (make-<matrix>-int 3 5))) (is-false (math/matr:squarep (make-<matrix>-int 5 3)))) (def-test matrix-main-diagonal-set-test () "Пример использования: (test-main-diagonal-set)" (let ((m-3x5 (make-<matrix>-int 3 5)) (m-5x3 (make-<matrix>-int 5 3)) (m-5x5 (make-<matrix>-int 5 5)) (m-3x5-d (make-instance 'math/matr:<matrix> :initial-contents '(( 1 12 13 14 15) (21 2 23 24 25) (31 32 3 34 35)))) (m-5x3-d (make-instance 'math/matr:<matrix> :initial-contents '(( 1 12 13 ) (21 2 23 ) (31 32 3 ) (41 42 43 ) (51 52 53 )))) (m-5x5-d (make-instance 'math/matr:<matrix> :initial-contents '(( 1 12 13 14 15) (21 2 23 24 25) (31 32 3 34 35) (41 42 43 4 45) (51 52 53 54 5))))) (setf (math/matr:main-diagonal m-3x5) '(1 2 3) (math/matr:main-diagonal m-5x3) '(1 2 3) (math/matr:main-diagonal m-5x5) '(1 2 3 4 5)) (is-true (math/matr:equivalent m-3x5 m-3x5-d)) (is-true (math/matr:equivalent m-5x3 m-5x3-d)) (is-true (math/matr:equivalent m-5x5 m-5x5-d)))) (def-test matrix-anti-diagonal-test () "Проверка операций с побочной диагональю." (let* ((m-5x5 (make-<matrix>-int 5 5)) (m-5x5-d (make-instance 'math/matr:<matrix> :initial-contents '((11 12 13 14 1) (21 22 23 2 25) (31 32 3 34 35) (41 4 43 44 45) ( 5 52 53 54 55))))) (is-true (equal (math/matr:anti-diagonal m-5x5) '(15 24 33 42 51))) (is-true (setf (math/matr:anti-diagonal m-5x5) '(1 2 3 4 5))) (is-true (math/matr:equivalent m-5x5 m-5x5-d)))) (def-test matrix-add-tests () "Проверка операций сложения." (is-true (math/matr:equivalent (math/matr:add (math/matr:matr-new 2 2 '(1 2 3 4)) (math/matr:matr-new 2 2 '(1 2 3 4))) (math/matr:matr-new 2 2 '(2 4 6 8)))) (is-true (math/matr:equivalent (math/matr:add (math/matr:matr-new 2 2 '(1 2 3 4)) (math/matr:matr-new 2 2 '(4 3 2 1))) (math/matr:matr-new 2 2 '(5 5 5 5 ))))) (def-test matrix-multiply-tests () "Проверка опрераций умножения." (is-true (math/matr:equivalent (math/matr:multiply (math/matr:matr-new 2 3 '(1.0 2.0 3.0 4.0 5.0 6.0)) (math/matr:matr-new 3 2 '(1.0 2.0 3.0 4.0 5.0 6.0))) (math/matr:matr-new 2 2 '(22.0 28.0 49.0 64.0)))) (is-true (math/matr:equivalent (math/matr:multiply (math/matr:matr-new 3 2 '(1.0 2.0 3.0 4.0 5.0 6.0)) (math/matr:matr-new 2 3 '(1.0 2.0 3.0 4.0 5.0 6.0))) (math/matr:matr-new 3 3 '( 9.0 12.0 15.0 19.0 26.0 33.0 29.0 40.0 51.0 )))) (is-true (math/matr:equivalent (math/matr:multiply 2 (math/matr:matr-new 3 2 '(1.0 2.0 3.0 4.0 5.0 6.0))) (math/matr:matr-new 3 2 '(2.0 4.0 6.0 8.0 10.0 12.0))))) (def-test matrix-transpose-tests () "Проверка операции транспонирования." (is-true (math/matr:transpose (math/matr:matr-new 2 3 '(11 12 13 21 22 23))) (math/matr:matr-new 3 2 '(11 21 12 22 13 23))) (is-true (equal (math/matr:transpose '((1 2) (3 4) (5 6))) '((1 3 5) (2 4 6))))) (def-test matrix->2d-list-tests () "Пример использования: (test-matrix->2d-list)" (is-true (equal (math/matr:matrix->2d-list (math/matr:matr-new 3 2 '(1 2 3 4 5 6))) '((1 2) (3 4) (5 6))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
11,709
Common Lisp
.lisp
270
36.37037
108
0.579813
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
771f3ff27099b3908276416f2f501d74a7914c131a2647cdb913312851261bcc
11,059
[ -1 ]
11,060
core.lisp
mnasoft_math/src/tests/core.lisp
;;;; ./math/src/tests/core.lisp (in-package :math/tests) (def-suite core :description "Мастер-набор всех тестов math/core." :in all) (in-suite core) #+nil ((math/core:roots (make-instance 'math/core:<linear> :a 1d0 :b -1d0)) (math/core:roots (make-instance 'math/core:<quadric> :a 1d0 :b -3d0 :c 2d0)) (math/core:roots (make-instance 'math/core:<cubic> :a 1d0 :b -6d0 :c 11d0 :d -6d0)) (math/core:roots (make-instance 'math/core:<quartic> :a 1 :b -10 :c 35 :d -50 :e 24))) (def-test norma () (is-true (= 0 (math/core:norma 0))) (is-true (= 100 (math/core:norma 100))) (is-true (= 100e0 (math/core:norma 100e0))) (is-true (= 100d0 (math/core:norma 100d0))) (is-true (= 2.236068 (math/core:norma #C(1 2)) (math/core:norma #C(2 1)) (math/core:norma #C(-1 2)) (math/core:norma #C(-2 1)))) (is-true (= 3/2 (math/core:norma '(-2 1)) (math/core:norma '(-1 2)))) (is-true (= 2 (math/core:norma '(1 2 3)) (math/core:norma '(-1 2 -3)))) (is-true (= 2.868034 (math/core:norma '(#C(1 2) #C(2 1) 2 5)) (math/core:norma '(#C(-1 2) #C(-2 1) -2 5))))) (def-test distance () "distance ()" (is-true (= 0 (math/core:distance 0 0))) (is-true (= 1 (math/core:distance 1 0))) (is-true (= 1 (math/core:distance -1 0))) (is-true (= 0e0 (math/core:distance 0e0 0e0))) (is-true (= 1e0 (math/core:distance 1e0 0e0))) (is-true (= 1e0 (math/core:distance -1e0 0e0))) (is-true (= 1e0 (math/core:distance -1e0 0e0))) (is-true (= 0.0 (math/core:distance '(1 2 3) '(1 2 3)))) (is-true (= 3.7416575 (math/core:distance '(2 4 6) '(1 2 3)))) (is-true (= 3.8729835 (math/core:distance '(#C(2 1) 4 6) '(#C(1 2) 2 3))))) (def-test distance-relative () "distance ()" (is-true (= 0 (math/core:distance-relative 0 0 10))) (is-true (= 0.1 (math/core:distance-relative 1 0 10))) (is-true (= 0.1 (math/core:distance-relative -1 0 10))) (is-true (= 0.0 (math/core:distance-relative 0e0 0e0 10))) (is-true (= 0.2 (math/core:distance-relative 1e0 0e0 5))) (is-true (= 0.1 (math/core:distance-relative -1e0 0e0 10))) (is-true (= 0.2 (math/core:distance-relative -1e0 0e0 5)))) (def-test semi-equal () "def-test semi-equal ()" (is-true (math/core:semi-equal 1.0 2.0 :tolerance 1.001)) (is-true (math/core:semi-equal 1.0 2.0 :tolerance 1.000001)) (is-false (math/core:semi-equal 1.0 1.1)) (is-false (math/core:semi-equal 1.0 1.01)) (is-false (math/core:semi-equal 1.0 1.001)) (is-false (math/core:semi-equal 1.0 1.0001)) (is-false (math/core:semi-equal 1.0 1.00001)) (is-true (math/core:semi-equal 1.0 1.000001)) (is-true (math/core:semi-equal 1.0 1.0000001)) )
2,766
Common Lisp
.lisp
62
39.741935
87
0.596636
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
1606b450564cfc447ee3da2f9a75ca213c0da99050f661ea4d20b3f5d71e81e4
11,060
[ -1 ]
11,061
all.lisp
mnasoft_math/src/tests/all.lisp
;;;; tests/main.lisp (in-package :math/tests) (def-suite all :description "Мастер-набор всех тестов проекта math.") (in-suite all) #+nil (defun test-math () (run! 'all-tests)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; #| (require :sb-cover) (require :math/tests) (declaim (optimize sb-cover:store-coverage-data)) (asdf:oos 'asdf:load-op :math/tests :force t) (sb-cover:report "coverage/") |#
488
Common Lisp
.lisp
14
31.214286
100
0.555809
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
0e1ebddee41197f6ec592bb86bdbc5cc86eb48f1f98e2442bdbde25949bc846f
11,061
[ -1 ]
11,062
equation.lisp
mnasoft_math/src/tests/equation.lisp
;;;; ./math/src/tests/equation.lisp (in-package :math/tests) (def-suite equation :description "Мастер-набор всех тестов math/equation." :in all) (in-suite equation) #+nil ( (math/equation:roots (make-instance 'math/equation:<linear> :a 1d0 :b -1d0)) (math/equation:roots (make-instance 'math/equation:<quadric> :a 1d0 :b -3d0 :c 2d0)) (math/equation:roots (make-instance 'math/equation:<cubic> :a 1d0 :b -6d0 :c 11d0 :d -6d0)) (math/equation:roots (make-instance 'math/equation:<quartic> :a 1 :b -10 :c 35 :d -50 :e 24)) ) (def-test equation-linear-coeffs () "def-test equation-linear-coeffs ()" (let ((linear (make-instance 'math/equation:<linear> :a 1d0 :b -1d0))) (is-true (equalp (math/equation:coeff-a linear) 1d0)) (is-true (equalp (math/equation:coeff-b linear) -1d0)) ;;;; tab (is-true (math/core:semi-equal (math/equation:tab linear 1d0) 0d0)) (is-false (math/core:semi-equal (math/equation:tab linear 0.5d0) 0d0)) (is-false (math/core:semi-equal (math/equation:tab linear 1.5d0) 0d0)) ;;;; roots (is-true (math/core:semi-equal (math/equation:roots linear) 1d0)) )) (def-test equation-quadric-coeffs () "def-test equation-quadric-coeffs ()" (let ((quadric (make-instance 'math/equation:<quadric> :a 1d0 :b -3d0 :c 2d0))) (is-true (equalp (math/equation:coeff-a quadric) 1d0)) (is-true (equalp (math/equation:coeff-b quadric) -3d0)) (is-true (equalp (math/equation:coeff-c quadric) 2d0)) ;;tab (is-true (math/core:semi-equal (math/equation:tab quadric 1d0) 0d0)) (is-true (math/core:semi-equal (math/equation:tab quadric 2d0) 0d0)) (is-false (math/core:semi-equal (math/equation:tab quadric 0.5d0) 0d0)) (is-false (math/core:semi-equal (math/equation:tab quadric 1.5d0) 0d0)) (is-false (math/core:semi-equal (math/equation:tab quadric 2.5d0) 0d0)) ;;;; roots (is-true (math/core:semi-equal (sort (math/equation:roots quadric) #'<) '(1 2))))) (def-test equation-cubic-coeffs () "def-test equation-cubic-coeffs ()" (let ((cubic (make-instance 'math/equation:<cubic> :a 1d0 :b -6d0 :c 11d0 :d -6d0))) (is-true (equalp (math/equation:coeff-a cubic) 1d0)) (is-true (equalp (math/equation:coeff-b cubic) -6d0)) (is-true (equalp (math/equation:coeff-c cubic) 11d0)) (is-true (equalp (math/equation:coeff-d cubic) -6d0)) ;;;; tab (is-true (math/core:semi-equal (math/equation:tab cubic 1d0) 0d0)) (is-true (math/core:semi-equal (math/equation:tab cubic 2d0) 0d0)) (is-true (math/core:semi-equal (math/equation:tab cubic 3d0) 0d0)) (is-false (math/core:semi-equal (math/equation:tab cubic 0.5d0) 0d0)) (is-false (math/core:semi-equal (math/equation:tab cubic 1.5d0) 0d0)) (is-false (math/core:semi-equal (math/equation:tab cubic 2.5d0) 0d0)) (is-false (math/core:semi-equal (math/equation:tab cubic 3.5d0) 0d0)) (is-false (math/core:semi-equal (math/equation:tab cubic 4.5d0) 0d0)) ;;;; roots (is-true (math/core:semi-equal (sort (math/equation:roots cubic) #'< :key #'math/core:norma) '(1 2 3))))) (def-test equation-quartic-coeffs () "def-test equation-quartic-coeffs ()" (let ((quartic (make-instance 'math/equation:<quartic> :a 1 :b -10 :c 35 :d -50 :e 24))) (is-true (equalp (math/equation:coeff-a quartic) 1d0)) (is-true (equalp (math/equation:coeff-b quartic) -10d0)) (is-true (equalp (math/equation:coeff-c quartic) 35d0)) (is-true (equalp (math/equation:coeff-d quartic) -50d0)) (is-true (equalp (math/equation:coeff-e quartic) 24d0)) ;;;; tab (is-true (math/core:semi-equal (math/equation:tab quartic 1d0) 0d0)) (is-true (math/core:semi-equal (math/equation:tab quartic 2d0) 0d0)) (is-true (math/core:semi-equal (math/equation:tab quartic 3d0) 0d0)) (is-true (math/core:semi-equal (math/equation:tab quartic 4d0) 0d0)) (is-false (math/core:semi-equal (math/equation:tab quartic 1.5d0) 0d0)) (is-false (math/core:semi-equal (math/equation:tab quartic 2.5d0) 0d0)) (is-false (math/core:semi-equal (math/equation:tab quartic 3.5d0) 0d0)) (is-false (math/core:semi-equal (math/equation:tab quartic 4.5d0) 0d0)) (is-false (math/core:semi-equal (math/equation:tab quartic 5.5d0) 0d0)) ;;;; roots #+nil (is-true (math/core:semi-equal (sort (math/equation:roots quartic) #'< :key #'math/core:norma) '(1 2 3 4)))))
4,432
Common Lisp
.lisp
82
49.402439
94
0.674004
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
16a270ad6fe573ebbb10823dde1faea46d3514d1808680abc5f6ac03d02dd314
11,062
[ -1 ]
11,063
appr.lisp
mnasoft_math/src/tests/appr.lisp
;;;; tests/approximation-tests.lisp (in-package :math/tests) (def-suite appr :description "Мастер-набор тестов по решению СЛАУ (систем линейных плгебраических уравнений." :in all) (in-suite appr) (def-test approximation-make-least-squares-matrix-test () "Пример использования: (test-matr-mnk)" (let* ((m1 (make-instance 'math/matr:<matrix> :initial-contents '(( 98.0d0 34.0d0 14.0d0 98.0d0 ) ( 34.0d0 14.0d0 4.0d0 34.0d0 ) ( 14.0d0 4.0d0 4.0d0 14.0d0 )))) (pts-1 '((-1.0 1.0) (0.0 0.0) (2.0 4.0) (3.0 9.0))) (m2 (make-instance 'math/matr:<matrix> :initial-contents '(( 225.0d0 75.0d0 75.0d0 25.0d0 931.25d0 ) ( 75.0d0 75.0d0 25.0d0 25.0d0 606.25d0 ) ( 75.0d0 25.0d0 75.0d0 25.0d0 631.25d0 ) ( 25.0d0 25.0d0 25.0d0 25.0d0 406.25d0 )))) (ff-2 #'(lambda (x1 x2) (+ (* 1/2 x1 x1 ) (* 1/4 x2 x2 ) (* 1 x1 x2 ) (* 2 x1) (* 3 x2) 8.0))) (pts-2 (let ((rez nil)) (loop :for x1 :from -1 :to 3 :do (loop :for x2 :from -1 :to 3 :do (push (list x1 x2 (funcall ff-2 x1 x2)) rez ))) rez))) (is-true (math/matr:equivalent m1 (math/appr:make-least-squares-matrix '(xx yy) '((xx xx) (xx) (1.0) (yy)) pts-1 ))) (is-true (math/matr:equivalent m2 (math/appr:make-least-squares-matrix '(x1 x2 yy) '((x1 x2) (x1) (x2) (1.0) (yy)) pts-2))))) (def-test averaging-function-tests () "Пример использования: (test-averaging-function)" (is-true (equal '((xx) (+ (* 1.0d0 xx xx) (* 0.0d0 xx) (* 0.0d0 1.0))) (math/appr::averaging-function-body '(xx yy) '((xx xx) (xx) (1.0) (yy)) '((-1.0 1.0) (0.0 0.0) (2.0 4.0) (3.0 9.0))))) (is-true (equal '(lambda (xx) (+ (* 1.0d0 xx xx) (* 0.0d0 xx) (* 0.0d0 1.0))) (math/appr:averaging-function-lambda '(xx yy) '((xx xx) (xx) (1.0) (yy)) '((-1.0 1.0) (0.0 0.0) (2.0 4.0) (3.0 9.0))))) (is-true (equal '(defun coool-func (xx) (+ (* 1.0d0 xx xx) (* 0.0d0 xx) (* 0.0d0 1.0))) (math/appr:averaging-function-defun '(xx yy) '((xx xx) (xx) (1.0) (yy)) '((-1.0 1.0) (0.0 0.0) (2.0 4.0) (3.0 9.0)) 'coool-func))))
2,490
Common Lisp
.lisp
65
29.738462
74
0.497624
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
03ce0e5cf8ecad608987e30d6609f2b515583275973b4609c4ac9f1295572902
11,063
[ -1 ]
11,064
half-div.lisp
mnasoft_math/src/half-div/half-div.lisp
;;;; ./src/half-div/half-div.lisp (defpackage :math/half-div (:use #:cl) (:export h-div) (:export h-div-lst) (:documentation "@b(Описание:) пакет @b( half-div) реализует алгоритм половинного деления для выполнения поиска корня функции на отрезке.")) (in-package :math/half-div) (defun boole-to-int (b) (if b 1 0)) (defun same-znak (a b) (if (zerop (logxor (boole-to-int (minusp a)) (boole-to-int (minusp b)))) t nil)) (defun epsylon (x &key (eps 1e-6)) "Функция для вычисления комплексной точности." (+ (* (abs x) eps ) eps)) (defun h-div (a b func &key (eps 1e-6) (iters 1000)) "@b(Описание:) функция @b(h-div) возвращает результат решения уравнения func(x)=0 методом половинного деления. Поиск решения выполняется на отрезке [a,b]. @b(Переменые:) @begin(list) @item(a - левая граница отрезка;) @item(b - правая граница отрезка;) @item(func - вид функциональной зависимости;) @item(eps - комплексная точность поиска решения;) @item(iters - максимальное количество итераций для достижения заданной точности.) @end(list) @b(Пример использования:) @begin[lang=lisp](code) (defun x2(x) (- (* x (log x)) 10000.)) (h-div 2.0 100000.0 #'x2 :iters 50) @end(code) " (do* ( (i 0 (1+ i)) (fa (funcall func a)) (fb (funcall func b)) (x (/ (+ a b) 2) (/ (+ a b) 2)) (fx (funcall func x)(funcall func x))) ((or (> i iters) (<= (abs(- b a)) (epsylon x :eps eps))) (values x (not (> i iters)) (abs(- b a)) (epsylon x :eps eps))) (if (same-znak fa fx) (setf a x fa fx) (setf b x fb fx)))) (defun h-div-lst (a b func n p_lst &key (eps 1e-6) (iters 1000)) "@b(Описание:) функция @b(h-div-lst) возвращает результат решения уравнения func(X[0],X[1],...,X[n],...,X[m])=0 методом половинного деления. Поиск решения выполняется на отрезке [a,b] для аргумента с номером n (первый аргумет имеет номер 0). @b(Переменые:) @begin(list) @item(a - левая граница отрезка;) @item(b - правая граница отрезка;) @item(func - вид функциональной зависимости;) @item(n - номер аргумента в списке аргументов функции при изменении которого на отрезке [a,b] выполняется поиск решения;) @item(p_lst - список аргуметов функции;) @item(eps - комплексная точность поиска решения;) @item(iters - максимальное количество итераций для достижения заданной точности.) @end(list) @b(Пример использования:) @begin[lang=lisp](code) (defun xy2(x y) (- (* x (log x)) y)) (h-div-lst 2.0 100000.0 #'xy2 0 '(t 10000.) :iters 50) @end(code)" (labels ((subst-by-no (lst el position) (substitute el (nth position lst) lst :start position))) (do* ( (i 0 (1+ i)) (fa (apply func (subst-by-no p_lst a n))) (fb (apply func (subst-by-no p_lst b n))) (x (/ (+ a b) 2) (/ (+ a b) 2)) (fx (apply func (subst-by-no p_lst x n)) (apply func (subst-by-no p_lst x n)))) ((or (> i iters) (<= (abs(- b a)) (epsylon x :eps eps))) (values x (not (> i iters)) (abs(- b a)) (epsylon x :eps eps))) (if (same-znak fa fx) (setf a x fa fx) (setf b x fb fx)))))
4,049
Common Lisp
.lisp
99
28.060606
82
0.62333
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
70c56ef2ff3cdbd1dcb4b1d9d19b295edada2d10f1f46191875877a91b9af901
11,064
[ -1 ]
11,065
coord.lisp
mnasoft_math/src/coord/coord.lisp
;;;; ./src/coord/coordinate-system.lisp (defpackage :math/coord (:use #:cl #:math/core) (:export dtr rtd polar->cartesian cartesian->polar spherical->cartesian cartesian->spherical ) (:export point-3d->4d point-4d->3d ) (:export double-float-list single-float-list ) (:documentation "coord")) (in-package :math/coord) (defun dtr (degree) "@b(Описание:) функция @b(dtr) переводит значение, заданное в градусах, в радианы. @b(Пример использования:) @begin[lang=lisp](code) (dtr (rtd 1/2)) => 0.5d0 @end(code) " (* pi 1/180 degree )) (defun rtd (radian) "@b(Описание:) функция @b(rtd) переводит значение, заданное в радианах, в градусы. @b(Пример использования:) @begin[lang=lisp](code) (rtd (dtr 45)) => 45.0d0 @end(code) " (/ radian pi 1/180)) (defun polar->cartesian (radius-angle) "@b(Описание:) функция @b(polar->cartesian) переводит полярные координаты в декартовы. @b(Переменые:) @begin(list) @item(radius-angle - список, состоящий из двух элементов: радиус-вектора и угла, заданного в радианах.) @end(list) @b(Пример использования:) @begin[lang=lisp](code) (polar->cartesian `(10.0 ,(dtr 45))) => (7.0710678118654755d0 7.071067811865475d0) @end(code) " (let ((radius (first radius-angle)) (angle (second radius-angle))) (list (* radius (cos angle)) (* radius (sin angle))))) (defun cartesian->polar (x-y) "@b(Описание:) функция @b(cartesian->polar) переводит декартовы координаты в полярные. @b(Переменые:) @begin(list) @item(radius-angle - список, состоящий из двух элементов: радиус-вектора и угла, заданного в радианах.) @end(list) @b(Пример использования:) @begin[lang=lisp](code) (cartesian->polar (list 10.0 10)) (14.142136 0.7853982) @end(code) " (let ((radius (sqrt (apply #'+ (mapcar #'square x-y)))) (angle (atan (second x-y) (first x-y)))) (list radius angle))) (defun spherical->cartesian (r-φ-θ) "@b(Описание:) функция @b(spherical->cartesian) выполняет преобразование координат из сферических в декартовы. @b(Переменые:) @begin(list) @item(r-φ-θ - список состоящий из трех величин: @begin(list) @item(r - расстояние от начала координат до заданной точки;) @item(φ - азимутальный угол (в плоскости X0Y);) @item(θ - зенитный угол.) @end(list)) @end(list) @b(Пример использования:) @begin[lang=lisp](code) (spherical->cartesian `(100 ,(dtr 30) ,(dtr 45))) => (61.237243569579455d0 35.35533905932737d0 70.71067811865476d0) @end(code) " (let ((r (first r-φ-θ)) (φ (second r-φ-θ)) (θ (third r-φ-θ))) (let ((x (* r (cos φ) (sin θ))) (y (* r (sin φ) (sin θ))) (z (* r (cos θ)))) (list x y z)))) (defun cartesian->spherical (x-y-z) "@b(Описание:) функция @b(cartesian->spherical) выполняет преобразование координат из декартовых в сферические. @b(Переменые:) @begin(list) @item(x-y-z - список, содержащий соответствующие координаты.) @end(list) @b(Пример использования:) @begin[lang=lisp](code) (cartesian->spherical '(61.237243569579455d0 35.35533905932737d0 70.71067811865476d0)) =>(100.0d0 0.5235987755982988d0 0.7853981633974483d0) @end(code) " (let* ((x (first x-y-z)) (y (second x-y-z)) (z (third x-y-z)) (r (sqrt (apply #'+ (mapcar #'square x-y-z)))) (φ (atan y x)) (θ (atan (sqrt (+ (* x x) (* y y))) z))) (list r φ θ))) (defun point-3d->4d (point-3d &optional (coord-4 1.0d0)) "@b(Описание:) функция @b(point-3d->4d) возвращает координаты точки @b(point-3d) в однородных координатах, добавляя к ним четвертую координату @b(coord-4). @b(Пример использования:) @begin[lang=lisp](code) (point-3d->4d '(1.0 2.0 3.0)) => (1.0 2.0 3.0 0.0d0) (point-3d->4d '(1.0 2.0 3.0) 0.0) => (1.0 2.0 3.0 0.0) @end(code)" (let ((point-4d (nreverse(copy-list point-3d)))) (nreverse (push coord-4 point-4d)))) (defun point-4d->3d (point-4d) "@b(Описание:) функция @b(point-4d->3d) преобразует координаты точки @b(point-4d) из однородных в 3d и возвращает последние. @b(Пример использования:) @begin[lang=lisp](code) (point-4d->3d '(1.0 2.0 3.0 0.0d0)) => (1.0 2.0 3.0) @end(code)" (loop :for i :from 0 :to 2 :for coord :in point-4d :collect coord)) (defun double-float-list (list) (loop :for i :in list :collect (coerce i 'double-float))) (defun single-float-list (list) (loop :for i :in list :collect (coerce i 'single-float)))
5,486
Common Lisp
.lisp
137
29.20438
88
0.661556
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
aace3f900b33be4a69b22af356bfa0f6d07d8aff8951a46b2745cef39b5ef4af
11,065
[ -1 ]
11,066
math.lisp
mnasoft_math/src/math/math.lisp
;;;; package.lisp (defpackage :math (:use #:cl) ;;#:math/core (:export mult-matr-vect)) (in-package :math) (defun mult-matr-vect (matr vect) "@b(Описание:) функция @b(mult-matr-vect) возвращает вектор, являющийся результатом умножения матрицы @b(matr) на вектор @b(vect). Количество элементов в результирующем векторе равно количеству элементов в векторе @b(vect). @b(Пример использования:) @begin[lang=lisp](code) (defparameter *m-test* (make-array '(3 4) :initial-contents '((10.0d0 11.0d0 12.0d0 4.0d0) (15.0d0 17.0d0 21.0d0 2.0d0) (70.0 8.0 10.0 3.0)))) (mult-matr-vect *m-test* ; Проверка правильности решения (системы линейных алгебраических уравнений) СЛАУ (solve-linear-system-rotation (cl-utilities:copy-array *m-test*))) @end(code) " (let* ((n (array-dimension vect 0)) (vect-rez (make-array n :initial-element 0.0d0))) (do ((i 0 (1+ i))) ((= i n) (values vect-rez matr vect )) (do ((j 0 (1+ j)) (summ 0.0d0)) ((= j n) (setf (aref vect-rez i) summ)) (setf summ (+ summ (* (aref matr i j ) (aref vect j))))))))
1,331
Common Lisp
.lisp
32
31.03125
90
0.660038
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
282da8b034d1561367dc030981bf5e5d3a488c95745a8d2d97933fb8ef72a7b0
11,066
[ -1 ]
11,067
appr.lisp
mnasoft_math/src/appr/appr.lisp
;;;; ./appr/package.lisp (defpackage :math/appr (:use #:cl) ;;#:math/matr (:export refine-smoothing-by-points smooth-by-points approximate appr-table averaging-function-lambda averaging-function-defun ) (:export make-approximation-defun make-linear-interpolation make-appr-linear make-least-squares-matrix make-refine-smoothing make-approximation-lambda ) (:export <appr-linear> appr-linear-x1 appr-linear-a1d-func ) (:export <appr-bilinear> appr-bilinear-a2d-func appr-bilinear-x1 appr-bilinear-x2 ) (:export *apr-args-1* *apr-args-2* ) (:export *apr-func-1-2* *apr-func-1-3* *apr-func-1-4* *apr-func-1-5* ) (:export *apr-func-2-4* *apr-func-2-5* *apr-func-2-6* *apr-func-2-8* *apr-func-2-7* *apr-func-2-9* )) (in-package :math/appr) ;;;; appr-func-temptate.lisp (defparameter *apr-args-1* '(x1 yy) "Аргументы для функции одного параметра. @begin[lang=lisp](code) '(x1 yy) @end(code)") (defparameter *apr-args-2* '(x1 x2 yy) "Аргументы для функции двух параметров. @begin[lang=lisp](code) '(x1 x2 yy) @end(code) ") (defparameter *apr-func-1-2* '((x1) (1.0) (yy)) "Шаблон для построения линейной функции одного параметра: x1 с двумя коэффициентами. @begin[lang=lisp](code) '((x1) (1.0) (yy)) @end(code) @begin[lang=scribe](code) yy(x@sub(1))=a·x@sub(1)+b @end(code)") (defparameter *apr-func-1-3* '((x1 x1) (x1) (1.0) (yy)) "Шаблон для построения квадратичной функции одного параметра: x1 c тремя коэффициентами. @begin[lang=lisp](code) '((x1 x1) (x1) (1.0) (yy)) @end(code) @begin[lang=scribe](code) yy(x@sub(1))=a·x@sub(1)@sup(2)+b·x@sub(1)+c @end(code)") (defparameter *apr-func-1-4* '((x1 x1 x1) (x1 x1) (x1) (1.0) (yy)) "Шаблон для построения квадратичной функции одного параметра: x1 c четырьмя коэффициентами. @begin[lang=lisp](code) '((x1 x1 x1) (x1 x1) (x1) (1.0) (yy)) @end(code) @begin[lang=scribe](code) yy(x@sub(1))=a·x@sub(1)@sup(3)+b·x@sub(1)@sup(2)+c·x@sub(1)+d @end(code)") (defparameter *apr-func-1-5* '((x1 x1 x1 x1) (x1 x1 x1) (x1 x1) (x1) (1.0) (yy)) "Шаблон для построения квадратичной функции одного параметра: x1 c пятью коэффициентами. @begin[lang=lisp](code) '((x1 x1 x1 x1) (x1 x1 x1) (x1 x1) (x1) (1.0) (yy)) @end(code) @begin[lang=scribe](code) yy(x@sub(1))=a·x@sub(1)@sup(4)+b·x@sub(1)@sup(3)+c·x@sub(1)@sup(2)+d·x@sub(1)+e @end(code) ") (defparameter *apr-func-2-4* '((x1 x2) (x1) (x2) (1.0) (yy)) "@b(Описание:) *apr-func-2-4* шаблон для построения функции двух параметров: x1 и x2 c четырьмя коэффициентами. @begin[lang=lisp](code) '((x1 x2) (x1) (x2) (1.0) (yy)) @end(code) @begin[lang=scribe](code) yy(x@sub(1))=a@sub(1)·x@sub(1)·x@sub(2)+a@sub(2)·x@sub(1)+a@sub(3)·x@sub(2)+a@sub(4) @end(code)") (defparameter *apr-func-2-5* '((x1 x1) (x2 x2) (x1) (x2) (1.0) (yy)) "@b(Описание:) *apr-func-2-5* шаблон для построения функции двух параметров: x1 и x2 c пятью коэффициентами. @begin[lang=lisp](code) '((x1 x1) (x2 x2) (x1) (x2) (1.0) (yy)) @end(code) @begin[lang=scribe](code) yy(x@sub(1))=a@sub(1)·x@sub(1)@sup(2)+a@sub(2)·x@sub(2)@sup(2)+a@sub(3)·x@sub(1)+a@sub(4)·x@sub(2)+a@sub(5) @end(code)") (defparameter *apr-func-2-6* '((x1 x1) (x2 x2) (x1 x2) (x1) (x2) (1.0) (yy)) "@b(Описание:) *apr-func-2-6* шаблон для построения функции двух параметров: x1 и x2 c шестью коэффициентами. @begin[lang=lisp](code) '((x1 x1) (x2 x2) (x1 x2) (x1) (x2) (1.0) (yy)) @end(code) @begin[lang=scribe](code) yy(x@sub(1))=a@sub(1)·x@sub(1)@sup(2)+a@sub(2)·x@sub(2)@sup(2)+a@sub(3)·x@sub(1)·x@sub(2)+a@sub(5)·x@sub(1)+a@sub(6)·x@sub(2)+a@sub(7) @end(code)") (defparameter *apr-func-2-7* '((x1 x1 x2) (x1 x2 x2) (x1 x1) (x2 x2) (x1) (x2) (1.0) (yy)) "@b(Описание:) *apr-func-2-7* шаблон для построения функции двух параметров: x1 и x2 c семью коэффициентами. @begin[lang=lisp](code) '((x1 x1 x2) (x1 x2 x2) (x1 x1) (x2 x2) (x1) (x2) (1.0) (yy)) @end(code) @begin[lang=scribe](code) yy(x@sub(1))=a@sub(1)·x@sub(1)@sup(2)·x@sub(2)+a@sub(2)·x@sub(1)·x@sub(2)@sup(2)+a@sub(3)·x@sub(1)@sup(2)+a@sub(4)·x@sub(2)@sup(2)+a@sub(5)·x@sub(1)+a@sub(6)·x@sub(2)+a@sub(7)@end(code)") (defparameter *apr-func-2-8* '((x1 x1 x2) (x1 x2 x2) (x1 x1) (x2 x2) (x1 x2) (x1) (x2) (1.0) (yy)) "@b(Описание:) *apr-func-2-8* шаблон для построения функции двух параметров: x1 и x2 c восемью коэффициентами. @begin[lang=lisp](code) '((x1 x1 x2) (x1 x2 x2) (x1 x1) (x2 x2) (x1 x2) (x1) (x2) (1.0) (yy)) @end(code) @begin[lang=scribe](code) yy(x@sub(1))=a@sub(1)·x@sub(1)@sup(2)·x@sub(2)+a@sub(2)·x@sub(1)·x@sub(2)@sup(2)+a@sub(3)·x@sub(1)@sup(2)+a@sub(4)·x@sub(2)@sup(2)+a@sub(5)·x@sub(1)·x@sub(2)+a@sub(6)·x@sub(1)+a@sub(7)·x@sub(2)+a@sub(8)@end(code)") (defparameter *apr-func-2-9* '((x1 x1 x2 x2) (x1 x1 x2) (x1 x2 x2) (x1 x1) (x2 x2) (x1 x2) (x1) (x2) (1.0) (yy)) "Шаблон для построения функции двух параметров: x1 и x2 c девятью коэффициентами. @begin[lang=lisp](code) '((x1 x1 x2 x2) (x1 x1 x2) (x1 x2 x2) (x1 x1) (x2 x2) (x1 x2) (x1) (x2) (1.0) (yy)) @end(code) @begin[lang=scribe](code) yy(x@sub(1))=a@sub(1)·x@sub(1)@sup(2)·x@sub(2)@sup(2)+ a@sub(2)·x@sub(1)@sup(2)·x@sub(2)+ a@sub(3)·x@sub(1)·x@sub(2)@sup(2)+ a@sub(4)·x@sub(1)@sup(2)+ a@sub(5)·x@sub(2)@sup(2)+ a@sub(6)·x@sub(1)·x@sub(2)+ a@sub(7)·x@sub(1)+ a@sub(8)·x@sub(2)+ a@sub(9) @end(code)") ;;;; approximation.lisp (defun appr-table (x table) "@b(Описание:) функция @b(appr-table) возвращает результат линейной интерполяции (или экстраполяции) для значения @b(x) на таблице @b(table). @b(Пример использования:) @begin[lang=lisp](code) (appr-table 0.5 '((0.0 0.0) (1.0 1.0) (2.0 4.0) (4.0 0.0))) => 0.5 (appr-table 1.5 '((0.0 0.0) (1.0 1.0) (2.0 4.0) (4.0 0.0))) => 2.5 (appr-table 3.0 '((0.0 0.0) (1.0 1.0) (2.0 4.0) (4.0 0.0))) => 2.0 Тест: (test-approximation-appr-table) @end(code) " (labels ((appr-line( XX PP0 PP1) (multiple-value-bind (x p0 p1) (values XX PP0 PP1) (+ (second p0) (/ (* (- x (first p0)) (- (second p1) (second p0))) (- (first p1) (first p0)))))) (appr-line-list( XX n0 n1 lst) (appr-line XX (nth n0 lst) (nth n1 lst)))) (do ((len (length table)) (res nil) (i 0 (1+ i))) ((>= i len) (appr-line-list x (first res) (second res ) table)) (cond ((and (null res) (<= x (first (nth 0 table)))) (setf res '(0 1))) ((and (null res) (<= (first (nth (1- len) table)) x)) (setf res (list (- len 2) (- len 1)))) ((and (null res) (<= (first(nth i table)) x) (<= x (first(nth (1+ i) table)))) (setf res (list i (1+ i)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Аппроксимационные полиномиальные зависимости функции нескольких переменных. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun make-least-squares-matrix (vv ff ex_pts) "@b(Описание:) функция @b(make-least-squares-matrix) возвращает матрицу для расчета коэффициентов полиномиальной зависимости вида @b(ff) со списком имен факторов влияния и имени функции отклика @b(vv), которая приближается к экспериментальным точкам @b(ex_pts), методом наименьших квадратов. @b(Переменые:) @begin(list) @item(vv - список, состоящий из имен факторов влияния и имени функции отклика;) @item(ff - задает вид функциональной зависимости;) @item(ex_pts - задает значения факторов влияния и значение функции отклика;) @end(list) @b(Пример использования:) @begin[lang=lisp](code) ;;;; Для аппроксимации экспериментальных точек полиномом второй степени функции одной переменной. ;;;; Здесь коэффициенты a1, a2, a3 можно найти решив САУ, получаемую в результате. ;;;; (defun yy (xx) (+ (* a1 xx xx) (* a2 xx) a3)) (make-least-squares-matrix '(xx yy) '((xx xx) (xx) (1.0) (yy)) '((-1.0 1.0) (0.0 0.0) (2.0 4.0) (3.0 9.0))) => Matr 3х4 [ 98.0d0 34.0d0 14.0d0 98.0d0 ] [ 34.0d0 14.0d0 4.0d0 34.0d0 ] [ 14.0d0 4.0d0 4.0d0 14.0d0 ] ;;;; Для аппроксимации экспериментальных точек полиномом второй степени функции двух переменных. ;;;; Здесь коэффициенты a1, a2, a3 можно найти решив САУ, получаемую в результате. (defun yy (x1 x2) (+ (* 1.0 x1 x1) (* 2.0 x2 x2) (* 3.0 x1 x2) (* 4.0 x1) (* 5.0 x2) 6.0)) (make-least-squares-matrix '(x1 x2 yy) '((x1 x1) (x2 x2) (x1 x2) (x1) (x2) (1.0) (yy)) (let ((pts nil)) (loop :for i :from -2 :to 2 :do (loop :for j :from -2 to 2 :do (push (list i j (yy i j)) pts))) pts)) ; => Matr 6х7 ; [ 170.0d0 100.0d0 0.0d0 0.0d0 0.0d0 50.0d0 670.0d0 ] ; [ 100.0d0 170.0d0 0.0d0 0.0d0 0.0d0 50.0d0 740.0d0 ] ; [ 0.0d0 0.0d0 100.0d0 0.0d0 0.0d0 0.0d0 300.0d0 ] ; [ 0.0d0 0.0d0 0.0d0 50.0d0 0.0d0 0.0d0 200.0d0 ] ; [ 0.0d0 0.0d0 0.0d0 0.0d0 50.0d0 0.0d0 250.0d0 ] ; [ 50.0d0 50.0d0 0.0d0 0.0d0 0.0d0 25.0d0 300.0d0 ] (solve-x *) ; => Matr 1х6 ; [ 1.0d0 2.0d0 3.0d0 4.0d0 5.0d0 6.0d0 ] @end(code) См. также math/ls-gauss/solve-x; math/ls-rotation/solve." (let* ((m (length ff)) (n (1- m)) (mtr (make-instance 'math/matr:<matrix> :dimensions (list n m) :initial-element 0.0d0 )) (mtr-lambda (make-instance 'math/matr:<matrix> :dimensions (list n m) :initial-element nil ))) (dotimes (i n) (dotimes (j m) (setf (math/matr:mref mtr-lambda i j) (eval (list 'lambda vv (cons '* (append (nth i ff) (nth j ff)))))))) (mapc #'(lambda (el) (dotimes (i n) (dotimes (j m) (setf (math/matr:mref mtr i j) (+ (apply (math/matr:mref mtr-lambda i j) el) (math/matr:mref mtr i j)))))) ex_pts) mtr)) (defun averaging-function-body (vv ff ex_pts) (let ((kk (cons '+ (mapcar #'(lambda(el1 el2) (cons '* (cons el1 el2))) (math/matr:row (math/ls-gauss:solve-x (make-least-squares-matrix vv ff ex_pts)) 0) ff))) (rez nil)) (setf rez (list (reverse (cdr(reverse vv))) kk)) rez)) (defun averaging-function-lambda (args-fuc-names func-view args-results) "@b(Описание:) функция @b(averaging-function-lambda) возвращает исходный код аппроксимиующей lambda-функции, построенной на основании списка, каждый элемент которого является списком, содержащим значения аргументов функции и значение функции, соответствующее этим аргументам. @b(Переменые:) @begin(list) @item(args-fuc-names - список, содержащий имена аргументов и функции ;) @item(func-view - вид функциональной зависимости. Функциональная зависимость должна использовать имена из args-fuc-names ;) @item(args-results - списка, каждый элемент которого является списком, содержащим значения аргументов функции и значение функции (соответствующее этим аргументам).) @end(list) @b(Пример использования:) @begin[lang=lisp](code) (averaging-function-lambda '(xx yy) '((xx xx) (xx) (1.0) (yy)) '((0.0 0.0) (1.0 1.0) (2.0 4.0) (3.0 9.0))) => (LAMBDA (XX) (+ (* 1.0d0 XX XX) (* 0.0d0 XX) (* 0.0d0 1.0))) (averaging-function-lambda '(xx yy) '((xx xx xx) (xx xx) (xx) (1.0) (yy)) '((-2.0 -8.0) (-1.0 -1.0) (0.0 0.0) (1.0 1.0) (2.0 8.0))) => (LAMBDA (XX) (+ (* 1.0d0 XX XX XX) (* 0.0d0 XX XX) (* 0.0d0 XX) (* 0.0d0 1.0))) @end(code)" `(lambda ,@(averaging-function-body args-fuc-names func-view args-results))) (defun averaging-function-defun (args-fuc-names func-view args-results func-name) "@b(Описание:) функция @b(averaging-function-defun) возвращает исходный код именований аппроксимиующей функции, построенной на основании списка, каждый элемент которого является списком, содержащим значения аргументов функции и значение функции, соответствующее этим аргументам. @b(Переменые:) @begin(list) @item(args-fuc-names - список, содержащий имена аргументов и функции ;) @item(func-view - вид функциональной зависимости. Функциональная зависимость должна использовать имена из args-fuc-names ;) @item(args-results - списка, каждый элемент которого является списком, содержащим значения аргументов функции и значение функции (соответствующее этим аргументам).) @item(func-name - имя функции.) @end(list) @b(Пример использования:) @begin[lang=lisp](code) (averaging-function-defun '(xx yy) '((xx xx) (xx) (1.0) (yy)) '((0.0 0.0) (1.0 1.0) (2.0 4.0) (3.0 9.0)) 'square-func) => (DEFUN SQUARE-FUNC (XX) (+ (* 1.0d0 XX XX) (* 0.0d0 XX) (* 0.0d0 1.0))) (averaging-function-defun '(xx yy) '((xx xx xx) (xx xx) (xx) (1.0) (yy)) '((-2.0 -8.0) (-1.0 -1.0) (0.0 0.0) (1.0 1.0) (2.0 8.0)) 'cubic-func) => (DEFUN CUBIC-FUNC (XX) (+ (* 1.0d0 XX XX XX) (* 0.0d0 XX XX) (* 0.0d0 XX) (* 0.0d0 1.0))) @end(code)" `(defun ,func-name ,@(averaging-function-body args-fuc-names func-view args-results))) (defmacro make-approximation-lambda (args-fuc-names func-view args-results) "@b(Описание:) макрос @b(make-approximation-lambda) определяет аппроксимиующую lambda-функцию, построенную на основании списка, каждый элемент которого является списком, содержащим значения аргументов функции и значение функции, соответствующее этим аргументам. @b(Пример использования:) @begin[lang=lisp](code) (let ((func (make-approximation-lambda (xx yy) ((xx xx) (xx) (1.0) (yy)) ((0.0 0.0) (1.0 1.0) (2.0 4.0) (3.0 9.0))))) (funcall func 1.0) ;=> 1.0d0 (funcall func 3.0) ;=> 9.0d0 (funcall func 5.0)) ;=> 25.0d0 @end(code) " (averaging-function-lambda args-fuc-names func-view args-results)) (defmacro make-approximation-defun (args-fuc-names func-view args-results func-name) "@b(Описание:) макрос @b(make-approximation-defun) определяет аппроксимиующую функцию с именем @b(func-name), построенной на основании списка, каждый элемент которого является списком, содержащим значения аргументов функции и значение функции, соответствующее этим аргументам. @b(Пример использования:) @begin[lang=lisp](code) (make-approximation-defun (xx yy) ((xx xx) (xx) (1.0) (yy)) ((0.0 0.0) (1.0 1.0) (2.0 4.0) (3.0 9.0)) square-func) (square-func 1.0) => 1.0d0 (square-func 3.0) => 9.0d0 (square-func 5.0) => 25.0d0 @end(code) " (averaging-function-defun args-fuc-names func-view args-results func-name)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Разработка линейной интерполяции функции одного переменного ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun make-linear-interpolation (points &key (ff *apr-func-1-2*)) "@b(Описание:) функция @b(make-linear-interpolation) возвращает функциональной зависимость, аппроксимируемую по функции одного переменного, заданной таблично. @b(Переменые:) @begin(list) @item(points - список, состоящий из аргумента и значения ;) @item(ff - вид функциональной зависимости см. *apr-func-1-2* --- *apr-func-1-5*.) @end(list) @b(Пример использования:) @begin[lang=lisp](code) (let* ((points-01 '((0.0 0.0) (1.0 1.0) (2.0 2.0))) (func-1 (make-linear-interpolation points-01))) (loop :for x :from 0 :to 2 :by 1/10 :collect (mapcar #'(lambda (el) (coerce el 'single-float)) (list x (funcall func-1 x))))) => ((0.0 0.0) (0.1 0.1) (0.2 0.2) (0.3 0.3) (0.4 0.4) (0.5 0.5) (0.6 0.6) (0.7 0.7) (0.8 0.8) (0.9 0.9) (1.0 1.0) (1.1 1.1) (1.2 1.2) (1.3 1.3) (1.4 1.4) (1.5 1.5) (1.6 1.6) (1.7 1.7) (1.8 1.8) (1.9 1.9) (2.0 2.0)) (let* ((points-02 '((0.0 0.0) (1.0 1.0) (2.0 4.0) (3.0 9.0))) (func-2 (make-linear-interpolation points-02 :ff *apr-func-1-3*))) (loop :for x :from 1 :to 3 :by 1/10 :collect (mapcar #'(lambda (el) (coerce el 'single-float)) (list x (funcall func-2 x))))) => ((1.0 1.0) (1.1 1.21) (1.2 1.44) (1.3 1.69) (1.4 1.96) (1.5 2.25) (1.6 2.56) (1.7 2.89) (1.8 3.24) (1.9 3.61) (2.0 4.0) (2.1 4.41) (2.2 4.84) (2.3 5.29) (2.4 5.76) (2.5 6.25) (2.6 6.76) (2.7 7.29) (2.8 7.84) (2.9 8.41) (3.0 9.0)) @end(code) " (eval (averaging-function-lambda *apr-args-1* ff points))) (defun make-linear-approximation-array (x1 a1d ) (let ((a1-rez (make-array (mapcar #'1- (array-dimensions a1d)) :initial-element nil))) (loop :for r :from 0 :below (array-dimension a1-rez 0) :do (setf (aref a1-rez r) (make-linear-interpolation (list (list (aref x1 r) (aref a1d r)) (list (aref x1 (1+ r)) (aref a1d (1+ r)))) :ff *apr-func-1-2*))) a1-rez)) (defun index-by-value (val vect) (let ((rez+ 0) (rez- (- (array-dimension vect 0) 2))) (cond ((< (svref vect 0) (svref vect (1- (array-dimension vect 0)))) (loop :for i :from 1 :below (1- (array-dimension vect 0)) :do (when (<= (svref vect i) val ) (setf rez+ i))) rez+) ((> (svref vect 0) (svref vect (1- (array-dimension vect 0)))) (loop :for i :from (1- (array-dimension vect 0)) :downto 1 :do (when (>= val (svref vect i)) (setf rez- (1- i)))) rez-)))) (defun approximation-linear (x1 a-x1 a-func) (funcall (aref a-func (index-by-value x1 a-x1)) x1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defclass <appr-linear> () ((x1 :accessor appr-linear-x1 :documentation "Вектор аргументов.") (a1d-func :accessor appr-linear-a1d-func :documentation "Вектор функций.")) (:documentation "@b(Описание:) Класс @b(<appr-linear>) представляет линейную интерполяцию. @b(Пример использования:) @begin[lang=lisp](code) (let ((a1 (make-instance '<appr-linear> :x1 (vector 1 2 3) :a1d (vector 1 4 9))) (a2 (make-instance '<appr-linear> :x1 (vector 2 3 4) :a1d (vector 4 9 16)))) (loop :for i :from 0 :to 5 :by 1/5 :do (format t \"| ~5F | ~5F | ~5F |~%\" i (approximate i a1) (approximate i a2)))) => | 0.0 | -2.0 | -6.0 | | 0.2 | -1.4 | -5.0 | | 0.4 | -0.8 | -4.0 | | 0.6 | -0.2 | -3.0 | | 0.8 | 0.4 | -2.0 | | 1.0 | 1.0 | -1.0 | | 1.2 | 1.6 | -0.0 | | 1.4 | 2.2 | 1.0 | | 1.6 | 2.8 | 2.0 | | 1.8 | 3.4 | 3.0 | | 2.0 | 4.0 | 4.0 | | 2.2 | 5.0 | 5.0 | | 2.4 | 6.0 | 6.0 | | 2.6 | 7.0 | 7.0 | | 2.8 | 8.0 | 8.0 | | 3.0 | 9.0 | 9.0 | | 3.2 | 10.0 | 10.4 | | 3.4 | 11.0 | 11.8 | | 3.6 | 12.0 | 13.2 | | 3.8 | 13.0 | 14.6 | | 4.0 | 14.0 | 16.0 | | 4.2 | 15.0 | 17.4 | | 4.4 | 16.0 | 18.8 | | 4.6 | 17.0 | 20.2 | | 4.8 | 18.0 | 21.6 | | 5.0 | 19.0 | 23.0 | @end(code)")) (defmethod print-object ((a-l <appr-linear>) stream) (print-unreadable-object (a-l stream :type t) (format stream " (~A ~A)" (appr-linear-x1 a-l) (appr-linear-a1d-func a-l)))) (defmethod initialize-instance ((a-l <appr-linear>) &key (x1 (vector -2 -1 0 1 2)) (a1d (vector 4 1 0 1 4))) (setf (appr-linear-x1 a-l) x1 (appr-linear-a1d-func a-l) (make-linear-approximation-array x1 a1d))) (defmethod approximate ((point number) (a-l <appr-linear>)) "@b(Описание:) метод @b(approximate) возвращает значение функции одного переменного в точке point для функции заданой таблично и аппроксимированной объектом @b(a-l)." (approximation-linear point (appr-linear-x1 a-l) (appr-linear-a1d-func a-l))) (defun make-appr-linear (args-resuls) "@b(Описание:) функция @b(make-appr-linear) возвращает функцию, являющуюся линейной интерполяцией функции одного переменного. @b(Пример использования:) @begin[lang=lisp](code) (let ((f1 (math/appr:make-appr-linear (loop :for i :from 0 :to 10 :collect (list (* 1.0d0 i) (* 0.1d0 i i)))))) (loop :for i :from 0 :to 10 :by 1/5 :collect (list (* 1.0 i) (coerce (funcall f1 (* 1d0 i))'single-float )))) => '((0.0 0.0) (0.2 0.02) (0.4 0.04) (0.6 0.06) (0.8 0.08) (1.0 0.1) (1.2 0.16) (1.4 0.22) (1.6 0.28) (1.8 0.34) (2.0 0.4) (2.2 0.50) (2.4 0.60) (2.6 0.70) (2.8 0.80) (3.0 0.9) (3.2 1.04) (3.4 1.18) (3.6 1.32) (3.8 1.46) (4.0 1.6) (4.2 1.78) (4.4 1.96) (4.6 2.14) (4.8 2.32) (5.0 2.5) (5.2 2.72) (5.4 2.94) (5.6 3.16) (5.8 3.38) (6.0 3.6) (6.2 3.86) (6.4 4.12) (6.6 4.38) (6.8 4.64) (7.0 4.9) (7.2 5.20) (7.4 5.50) (7.6 5.80) (7.8 6.10) (8.0 6.4) (8.2 6.74) (8.4 7.08) (8.6 7.42) (8.8 7.76) (9.0 8.1) (9.2 8.48) (9.4 8.86) (9.6 9.24) (9.8 9.62) (10.0 10.0)) @end(code) " (let ((appr-1d (make-instance '<appr-linear> :x1 (apply #'vector (mapcar #'first args-resuls)) :a1d (apply #'vector (mapcar #'second args-resuls))))) #'(lambda (el) (approximate el appr-1d)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Линейная интерполяции функции двух переменных (билинейная интерполяция) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun make-bilinear-interpolation (points &key (ff *apr-func-2-4*)) (eval (averaging-function-lambda *apr-args-2* ff points))) (defun make-bilinear-approximation-array (a2d x1 x2) (when (/= 2 (array-rank a2d)) (error "In make-bilinear-approximation-array: (/= 2 (array-rank a2d))")) (let ((a2-rez (make-array (mapcar #'1- (array-dimensions a2d)) :initial-element nil))) (loop :for r :from 0 :below (array-dimension a2-rez 0) :do (loop :for c :from 0 :below (array-dimension a2-rez 1) :do (setf (aref a2-rez r c) (make-bilinear-interpolation (list (list (svref x1 r) (svref x2 c) (aref a2d r c)) (list (svref x1 r) (svref x2 (1+ c)) (aref a2d r (1+ c))) (list (svref x1 (1+ r)) (svref x2 c) (aref a2d (1+ r) c)) (list (svref x1 (1+ r)) (svref x2 (1+ c)) (aref a2d (1+ r) (1+ c)))) :ff *apr-func-2-4*)))) a2-rez)) (defun approximation-bilinear (v1 v2 a-x1 a-x2 a-func) (funcall (aref a-func (index-by-value v1 a-x1) (index-by-value v2 a-x2)) v1 v2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defclass <appr-bilinear> () ((x1 :accessor appr-bilinear-x1 :documentation "Вектор реперных значений по первому направлению (измерению).") (x2 :accessor appr-bilinear-x2 :documentation "Вектор реперных значений по второму направлению (измерению).") (a2d-func :accessor appr-bilinear-a2d-func :documentation "Двумерный массив функций размерности которого, на единицу меньше количества реперных значений по соответствующему направлению (измерению).")) (:documentation "@b(Описание:) Класс @b(<appr-bilinear>) представляет билинейную интерполяцию.")) (defmethod print-object ((a-l <appr-bilinear>) stream) (print-unreadable-object (a-l stream) (format stream " (~A ~A ~A)" (appr-bilinear-x1 a-l) (appr-bilinear-x2 a-l) (appr-bilinear-a2d-func a-l)))) (defmethod initialize-instance ((a-l <appr-bilinear>) &key (x1 (vector -1 0 1 )) (x2 (vector 0 1 )) (a2d '#2A((1 2) (3 4) (5 6)))) (setf (appr-bilinear-x1 a-l) x1 (appr-bilinear-x2 a-l) x2 (appr-bilinear-a2d-func a-l) (make-bilinear-approximation-array a2d x1 x2))) (defmethod approximate (point (a-l <appr-bilinear>)) "@b(Описание:) метод @b(approximate)" (approximation-bilinear (aref point 0) (aref point 1) (appr-bilinear-x1 a-l) (appr-bilinear-x2 a-l) (appr-bilinear-a2d-func a-l))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Сглаживание методами gnuplot ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defgeneric smooth-by-points (point-s base-dist-s nod-points nod-values &key weight-func) (:documentation "@b(Описание:) обобщенная функция @b(smooth-by-points) возвращает значение в точке @b(point-s), являющееся результатом сглаживания зависимости заданной: @begin(list) @item(таблицей узловых точек @b(nod-points);) @item(таблицей значений @b(nod-values);) @item(функцией @b(weight-func) учета веса значений от относительного расстояния до аргумента (при которых эти значения определены);) @item(базовой длины (базовых длинн) @b(base-dist-s), по которой (которым) вычисляются относительные расстояния.) @end(list)")) (defgeneric refine-smoothing-by-points (nod-points nod-values base-dist-s &key weight-func delta iterations) (:documentation "@b(Описание:) обобщенная функция @b(refine-smoothing-by-points) возвращает массив значений @b(rez-values@sub(i)) такой, что для точек @b(nod-points@sub(i)) сумма отклонений между @b(nod-values@sub(i)) и @b((smooth-by-points point-s@sub(i) base-dist-s nod-points rez-values@sub(i) :weight-func weight-func)) не превысит @b(delta). Вторым значением возвращается: @begin(list) @item(T - если такой массив удалось найти за указанной в параметре @b(iterations) количестве итераций;) @item(nil - если за указанной количество итераций @b(iterations) такой массив удалось найти не удалось.) @end(list) ")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod smooth-by-points ((x number) (dx number) (points vector) (values vector) &key (weight-func #'math/smooth:gauss-smoothing)) "@b(Описание:) метод @b(smooth-by-points) возвращает значение, являющееся результатом сглаживания зависимости заданной: @begin(list) @item(аргументами @b(points);) @item(значениями в этих точках @b(values);) @item(функцией @b(weight-func) учета веса значений от относительного расстояния до аргумента (при которых эти значения определены);) @item(базовой длины, по которой вычисляются относительные расстояния.) @end(list) Этот вариант метода примерняется для сглаживания функции одного аргумента. @b(Пример использования:) @begin[lang=lisp](code) (let ((args #(-2.0 -1.0 0.0 1.0 2.0)) (vals #( 4.0 1.0 0.0 1.0 4.0)) (dx-2_0 2.0) (dx-1_0 1.0) (dx-0_6 0.6)) (loop :for i :from 0 :to 2 :by 1/5 :collect (list (* i 1.0) (* i i 1.0) (smooth-by-points i dx-0_6 args vals) (smooth-by-points i dx-1_0 args vals) (smooth-by-points i dx-2_0 args vals)))) => '((0.0 0.0 0.11070304 0.4977933 1.3665789) (0.2 0.04 0.1735467 0.5375060 1.3774427) (0.4 0.16 0.3702085 0.6551497 1.4096088) (0.6 0.36 0.6500492 0.8464661 1.4618422) (0.8 0.64 0.8946066 1.1046556 1.5322074) (1.0 1.00 1.1105981 1.4196386 1.6182360) (1.2 1.44 1.4516152 1.7761649 1.7171193) (1.4 1.96 2.0848030 2.1525292 1.8259060) (1.6 2.56 2.9039226 2.5225418 1.9416808) (1.8 3.24 3.5229838 2.8611753 2.0617056) (2.0 4.00 3.8243356 3.1507930 2.1835241)) @end(code)" (assert (math/smooth:weight-func-p weight-func)) (assert (= (length points) (length values))) (let ((w-summ 0.0) (w-z-summ 0.0) (w 0.0) (z 0.0)) (loop :for i :from 0 :below (array-dimension points 0) :do (progn (setf w (funcall weight-func (math/core:distance-relative x (aref points i) dx)) w-summ (+ w-summ w) z (aref values i) w-z-summ (+ w-z-summ (* w z ))))) (/ w-z-summ w-summ))) (defmethod smooth-by-points ((x vector) (dx vector) (points array) (values vector) &key (weight-func #'math/smooth:gauss-smoothing)) "@b(Описание:) метод @b(smooth-by-points) возвращает значение, являющееся результатом сглаживания зависимости заданной: @begin(list) @item(аргументами @b(points);) @item(значениями в этих точках @b(values);) @item(функцией @b(weight-func) учета веса значений от относительного расстояния до аргумента (при которых эти значения определены);) @item(базовой длины, по которой вычисляются относительные расстояния.) @end(list) Этот вариант метода примерняется для сглаживания функции двух аргументов. @b(Пример использования:) @begin[lang=lisp](code) (smooth-by-points #(0.0 0.0) #(1.0 1.0) (make-array '(4 2) :initial-contents '((0.0 0.0) (1.0 0.0) (0.0 1.0) (1.0 1.0))) #(0.0 1.0 1.0 2.0)) 0.53788286 (smooth-by-points #(0.0 0.0) #(0.6 0.6) (make-array '(4 2) :initial-contents '((0.0 0.0) (1.0 0.0) (0.0 1.0) (1.0 1.0))) #(0.0 1.0 1.0 2.0)) 0.117073804 (smooth-by-points #(0.0 0.0) #(0.4 0.4) (make-array '(4 2) :initial-contents '((0.0 0.0) (1.0 0.0) (0.0 1.0) (1.0 1.0))) #(0.0 1.0 1.0 2.0)) 0.0038534694 (smooth-by-points #(1.0 0.0) #(1.0 1.0) (make-array '(4 2) :initial-contents '((0.0 0.0) (1.0 0.0) (0.0 1.0) (1.0 1.0))) #(0.0 1.0 1.0 2.0)) 1.0 (smooth-by-points #(1.0 0.0) #(0.6 0.6) (make-array '(4 2) :initial-contents '((0.0 0.0) (1.0 0.0) (0.0 1.0) (1.0 1.0))) #(0.0 1.0 1.0 2.0)) 0.9999999 (smooth-by-points #(1.0 0.0) #(0.4 0.4) (make-array '(4 2) :initial-contents '((0.0 0.0) (1.0 0.0) (0.0 1.0) (1.0 1.0))) #(0.0 1.0 1.0 2.0)) 1.0 (smooth-by-points #(0.0 1.0) #(1.0 1.0) (make-array '(4 2) :initial-contents '((0.0 0.0) (1.0 0.0) (0.0 1.0) (1.0 1.0))) #(0.0 1.0 1.0 2.0)) 1.0 (smooth-by-points #(0.0 1.0) #(0.6 0.6) (make-array '(4 2) :initial-contents '((0.0 0.0) (1.0 0.0) (0.0 1.0) (1.0 1.0))) #(0.0 1.0 1.0 2.0)) 1.0 (smooth-by-points #(0.0 1.0) #(0.4 0.4) (make-array '(4 2) :initial-contents '((0.0 0.0) (1.0 0.0) (0.0 1.0) (1.0 1.0))) #(0.0 1.0 1.0 2.0)) 1.0 (smooth-by-points #(1.0 1.0) #(1.0 1.0) (make-array '(4 2) :initial-contents '((0.0 0.0) (1.0 0.0) (0.0 1.0) (1.0 1.0))) #(0.0 1.0 1.0 2.0)) 1.4621171 (smooth-by-points #(1.0 1.0) #(0.6 0.6) (make-array '(4 2) :initial-contents '((0.0 0.0) (1.0 0.0) (0.0 1.0) (1.0 1.0))) #(0.0 1.0 1.0 2.0)) 1.8829262 (smooth-by-points #(1.0 1.0) #(0.4 0.4) (make-array '(4 2) :initial-contents '((0.0 0.0) (1.0 0.0) (0.0 1.0) (1.0 1.0))) #(0.0 1.0 1.0 2.0)) 1.9961466 (smooth-by-points #(0.5 0.5) #(1.0 1.0) (make-array '(4 2) :initial-contents '((0.0 0.0) (1.0 0.0) (0.0 1.0) (1.0 1.0))) #(0.0 1.0 1.0 2.0)) 1.0 (smooth-by-points #(0.5 0.5) #(0.6 0.6) (make-array '(4 2) :initial-contents '((0.0 0.0) (1.0 0.0) (0.0 1.0) (1.0 1.0))) #(0.0 1.0 1.0 2.0)) 1.0 (smooth-by-points #(0.5 0.5) #(0.4 0.4) (make-array '(4 2) :initial-contents '((0.0 0.0) (1.0 0.0) (0.0 1.0) (1.0 1.0))) #(0.0 1.0 1.0 2.0)) 1.0 @end(code)" (assert (math/smooth:weight-func-p weight-func)) (assert (= (array-rank points) 2)) (assert (= (array-dimension points 0) (length values))) (assert (= (array-dimension points 1) (length x) (length dx))) (let ((w-summ 0.0) (w-z-summ 0.0) (w 0.0) (z 0.0)) (loop :for i :from 0 :below (array-dimension points 0) :do (progn (setf w (funcall weight-func (math/core:distance-relative x (math/matr:row i points) dx)) w-summ (+ w-summ w) z (aref values i) w-z-summ (+ w-z-summ (* w z ))))) (/ w-z-summ w-summ))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; refine-smoothing-by-points (defmethod refine-smoothing-by-points ((nod-points vector) (nod-values vector) (base-dist-s number) &key (weight-func #'math/smooth:gauss-smoothing) (delta 0.001) (iterations 10000)) "@b(Описание:) метод @b(refine-smoothing-by-points) в случе нахождения сглаживания для функции одного переменного." (assert (math/smooth:weight-func-p weight-func)) (assert (= (length nod-points) (length nod-values))) (let ((v-iter (cl-utilities:copy-array nod-values)) (v-rez (cl-utilities:copy-array nod-values))) (labels ((start-V1 (v-rez v-iter) (loop :for i :from 0 :below (length nod-values) :do (setf (svref v-rez i) (smooth-by-points (svref nod-points i) base-dist-s nod-points v-iter :weight-func weight-func))) (math/core:summ-distance v-rez nod-values)) (iterate (v-rez v-iter) (loop :for i :from 0 :below (length nod-values) :do (setf (svref v-iter i) (+ (svref v-iter i) (* 1 (- (svref nod-values i) (svref v-rez i)))))))) (do ((i 0 (1+ i)) (dist (start-V1 v-rez v-iter ) (start-V1 v-rez v-iter))) ((or (> i iterations) (< dist delta)) (progn ;;;;(format t "I=~D; DIST=~F;~%V-ITER~S;~%V-REZ=~S~%" i dist v-iter v-rez ) (if (< i iterations) (values v-iter t i dist v-rez nod-values) (values v-iter nil i dist v-rez nod-values)))) (iterate v-rez v-iter))))) (defmethod refine-smoothing-by-points ((nod-points array) (nod-values vector) (base-dist-s vector) &key (weight-func #'math/smooth:gauss-smoothing) (delta 0.001) (iterations 10000)) "@b(Описание:) метод @b(refine-smoothing-by-points) в случе нахождения сглаживания для функции двух переменных. @b(Пример использования:) @begin[lang=lisp](code) (let* ((nod-lst '((-1.0 0.0) (1.0 0.0) (-1.0 1.0) (1.0 1.0))) (nod-rez #(-10.0 0.0 0.0 10.0)) (nod-pts (make-array '(4 2) :initial-contents nod-lst)) (base-dists-1_5 #(1.5 1.5)) (base-dists-1_0 #(1.0 1.0)) (base-dists-0_6 #(0.6 0.6)) (base-dists-0_4 #(0.4 0.4))) (refine-smoothing-by-points nod-pts nod-rez base-dists-0_4) (refine-smoothing-by-points nod-pts nod-rez base-dists-0_6) (refine-smoothing-by-points nod-pts nod-rez base-dists-1_0) (refine-smoothing-by-points nod-pts nod-rez base-dists-1_5) ) => #(-10.019267 -0.019267347 0.019267347 10.019267), T, 1, 2.9726332e-4, #(-9.999926 7.424513e-5 -7.424499e-5 9.999926), #(-10.0 0.0 0.0 10.0), #(0.4 0.4) => #(-10.663013 -0.66271365 0.6627135 10.663013), T, 4, 4.3922185e-4, #(-9.99989 1.0987265e-4 -1.1000411e-4 9.99989), #(-10.0 0.0 0.0 10.0), #(0.6 0.6) => #(-16.005812 -5.632663 5.6326632 16.00581), T, 15, 9.807203e-4, #(-9.999755 2.451054e-4 -2.4542634e-4 9.999755), #(-10.0 0.0 0.0 10.0), #(1.0 1.0) => #(-29.902119 -15.834344 15.834344 29.902119), T, 40, 8.0980576e-4, #(-9.999799 2.0380187e-4 -2.0355334e-4 9.999799), #(-10.0 0.0 0.0 10.0), #(1.5 1.5) @end(code)" (assert (math/smooth:weight-func-p weight-func)) (assert (= (array-rank nod-points) 2)) (assert (= (array-dimension nod-points 0) (length nod-values))) (assert (= (array-dimension nod-points 1) (length base-dist-s))) (let ((v-iter (cl-utilities:copy-array nod-values)) (v-rez (cl-utilities:copy-array nod-values))) (labels ((start-V1 (v-rez v-iter) (loop :for i :from 0 :below (length nod-values) :do (setf (svref v-rez i) (smooth-by-points (math/matr:row i nod-points) base-dist-s nod-points v-iter :weight-func weight-func))) (math/core:summ-distance v-rez nod-values)) (iterate (v-rez v-iter) (loop :for i :from 0 :below (length nod-values) :do (setf (svref v-iter i) (+ (svref v-iter i) (* 1 (- (svref nod-values i) (svref v-rez i)))))))) (do ((i 0 (1+ i)) (dist (start-V1 v-rez v-iter ) (start-V1 v-rez v-iter))) ((or (> i iterations) (< dist delta)) (progn ;;;; (format t "I=~D ; DIST=~F;~%V-ITER~S;~%V-REZ=~S~%" i dist v-iter v-rez ) (if (< i iterations) (values v-iter t i dist v-rez nod-values base-dist-s) (values v-iter nil i dist v-rez nod-values base-dist-s)))) (iterate v-rez v-iter))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; make-refine-smoothing (defmethod make-refine-smoothing ((nod-points vector) (nod-values vector) (base-dist-s number) &key (weight-func #'math/smooth:gauss-smoothing) (delta 0.001) (iterations 10000)) "@b(Описание:) метод @b(make-refine-smoothing) в случе нахождения сглаживания для функции одного переменного. @b(Пример использования:) @begin[lang=lisp](code) (let* ((nod-pts #(-2.0 -1.0 -0.5 0.0 0.5 1.0 2.0)) (nod-rez #( 4.0 1.0 0.25 0.0 0.25 1.0 4.0)) (base-dists-1_5 1.5 ) (base-dists-1_0 1.0 ) (base-dists-0_6 0.6 ) (base-dists-0_4 0.4 ) (func (make-refine-smoothing nod-pts nod-rez base-dists-1_5))) (loop :for i :from -2 :to 2 :by 1/10 :collect (list (* 1.0 i) (* 1.0 i i) (funcall func (* 1.0 i)) (* 100 (1- (/ (* 1.0 i i) (funcall func (* 1.0 i)))))))) => '(( 0.0 0.00 0.00350) ( 0.1 0.01 0.01315) ( 0.2 0.04 0.04218) ( 0.3 0.09 0.09071) ( 0.4 0.16 0.15898) ( 0.5 0.25 0.24730) ( 0.6 0.36 0.35599) ( 0.7 0.49 0.48542) ( 0.8 0.64 0.63591) ( 0.9 0.81 0.80774) ( 1.0 1.00 1.00107) ( 1.1 1.21 1.21590) ( 1.2 1.44 1.45205) ( 1.3 1.69 1.70909) ( 1.4 1.96 1.98635) ( 1.5 2.25 2.28284) ( 1.6 2.56 2.59730) ( 1.7 2.89 2.92817) ( 1.8 3.24 3.27363) ( 1.9 3.61 3.63161) ( 2.0 4.00 3.99986)) @end(code)" (let ((new-nod-values (refine-smoothing-by-points nod-points nod-values base-dist-s :weight-func weight-func :delta delta :iterations iterations)) (new-nod-points (cl-utilities:copy-array nod-points)) (new-base-dist-s base-dist-s)) (lambda (x) (smooth-by-points x new-base-dist-s new-nod-points new-nod-values :weight-func weight-func)))) (defmethod make-refine-smoothing ((nod-points cons) (nod-values cons) (base-dist-s number) &key (weight-func #'math/smooth:gauss-smoothing) (delta 0.001) (iterations 10000)) (make-refine-smoothing (coerce nod-points 'vector) (coerce nod-values 'vector) base-dist-s :weight-func weight-func :delta delta :iterations iterations)) (defmethod make-refine-smoothing ((nod-points array) (nod-values vector) (base-dist-s vector) &key (weight-func #'math/smooth:gauss-smoothing) (delta 0.001) (iterations 10000)) "@b(Описание:) метод @b(make-refine-smoothing) в случе нахождения сглаживания для функции двух переменных. @b(Пример использования:) @begin[lang=lisp](code) (let* ((nod-lst '((-1.0 -1.0) (1.0 -1.0) (-1.0 1.0) (1.0 1.0))) (nod-rez #(-10.0 0.0 0.0 10.0)) (nod-pts (make-array '(4 2) :initial-contents nod-lst)) (base-dists-1_5 #(1.5 1.5)) (base-dists-1_0 #(1.0 1.0)) (base-dists-0_6 #(0.6 0.6)) (base-dists-0_4 #(0.4 0.4)) (func (make-refine-smoothing nod-pts nod-rez base-dists-1_5))) (funcall func 0.0 0.5)) @end(code)" (let ((new-nod-values (refine-smoothing-by-points nod-points nod-values base-dist-s :weight-func weight-func :delta delta :iterations iterations)) (new-nod-points (cl-utilities:copy-array nod-points)) (new-base-dist-s (cl-utilities:copy-array base-dist-s))) (lambda (x1 x2) (smooth-by-points (vector x1 x2) new-base-dist-s new-nod-points new-nod-values :weight-func weight-func))))
44,557
Common Lisp
.lisp
791
44.787611
251
0.59108
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
c8572996dbd933039b3a25a134176249ce6c2951d27a75ca3dbfbb09d42d975e
11,067
[ -1 ]
11,068
temp.lisp
mnasoft_math/src/ls-gsll/temp.lisp
;;;; ls-solve/temp.lisp (in-package :math/ls-solve) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(make-instance 'grid:matrix :dimensions '(3 3) :element-type 'double-float :initial-element 1.0d0) (lu-solve-extmatr '((1 2 3 14) (2 1 1 7) (3 0 1 2)) :grid-type 'array :element-type 'double-float) (math:equivalent) (defparameter *a* (make-array '(2 3 ) :initial-element 10.0)) (defparameter *b* (make-array '(2 3) :initial-element 10.00001)) (deftype 2d-array (&optional type size1 size2 ) `(array ,type (,size1 ,size2))) (math:equivalent *a* *a*) (math:equivalent *a* *b*) (eql (and (arrayp *a*) (= 2 (array-rank *a*))) t ) (type-of *a*) ; => (SIMPLE-ARRAY T (2 3)) (subtypep (eql (type-of *a*) (SIMPLE-ARRAY T (2 3)))
802
Common Lisp
.lisp
16
47.8125
101
0.567708
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
6fea42b0f72c3574e4b240097ab48bf4f0286a79faaee2285551c43abc35ed17
11,068
[ -1 ]
11,069
gsll-samples.lisp
mnasoft_math/src/ls-gsll/gsll-samples.lisp
(defparameter *m* '((1d0 1d0 1d0 1d0) (1d0 2d0 3d0 4d0) (1d0 4d0 9d0 16d0) (1d0 8d0 27d0 64d0))) (defparameter *v* '(10d0 30d0 100d0 354d0)) (let ((matrix (grid:make-foreign-array 'double-float :initial-contents *m*)) (vec (grid:make-foreign-array 'double-float :initial-contents *v*))) (multiple-value-bind (matrix perm) (gsll:lu-decomposition matrix) (gsll:lu-solve matrix vec perm))) (grid:copy-to (gsll:lu-solve matrix vec perm) grid:*default-grid-type*) (MULTIPLE-VALUE-BIND (matrix PERM) (GSLL:LU-DECOMPOSITION *m*) (LET ((GSLL::X (GSLL:LU-SOLVE matrix *v* PERM))) (GRID:COPY-TO (GSLL:PERMUTE-INVERSE PERM (GSLL:MATRIX-PRODUCT-TRIANGULAR matrix (GSLL:MATRIX-PRODUCT-TRIANGULAR matrix GSLL::X 1 :UPPER :NOTRANS :NONUNIT) 1 :LOWER :NOTRANS :UNIT))))) (GSLL:LU-DECOMPOSITION (grid:make-foreign-array 'double-float :initial-contents *m*)) (let ((matrix (grid:make-foreign-array 'double-float :initial-contents '((-34.5d0 8.24d0 3.29d0 -8.93d0) ( 34.12d0 -6.15d0 49.27d0 -13.49d0) ( 32.5d0 42.73d0 -17.24d0 43.31d0) (-16.12d0 -8.25d0 21.44d0 -49.08d0)))) (VEC (GRID:MAKE-FOREIGN-ARRAY 'DOUBLE-FLOAT :INITIAL-CONTENTS '(-39.66d0 -49.46d0 19.68d0 -5.55d0)))) (MULTIPLE-VALUE-BIND (MATRIX perm) (GSLL:LU-DECOMPOSITION MATRIX) (LET ((x (GSLL:LU-SOLVE MATRIX VEC perm))) (GRID:COPY-TO (GSLL:PERMUTE-INVERSE perm (GSLL:MATRIX-PRODUCT-TRIANGULAR MATRIX (GSLL:MATRIX-PRODUCT-TRIANGULAR MATRIX x 1 :UPPER :NOTRANS :NONUNIT) 1 :LOWER :NOTRANS :UNIT)))))) (let ((matrix (grid:make-foreign-array '(complex double-float) :initial-contents '((#c(-34.5d0 8.24d0) #c( 3.29d0 -8.93d0) #c( 34.12d0 -6.15d0) #c(49.27d0 -13.49d0)) (#c( 34.12d0 -6.15d0) #c( 49.27d0 -13.49d0) #c( 32.5d0 42.73d0) #c(-17.24d0 43.31d0)) (#c( 32.5d0 42.73d0) #c(-17.24d0 43.31d0) #c(-16.12d0 -8.25d0) #c( 21.44d0 -49.08d0)) (#c(-16.12d0 -8.25d0) #c( 21.44d0 -49.08d0) #c(-39.66d0 -49.46d0) #c( 19.68d0 -5.55d0))))) (vec (grid:make-foreign-array '(complex double-float) :initial-contents '(#c(-39.66d0 -49.46d0) #c( 19.68d0 -5.55d0) #c( -8.82d0 25.37d0) #c( -30.58d0 31.67d0))))) (multiple-value-bind (matrix perm) (gsll:lu-decomposition matrix) (let ((x (gsll:lu-solve matrix vec perm))) (grid:copy-to (gsll:permute-inverse perm (gsll:matrix-product-triangular matrix (gsll:matrix-product-triangular matrix x 1 :upper :notrans :nonunit) 1 :lower :notrans :unit))))))
2,602
Common Lisp
.lisp
53
43.433962
110
0.643705
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
4475095f5b191441c92a450908fcb28b5d48651dc6d56e670a6b9e5019724aba
11,069
[ -1 ]
11,070
ls-gsll.lisp
mnasoft_math/src/ls-gsll/ls-gsll.lisp
;;;; ./src/ls-solve/ls-solve.lisp (defpackage :math/ls-gsll (:use #:cl ) (:export solve solve-x) (:documentation "@b(Описание:) пакет @b(math/ls-gsll) пределяет функции для решения СЛАУ методом LU-разложения при помощи системσ GSLL.")) (in-package :math/ls-gsll) (defun solve (matrix vector) "@b(Описание:) функция| @b(solve) возвращает корни решения СЛАУ (системы линейных алгебраических уравнений), используя LU-разложение матрицы @b(matrix). @b(Пример использования:) @begin[lang=lisp](code) (let ((m (grid:make-foreign-array 'double-float :initial-contents '((1 2 3) (2 1 1) (3 0 1)))) (v (grid:make-foreign-array 'double-float :initial-contents '(14 7 6)))) (solve m v)) => #(1.0000000000000002d0 2.0000000000000004d0 2.9999999999999996d0) @end(code)" (multiple-value-bind (upper permutation signum) (gsl:lu-decomposition (grid:copy matrix)) (declare (ignore signum)) (let* ((initial-solution (gsl:lu-solve upper vector permutation t)) (rez (gsl:lu-refine matrix upper permutation vector initial-solution))) (apply #'vector (loop :for i :from 0 :below (grid:dim0 rez) :collect (grid:gref rez i)))))) (defun solve-x (m-v) "@b(Описание:) функция| @b(solve) возвращает корни решения СЛАУ (системы линейных алгебраических уравнений), используя LU-разложение матрицы @b(m-v). @b(Переменые:) @begin(list) @item(m-v - матрица, представленная в виде 2d-list, (списком состоящим из списков)); @end(list) @b(Пример использования:) @begin[lang=lisp](code) (let ((m '((1 2 3 14) (2 1 1 7) (3 0 1 6)))) (solve-x m)) => #(1.0000000000000002d0 2.0000000000000004d0 2.9999999999999996d0) @end(code)" (let ((m (math/matr:detach-last-col m-v)) (v (math/matr:get-last-col m-v))) (solve (grid:make-foreign-array 'double-float :initial-contents m) (grid:make-foreign-array 'double-float :initial-contents v)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2,542
Common Lisp
.lisp
58
31.87931
100
0.621053
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
b4755a8cbd48eb9074c6ff058f126c999f0410f871cf72e644508120278cbdda
11,070
[ -1 ]
11,071
core.lisp
mnasoft_math/src/core/core.lisp
;;;; ./src/core/core.lisp (defpackage :math/core (:use #:cl) (:export norma *semi-equal-relativ* *semi-equal-zero* semi-equal ) (:export summ-distance distance exclude-nil-from-list depth-sphere-along-cone distance-relative square) (:export split-range split-range-by-func split-range-at-center ) (:export matr-name-* ) (:export round-to-significant-digits +significant-digits+)) (in-package :math/core) (defun square (x) "@b(Описание:) функция @b(square) возвращает квадрат значения. @b(Переменые:) @begin(list) @item(x - число.) @end(list) @b(Пример использования:) @begin[lang=lisp](code) (square 5) => 25 (square -4) => 16 @end(code)" (* x x)) (defun exclude-nil-from-list (lst) "@b(Описание:) функция @b(exclude-nil-from-list) возвращает список в котором нет nil-элементов (они исключаются). @b(Пример использования:) @begin[lang=lisp](code) (exclude-nil-from-list '(1.1 1.0 nil 0.9 nil 1.2 nil 0.8)) => (1.1 1.0 0.9 1.2 0.8) @end(code)" (let ((res nil)) (dolist (el lst (reverse res) ) (when el (push el res ))))) (defun e-value (n) (let ((rez 1) (nf 1)) (dotimes (i n rez) (setf nf (/ nf (1+ i)) rez (+ rez nf))))) (defun split-range (from to steps) "@b(Описание:) split-range @b(Пример использования:) @begin[lang=lisp](code) (split-range 10 20 5) => (10.0 12.0 14.0 16.0 18.0 20.0) @end(code) " (loop :for i :from 0 :to steps :collect (coerce (+ from (* (/ i steps ) (- to from))) 'float))) (defun split-range-by-func (from to steps &key (func #'(lambda (x) (log x 10))) (anti-func #'(lambda (x) (expt 10 x)))) "@b(Описание:) split-range-by-func @b(Пример использования:) @begin[lang=lisp](code) (split-range-by-func 1 10 5) => (1.0 1.5848932 2.5118864 3.981072 6.3095737 10.0) (split-range-by-func 1 10 10) => (1.0 1.2589254 1.5848932 1.9952624 2.5118864 3.1622777 3.981072 5.0118723 6.3095737 7.943282 10.0) @end(code) " (mapcar #'(lambda (el)(funcall anti-func el)) (split-range (funcall func from) (funcall func to) steps))) (defun split-range-at-center (from to subdivisions) "@b(Описание:) функция @b(split-range-in-center) делит интервал от @b(from) до @b(to) на @b(subdivisions) интервалов, возвращая их середины. @b(Пример использования:) @begin[lang=lisp](code) (split-range-at-center 0.0 10.0 10) => (0.5 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5) @end(code) " (let ((delta (- to from)) (divisions (* subdivisions 2))) (loop :for i :from 1 :to divisions :by 2 :collect (+ from (* (/ i divisions) delta))))) (defun depth-sphere-along-cone (r alpha) "@b(Описание:) функция @b(depth-sphere-along-cone) возвращает заглубление сферы с радиусом R в конуc с углом при вершине равным alpha от линии пересечения конуса с цилиндром." (let ((betta (- pi (/ alpha 2)))) (- r (* r (tan (/ betta 2)))))) (defparameter +significant-digits+ 4 "Определяет количество значащих цифр при округлении по умолчанию.") (defun round-to-significant-digits (val &optional (significant-digits +significant-digits+) (base-val val)) "@b(Описание:) функция @b(round-to-significant-digits) округляет значение val до количества значащих цифр, задаваемых аргументом significant-digits. @b(Пример использования:) @begin[lang=lisp](code) (round-to-significant-digits 456.32738915923 ) => 456.3 (round-to-significant-digits 456.32738915923 6 ) => 456.327 (round-to-significant-digits 456.32738915923 6 53562.23) => 456.3 @end(code) " (labels ((find-divisor (val) "@b(Описание:) функция @b(find-divisor) @b(Пример использования:) @begin[lang=lisp](code) (find-divisor 10.964739714723287d0) @end(code) " (do ((divisor 1)) ((<= 1 (abs (* val divisor)) 10) divisor) (cond ((< (abs (* val divisor)) 1) (setf divisor (* divisor 10))) ((< 1 (abs (* val divisor))) (setf divisor (/ divisor 10)))))) (my-round (val &optional (divisor 1)) " @b(Пример использования:) @begin[lang=lisp](code) (my-round 10.964739714723287d0 1/100) => 10.96 @end(code) " (coerce (* (round val divisor) divisor) 'single-float))) (my-round val (/ (expt 10 (* -1 (- significant-digits 1))) (find-divisor base-val))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; /src/core/generic.lisp ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defgeneric distance (x1 x2) (:documentation "@b(Описание:) обобщенная функция @b(distance) возвращает расстояние между x1 и x2. Как корень квадратный из сумм квадратов расстояний по каждому направлению.")) (defgeneric distance-relative (x0 x1 dx) (:documentation "@b(Описание:) обобщенная функция @b(distance-relative) возвращает относительную длину между x0 и x1, длина приведения dx. Корень квадратный из сумм квадратов расстояний по каждому направлению отнесенному к длине приведения.")) (defgeneric summ-distance (x1 x2) (:documentation "@b(Описание:) обобщенная функция @b(summ-distance) возвращает сумму расстояний по каждому направлению.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; /src/core/generic-matr.lisp ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defgeneric matr-name-* (matrix) (:documentation "Matr")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defparameter *semi-equal-relativ* 1e-6 "@b(Описание:) переменная @b(*semi-equal-relativ*) определяет относительную величину, на которую могут отличаться значения считающиеся равными при срвнении из с помощью функции @b(semi-equal). ") (defparameter *semi-equal-zero* 1e-6 "@b(Описание:) переменная @b(*semi-equal-zero*) определяет абсолютную величину, на которую могут отличаться значения считающиеся равными при срвнении из с помощью функции @b(semi-equal). ") (defgeneric norma (x)) (defmethod norma ((x real)) (abs x)) (defmethod norma ((x number)) (sqrt (+ (* (realpart x) (realpart x)) (* (imagpart x) (imagpart x))))) (defmethod norma ((x cons)) (let ((n (loop :for i :in x :collect (* (norma i))))) (/ (apply #'+ n) (length n)))) (defmethod norma ((x vector)) (let ((n (loop :for i :across x :collect (* (norma i))))) (/ (apply #'+ n) (length n)))) (defgeneric semi-equal (x y &key tolerance) ) (defmethod semi-equal ((x number) (y number) &key (tolerance (+ *semi-equal-zero* (* *semi-equal-relativ* (norma (list (norma x) (norma y))))))) "@b(Описание:) функция @b(semi-equal) возвращает T, если расстояние между значениями меньше tolerance. При этом имеется в виду, что значения примерно равны. @b(Пример использования:) @begin[lang=lisp](code) (semi-equal 1.0 1.000001) T (semi-equal 1.0 1.00001) nil @end(code) " (< (distance x y) tolerance)) (defmethod semi-equal ((x cons) (y cons) &key (tolerance (+ *semi-equal-zero* (* *semi-equal-relativ* (norma (list (norma x) (norma y))))))) (when (and (= (length x) (length y)) (< (distance x y) tolerance)) t)) (defmethod semi-equal ((x vector) (y vector) &key (tolerance (+ *semi-equal-zero* (* *semi-equal-relativ* (norma (list (norma x) (norma y))))))) (when (and (= (length x) (length y)) (< (distance x y) tolerance)) t)) (defmethod semi-equal ((x1 vector) (x2 cons) &key (tolerance (+ *semi-equal-zero* (* *semi-equal-relativ* (norma (list (norma x1) (norma x2))))))) (semi-equal x1 (coerce x2 'vector) :tolerance tolerance)) (defmethod semi-equal ((x1 cons) (x2 vector) &key (tolerance (+ *semi-equal-zero* (* *semi-equal-relativ* (norma (list (norma x1) (norma x2))))))) (semi-equal (coerce x1 'vector) x2 :tolerance tolerance)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; /src/core/method.lisp ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; distance (defmethod distance ((x1 real) (x2 real)) " @b(Пример использования:) @begin[lang=lisp](code) (distance 1 0 ) => 1 (distance 2 0 ) => 2 (distance 2 1 ) => 1 @end(code)" (let ((rez (- x1 x2))) (abs rez))) (defmethod distance ((x1 number) (x2 number)) " @b(Пример использования:) @begin[lang=lisp](code) (distance (complex 1 2) 0) => 2.236068 (distance 0 (complex 1 2)) => 2.236068 (distance (complex 0 2) (complex 1 2)) => 1.0 @end(code)" (sqrt (+ (square (- (realpart x1) (realpart x2))) (square (- (imagpart x1) (imagpart x2)))))) (defmethod distance ((x1-lst cons) (x2-lst cons)) "@b(Описание:) метод @b(distance) возвращает расстояние между точками @b(x1-lst) и @b(x2-lst). @b(Пример использования:) @begin[lang=lisp](code) (distance '(1 1 1) '(0 0 0)) => 1.7320508 = (sqrt (+ 1 1 1)) (distance '(2 2 2) '(0 0 0)) => 3.4641016 = (sqrt (+ 4 4 4)) (distance '(2 1 2) '(0 0 0)) => 3.0 = (sqrt (+ 4 1 4)) @end(code)" (assert (= (length x1-lst) (length x1-lst))) (sqrt (apply #'+ (mapcar #'(lambda (x1 x2) (square (distance x1 x2))) x1-lst x2-lst)))) (defmethod distance ((x1 vector) (x2 vector)) "@b(Описание:) метод @b(distance) возвращает расстояние между точками @b(x1-lst) и @b(x2-lst). @b(Пример использования:) @begin[lang=lisp](code) (distance #(1 1 1) #(0 0 0)) => 1.7320508 (distance #(2 2 2) #(0 0 0)) => 3.4641016 (distance #(2 1 2) #(0 0 0)) => 3.0 @end(code)" (assert (= (length x1) (length x2))) (sqrt (loop :for i :from 0 :below (array-dimension x1 0) :summing (square (distance (svref x1 i) (svref x2 i)))))) (defmethod distance ((x1 vector) (x2 cons)) (distance x1 (coerce x2 'vector))) (defmethod distance ((x1 cons) (x2 vector)) (distance (coerce x1 'vector) x2)) ;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; distance-relative (defmethod distance-relative ((x number) (xi number) (dx number)) " @b(Пример использования:) @begin[lang=lisp](code) (distance-relative 1 0 1) => 1.0 (distance-relative 2 0 1) => 2.0 (distance-relative 2 0 2) => 1.0 @end(code)" (let ((rez (/ (- x xi) dx))) (sqrt (square rez)))) (defmethod distance-relative ((x-lst cons) (xi-lst cons) (dx-lst cons)) " @b(Пример использования:) @begin[lang=lisp](code) (distance-relative '(1 1 1) '(0 0 0) '(1 1 1)) => 1.7320508 (distance-relative '(2 2 2) '(0 0 0) '(1 1 1)) => 3.4641016 (distance-relative '(2 2 2) '(0 0 0) '(1 2 2)) => 2.4494898 @end(code)" (assert (apply #'= (mapcar #'length `(,x-lst ,xi-lst ,dx-lst)))) (sqrt (apply #'+ (mapcar #'(lambda (x xi dx) (let ((rez (/ (- x xi) dx))) (square rez))) x-lst xi-lst dx-lst)))) (defmethod distance-relative ((x vector) (xi vector) (dx vector)) " @b(Описание:) метод @b(distance-relative) возвращает относительное расстояние от точки @b(x) до точки @b(xi) по отношению к базовым длинам, находящимся в @b(dx). @b(Пример использования:) @begin[lang=lisp](code) (distance-relative #(1 1 1) #(0 0 0) #(1 1 1)) => 1.7320508 (distance-relative #(1 1 1) #(0 0 0) #(2 2 2)) => 0.8660254 (distance-relative #(1 2 3) #(0 0 0) #(3 2 1)) => 3.1797974 = (sqrt (+ (* 1/3 1/3) (* 2/2 2/2) (* 3/1 3/1))) @end(code) " (assert (apply #'= (mapcar #'length `(,x ,xi ,dx)))) (sqrt (apply #'+ (loop :for i :from 0 :below (array-dimension x 0) :collect (let ((rez (/ (- (svref x i) (svref xi i)) (svref dx i)))) (square rez)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; summ-distance (defmethod summ-distance ((x1 vector) (x2 vector)) "@b(Описание:) метод @b(summ-distance) возвращает сумму расстояний по каждому направлению. @b(Пример использования:) @begin[lang=lisp](code) (summ-distance #(1 2 3) #(3 2 1)) => 4 = (+ 2 0 2) @end(code) " (assert (= (length x1) (length x2))) (apply #'+ (loop :for i :from 0 :below (length x1) :collect (abs (- (svref x1 i) (svref x2 i)))))) (defmethod summ-distance ((x1 cons) (x2 cons)) "@b(Описание:) функция @b(summ-distance) возвращает сумму расстояний по каждому направлению. @b(Пример использования:) @begin[lang=lisp](code) (summ-distance '(1 2 3) '(3 2 1)) => 4 = (+ 2 0 2) @end(code) " (assert (= (length x1) (length x2))) (apply #'+ (mapcar #'(lambda (el1 el2) (abs (- el1 el2))) x1 x2)))
15,414
Common Lisp
.lisp
350
33.248571
109
0.55468
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
1c16d6a2609ead27437ff6ede0ccd571566da3141d8859302f9632fa93938166
11,071
[ -1 ]
11,072
rnd.lisp
mnasoft_math/src/rnd/rnd.lisp
;;;; ./src/rnd/rnd.lisp (defpackage :math/rnd (:use #:cl) (:export make-1d-list make-2d-list make-ls-system) (:documentation "@b(Описание:) пакет @b(math/rnd) содержит функции, предназначенные для создания случайных одномерных (1d-list) и двумерных (2d-list) списков, а также систем линейных уравнений со сручайным наперед заданным решением.")) (in-package :math/rnd) (defun make-1d-list (size &optional (arg 15)) "@b(Описание:) функция @b(make-1d-list) возвращает 1d-list длиной @b(size), состоящий из случайных целых чисел в диапазоне от 0 до @b(arg). @b(Пример использования:) @begin[lang=lisp](code) (make-1d-list 1) => (8) (make-1d-list 2) => (10 7) (make-1d-list 5) => (8 13 5 6 11) @end(code) " (loop :for i :from 0 :below size :collect (random arg))) (defun make-2d-list (size &optional (arg 15)) "@b(Описание:) функция @b(make-1d-list) возвращает 2d-list размером @b(size)*@b(size), состоящий из случайных целых чисел. @b(Пример использования:) @begin[lang=lisp](code) (make-2d-list 1) => ((9)) (make-2d-list 2) => ((9 4) (12 1)) (make-2d-list 5) '((2 12 5 4 8) (12 13 0 3 14) (10 9 13 2 3) ( 6 6 0 6 0) ( 1 0 3 10 6)) @end(code) " (loop :for i :from 0 :below size :collect (loop :for j :from 0 :below size :collect (random arg)))) (defun make-ls-system (m vec) "@b(Описание:) функция @b(make-ls-system) возвращает 2d-list, представляющий из себя расширенную матрицу (матрицу с правыми частями), являющуюся представлением системы линейных уравнений, при решении которой результатом будет @b(vec). @b(Пример использования:) @begin[lang=lisp](code) (let* ((n 1) (m (make-2d-list n)) (v (make-1d-list n))) (values (make-ls-system m v) v)) => ((2 14)), (7) (let* ((n 3) (m (make-2d-list n)) (v (make-1d-list n))) (values (make-ls-system m v) v)) => ((14 1 1 133) (0 2 12 84) (4 3 2 50)), (9 0 7) @end(code)" (assert (= (length m) (length vec))) (math/matr:append-col (mapcar #'(lambda(el) (apply #'+ (mapcar #'(lambda(v a) (* v a)) vec el))) m) m))
2,781
Common Lisp
.lisp
71
26.746479
70
0.595793
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
45148d62127cfaa1b5af9fd5f8d561f74f9b34fedbe94dd98b7f1a6bb3961d46
11,072
[ -1 ]
11,073
equation.lisp
mnasoft_math/src/equation/equation.lisp
;;;; ./src/equation/equation.lisp (defpackage :math/equation (:use #:cl) (:export tab func roots) (:export <linear> <quadric> <cubic> <quartic>) (:export coeff-a coeff-b coeff-c coeff-d coeff-e)) (in-package :math/equation) (defclass <linear> () ((a :accessor coeff-a :initform 1.0 :initarg :a :documentation "Коэффициент при степени 1.") (b :accessor coeff-b :initform -1.0 :initarg :b :documentation "Коэффициент при степени 0.")) (:documentation "@b(Описание:) класс @b(<linear>) представляет линейное уравнение вида: @b(Пример использования:) @begin[lang=c](code) f(x)=@b(a)*x+@b(b) @end(code) .")) (defclass <quadric> () ((a :accessor coeff-a :initform 1.0 :initarg :a :documentation "Коэффициент при степени 2.") (b :accessor coeff-b :initform 0.0 :initarg :b :documentation "Коэффициент при степени 1.") (c :accessor coeff-c :initform -1.0 :initarg :c :documentation "Коэффициент при степени 0.")) (:documentation "@b(Описание:) класс @b(<linear>) представляет квадратное уравнение вида: @begin[lang=c](code) f(x)=@b(a)*x@sup(2)+@b(b)*x+@b(c) @end(code) .")) (defclass <cubic> () ((a :accessor coeff-a :initform 1.0 :initarg :a :documentation "Коэффициент при степени 3.") (b :accessor coeff-b :initform 0.0 :initarg :b :documentation "Коэффициент при степени 2.") (c :accessor coeff-c :initform 0.0 :initarg :c :documentation "Коэффициент при степени 1.") (d :accessor coeff-d :initform -1.0 :initarg :d :documentation "Коэффициент при степени 0.")) (:documentation "@b(Описание:) класс @b(<linear>) представляет кубическое уравнение вида: @begin[lang=c](code) f(x)=@b(a)*x@sup(3)+@b(b)*x@sup(2)+@b(c)*x+@b(d) @end(code) .")) (defclass <quartic> () ((a :accessor coeff-a :initform 1.0 :initarg :a :documentation "Коэффициент при степени 4.") (b :accessor coeff-b :initform 0.0 :initarg :b :documentation "Коэффициент при степени 3.") (c :accessor coeff-c :initform 0.0 :initarg :c :documentation "Коэффициент при степени 2.") (d :accessor coeff-d :initform 0.0 :initarg :d :documentation "Коэффициент при степени 1.") (e :accessor coeff-e :initform -1.0 :initarg :e :documentation "Коэффициент при степени 1.")) (:documentation "@b(Описание:) класс @b(<linear>) представляет уравнение четвертой степени вида: @begin[lang=c](code) f(x)=@b(a)*x@sup(4)+@b(b)*x@sup(3)+@b(c)*x@sup(2)+@b(d)*x+@b(e) @end(code) .")) (defmethod print-object ((eq <linear>) s) (print-unreadable-object (eq s :type t) (format s "f(x)=(~S)*x+(~S)" (coeff-a eq) (coeff-b eq)))) (defmethod print-object ((eq <quadric>) s) (print-unreadable-object (eq s :type t) (format s "f(x)=(~S)*x^2+(~S)*x+(~S)" (coeff-a eq) (coeff-b eq) (coeff-c eq)))) (defmethod print-object ((eq <cubic>) s) (print-unreadable-object (eq s :type t) (format s "f(x)=(~S)*x^3+(~S)*x^2+(~S)*x+(~S)" (coeff-a eq) (coeff-b eq) (coeff-c eq) (coeff-d eq)))) (defmethod print-object ((eq <quartic>) s) (print-unreadable-object (eq s :type t) (format s "f(x)=(~S)*x^4+(~S)*x^3+(~S)*x^2+(~S)*x+(~S)" (coeff-a eq) (coeff-b eq) (coeff-c eq) (coeff-d eq) (coeff-e eq)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defgeneric tab (eq x) (:documentation "@b(Описание:) обобщенная_функция @b(tab) возвращает значение фукции @b(eq) в точке @b(x).")) (defgeneric roots (eq) (:documentation "@b(Описание:) обобщенная_функция @b(roots) возвращает корни уравнения @b(eq).")) (defgeneric func (eq) (:documentation "@b(Описание:) обобщенная_функция @b(func) функцию одного переменного, представляющее полином.")) (defmethod func ((eq <linear>)) " @b(Пример использования:) @begin[lang=lisp](code) (funcall (func (make-instance '<linear>)) 1) => 0.0 @end(code) " (values #'(lambda (x) (+ (* x (coeff-a eq)) (coeff-b eq))) (format nil "~S" eq))) (defmethod func ((eq <quadric>)) " @b(Пример использования:) @begin[lang=lisp](code) (funcall (func (make-instance '<quadric>)) 2) => 3.0 @end(code) " (values #'(lambda (x) (+ (* x x (coeff-a eq)) (* x (coeff-b eq)) (coeff-c eq))) (format nil "~S" eq))) (defmethod func ((eq <cubic>)) " @b(Пример использования:) @begin[lang=lisp](code) (funcall (func (make-instance '<cubic>)) 5) => 124.0 @end(code) " (values #'(lambda (x) (+ (* x x x (coeff-a eq)) (* x x (coeff-b eq)) (* x (coeff-c eq)) (coeff-d eq))) (format nil "~S" eq))) (defmethod func ((eq <quartic>)) " @b(Пример использования:) @begin[lang=lisp](code) (funcall (func (make-instance '<quartic>)) 0) => -1.0 @end(code) " (values #'(lambda (x) (+ (* x x x x (coeff-a eq)) (* x x x (coeff-b eq)) (* x x (coeff-c eq)) (* x (coeff-d eq)) (coeff-e eq))) (format nil "~S" eq))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod tab ((eq <linear>) x) (let ((a (coeff-a eq)) (b (coeff-b eq))) (+ (* a x ) b))) (defmethod tab ((eq <quadric>) x) (let ((a (coeff-a eq)) (b (coeff-b eq)) (c (coeff-c eq))) (+ (* a x x) (* b x) c))) (defmethod tab ((eq <cubic>) x) (let ((a (coeff-a eq)) (b (coeff-b eq)) (c (coeff-c eq)) (d (coeff-d eq))) (+ (* a x x x) (* b x x) (* c x) d))) (defmethod tab ((eq <quartic>) x) " @b(Пример использования:) @begin[lang=lisp](code) (roots (make-instance '<linear> :a 1 :b -2)) @end(code)" (let ((a (coeff-a eq)) (b (coeff-b eq)) (c (coeff-c eq)) (d (coeff-d eq)) (e (coeff-e eq))) (+ (* a x x x x) (* b x x x) (* c x x) (* d x) e))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod roots ((eq <linear>)) (let ((a (coeff-a eq)) (b (coeff-b eq))) (- (/ b a)))) (defmethod roots ((eq <quadric>)) " @b(Пример использования:) @begin[lang=lisp](code) (roots (make-instance '<quadric> :a 1 :b -2 :c 1)) => (1.0 1.0) (roots (make-instance '<quadric> :a 1 :b -4 :c 4)) => (2.0 2.0) @end(code)" (let ((a (coeff-a eq)) (b (coeff-b eq)) (c (coeff-c eq))) (let ((Δ (sqrt (- (* b b) (* 4 a c))))) (list (/ (+ (- b) Δ) 2 a) (/ (+ (- b) (- Δ)) 2 a))))) (defmethod roots ((eq <cubic>)) " @b(Пример использования:) @begin[lang=lisp](code) (roots (make-instance '<cubic> :a 2 :b -3 :c -3 :d 2)) => (#C(-1.0d0 -0.0d0) #C(0.5000000000000004d0 2.9605947323337506d-16) #C(1.9999999999999996d0 -2.9605947323337506d-16)) (roots (make-instance '<cubic> :a 1 :b 2 :c 10 :d -20)) => (#C(-1.6844040539106864d0 -3.4313313501976914d0) #C(1.3688081078213714d0 1.9558293600573398d-16) #C(-1.684404053910686d0 3.4313313501976905d0)) (roots (make-instance '<cubic> :a 1 :b -6 :c 12 :d -8)) => (2.0d0 2.0d0 2.0d0) @end(code)" (let ((a (coeff-a eq)) (b (coeff-b eq)) (c (coeff-c eq)) (d (coeff-d eq)) (ξ (* 0.5d0 (+ -1.0d0 (sqrt -3.0d0))))) (let* ((Δ0 (- (* b b) (* 3d0 a c))) (Δ1 (+ (* 2d0 b b b) (* -9.0d0 a b c) (* 27.0d0 a a d))) (c+ (expt (/ (+ Δ1 (sqrt (- (* Δ1 Δ1) (* 4.0d0 Δ0 Δ0 Δ0)))) 2d0) (/ 3d0))) (c- (expt (/ (- Δ1 (sqrt (- (* Δ1 Δ1) (* 4.0d0 Δ0 Δ0 Δ0)))) 2d0) (/ 3d0))) (c (if (< (abs c-) (abs c+)) c+ c-))) (if (= Δ0 Δ1 0.0d0) (loop :for k :from 0 :to 2 :collect (/ (- b) (* 3.0d0 a))) (loop :for k :from 0 :to 2 :collect (* (/ -1.0d0 (* 3.0d0 a)) (+ b (* (expt ξ k) c) (/ Δ0 (* (expt ξ k) c))))))))) (defmethod roots ((eq <quartic>)) "@b(Описание:) метод @b(roots) возвращает список корней кубического уравнения @b(eq)." (error "Not yet defined."))
8,819
Common Lisp
.lisp
213
32.525822
103
0.552357
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
3729635f27b7bb51c5d0dbee360ebd5c06be83d5c83c94ff960b60731b5d5872
11,073
[ -1 ]
11,074
obj.lisp
mnasoft_math/src/obj/obj.lisp
(defpackage :math/obj (:use #:cl) (:export b* b/ b+ b- ;; Операции биаргументного умножения, деления, слоожения и вычитания; m* m/ m+ m- ;; Операции мультиаргументного умножения, деления, слоожения и вычитания; ) (:export point-3d <point-3d> <point-3d>-x <point-3d>-y <point-3d>-z ) (:export <vector-3d> <vector-3d>-x <vector-3d>-y <vector-3d>-z )) (in-package :math/obj) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun b (i n p) (* (math/stat:combinations i n) (expt p i) (expt (- 1 p) (- n i)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defclass <point-3d> () ((x :accessor <point-3d>-x :initform 0.0d0 :initarg :x :type 'double-float ) (y :accessor <point-3d>-y :initform 0.0d0 :initarg :y :type 'double-float ) (z :accessor <point-3d>-z :initform 0.0d0 :initarg :z :type 'double-float ))) (defmethod print-object ((point-3d <point-3d>) s) (format s "(~A ~A ~A)" (<point-3d>-x point-3d) (<point-3d>-y point-3d) (<point-3d>-z point-3d))) (defclass <vector-3d> () ((x :accessor <vector-3d>-x :initform 0.0d0 :initarg :x :type 'double-float ) (y :accessor <vector-3d>-y :initform 0.0d0 :initarg :y :type 'double-float ) (z :accessor <vector-3d>-z :initform 0.0d0 :initarg :z :type 'double-float ))) (defmethod print-object ((vector-3d <vector-3d>) s) (format s "(~A ~A ~A)" (<vector-3d>-x vector-3d) (<vector-3d>-y vector-3d) (<vector-3d>-z vector-3d))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun point-3d (x y z) (make-instance '<point-3d> :x (coerce x 'double-float) :y (coerce y 'double-float) :z (coerce z 'double-float))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defgeneric b* (v1 v2) (:documentation "@b(Описание:) обобщенная_функция @b(b*) умножение 2-х аргументов.")) (defgeneric b/ (v1 v2) (:documentation "@b(Описание:) обобщенная_функция @b(b*) деление 2-х аргументов.")) (defgeneric b+ (v1 v2) (:documentation "@b(Описание:) обобщенная_функция @b(b*) сложение 2-х аргументов.")) (defgeneric b- (v1 v2) (:documentation "@b(Описание:) обобщенная_функция @b(b*) вычитание 2-х аргументов.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod b* ((v1 number) (v2 number)) (* v1 v2)) (defmethod b* ((v1 number)(p <point-3d>)) (let ((rez (make-instance '<point-3d>)) ) (setf (<point-3d>-x rez) (* v1 (<point-3d>-x p))) (setf (<point-3d>-y rez) (* v1 (<point-3d>-y p))) (setf (<point-3d>-z rez) (* v1 (<point-3d>-z p))) rez)) (defmethod b* ((p <point-3d>) (v1 number)) (b* v1 p)) ;;;;;;;;;; (defmethod b+ ((v1 number)(v2 number)) (+ v1 v2)) (defmethod b+ ((p1 <point-3d>) (p2 <point-3d>)) (let ((rez (make-instance '<point-3d>)) ) (setf (<point-3d>-x rez) (+ (<point-3d>-x p1) (<point-3d>-x p2))) (setf (<point-3d>-y rez) (+ (<point-3d>-y p1) (<point-3d>-y p2))) (setf (<point-3d>-z rez) (+ (<point-3d>-z p1) (<point-3d>-z p2))) rez)) ;;;;;;;;;; (defmethod b- ((p1 <point-3d>) (p2 <point-3d>)) (let ((vec (make-instance '<vector-3d>)) ) (setf (<vector-3d>-x vec) (- (<point-3d>-x p2) (<point-3d>-x p1))) (setf (<vector-3d>-y vec) (- (<point-3d>-y p2) (<point-3d>-y p1))) (setf (<vector-3d>-z vec) (- (<point-3d>-z p2) (<point-3d>-z p1))) vec)) (defmethod b/ ((v1 number) (v2 number)) (/ v1 v2)) (defmethod b/ ((p <point-3d>) (v number)) (let ((rez (make-instance '<point-3d>))) (setf (<point-3d>-x rez) (/ (<point-3d>-x p) v)) (setf (<point-3d>-y rez) (/ (<point-3d>-y p) v)) (setf (<point-3d>-z rez) (/ (<point-3d>-z p) v)) rez)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun m* (v &rest rest) (reduce #'(lambda (el1 el2) (b* el1 el2)) rest :initial-value v)) (defun m/ (v &rest rest) (reduce #'(lambda (el1 el2) (b/ el1 el2)) rest :initial-value v)) (defun m- (v &rest rest) (reduce #'(lambda (el1 el2) (b- el1 el2)) rest :initial-value v)) (defun m+ (v &rest rest) (reduce #'(lambda (el1 el2) (b+ el1 el2)) rest :initial-value v)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun B-point (prm points &key (weights (make-list (length points) :initial-element 1.0d0))) (let ((n (1- (length points)))) (loop :for i :from 0 :to n :for w :in weights :collect (m* (b i n prm) (svref points i) w) :into a-first :collect (m* (b i n prm) w) :into a-second :finally (return (m/ (apply #'m+ a-first) (apply #'m+ a-second)))))) (progn (defparameter *p* (vector (point-3d 0 -1 0) (point-3d 0.66 -1.0 0.0) (point-3d 1.0 -0.66 0.0) (point-3d 1.0 0.0 0.0))) (defparameter w '(1d0 1.66666666666666d0 3d0 1.66666666666666d0 1d0)) (defparameter *pts* (loop :for i :from 0 :to 100 :collect (let ((p (B-point (/ i 100) *p* ))) ;; :weights w (list (<point-3d>-x p) (<point-3d>-y p))))) (vgplot:plot (map 'list #'first *pts*) (map 'list #'second *pts*) "" (map 'list #'(lambda (p) (<point-3d>-x p ) ) *p*) (map 'list #'(lambda (p) (<point-3d>-y p ) ) *p*) "")) #+nil (progn (vgplot:format-plot t "unset tics") (vgplot:format-plot t "set label ") (vgplot:xlabel "X") (vgplot:ylabel "Y"))
6,161
Common Lisp
.lisp
136
37.426471
100
0.488106
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
06240d6d06dcee5a67b4863495c41fc01b5ba66c0e5628d027ced3ca18f29742
11,074
[ -1 ]
11,075
math.asd
mnasoft_math/math.asd
;;;; math.asd (defsystem "math" :description "Math is a math library, implementing some algorithms: @begin(list) @item(linear algebra;) @item(operations with matrices;) @item(statistical functions;) @item(linear and bilinear interpolation;) @item(finding approximating polynomials, implemented in Common Lisp.) @end(list) " :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :version "0.0.3" :serial t :in-order-to ((test-op (test-op "math/tests"))) :depends-on ("cl-utilities" "math/core" "math/coord" "math/matr" "math/geom" "math/equation" "math/stat" "math/smooth" "math/rnd" "math/ls-gauss" "math/ls-gsll" "math/ls-rotation" "math/gnuplot" "math/appr" "math/series" "math/half-div" ;; "math/x-o" ) ;;;; "math/tests" :components ((:module "src/math" :serial t :components ((:file "math"))))) ;;;; (:file "matr-temp") (defsystem "math/half-div" :description "Describe half-div here" :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :serial t :components ((:module "src/half-div" :serial nil :components ((:file "half-div") (:file "half-div-doc" :depends-on ("half-div")))))) (defsystem "math/series" :description "@b(Описание:) система @b(math/series) определяет некоторые операции с прогрессиями." :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :serial t :depends-on ("math/half-div" "math/equation") :components ((:module "src/series" :serial nil :components ((:file "series") (:file "series-doc" :depends-on ("series")))))) (defsystem "math/rnd" :description "Содержит функции для генерирования случайных списков и 2d-списков." :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :serial t :depends-on ("math/matr") :in-order-to ((test-op (test-op "math/core/tests"))) :components ((:module "src/rnd" :serial nil :components ((:file "rnd") (:file "rnd-doc" :depends-on ("rnd")))))) (defsystem "math/core" :description "Содержит некоторые функции и обобщенные функции, используемые в проекте повсеместно" :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :serial t :in-order-to ((test-op (test-op "math/core/tests"))) ;; :depends-on () :components ((:module "src/core" :serial nil :components ((:file "core") (:file "core-doc" :depends-on ("core")))))) (defsystem "math/ls-rotation" :description "Реализация решение системы линейных уравнений методом вращения" :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :serial t :in-order-to ((test-op (test-op "math/ls-rotation/tests"))) :depends-on ("math/matr") :components ((:module "src/ls-rotation" :serial t :components ((:file "ls-rotation") (:file "ls-rotation-doc"))))) (defsystem "math/gnuplot" :description "Интерфейс к программе построения графиков gnuplot" :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :serial t :in-order-to ((test-op (test-op "math/gnuplot/tests"))) :depends-on ("math/core" "font-discovery" "vgplot") :components ((:module "src/gnuplot" :serial t :components ((:file "gnuplot") (:file "gnuplot-doc" :depends-on ("gnuplot")))))) (defsystem "math/ls-gauss" :description "Решение систем линейных уравнений методом Гаусса" :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :serial t :in-order-to ((test-op (test-op "math/ls-gauss/tests"))) :depends-on ("math/matr") :components ((:module "src/ls-gauss" :serial t :components ((:file "ls-gauss") (:file "ls-gauss-doc"))))) (defsystem "math/appr" :description "Describe math here" :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :serial t :in-order-to ((test-op (test-op "math/appr/tests"))) :depends-on ("math/core" "math/matr" "math/ls-gauss" "math/smooth") :components ((:module "src/appr" :serial t :components ((:file "appr") (:file "appr-doc"))))) (defsystem "math/stat" :description "Describe math here" :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :serial t :in-order-to ((test-op (test-op "math/stat/tests"))) :depends-on ("math/core" "gsll") :components ((:module "src/stat" :serial t :components ((:file "stat") (:file "stat-doc" :depends-on ("stat")))))) (defsystem "math/smooth" :description "Весовые функции для методов сглаживания" :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :serial t :in-order-to ((test-op (test-op "math/smooth/tests"))) ;;; :depends-on (:math) :components ((:module "src/smooth" :serial t :components ((:file "smooth") (:file "smooth-doc" :depends-on ("smooth")))))) (defsystem "math/coord" :description "Содержит функции преобразования - угловой меры; - координат точки между декартовой, полярной, сферической системами координат. " :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :serial t :in-order-to ((test-op (test-op "math/coord/tests"))) :depends-on ("math/core") :components ((:module "src/coord" :serial t :components ((:file "coord") (:file "coord-doc"))))) (defsystem "math/ls-gsll" :description "Решение систем линейных уравнений при помощи библиотеки gsll" :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :serial t :in-order-to ((test-op (test-op "math/tests"))) :depends-on ("gsll" "math/matr") :components ((:module "src/ls-gsll" :serial t :components ((:file "ls-gsll") (:file "ls-gsll-doc"))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defsystem "math/tests" :description "Тестирование систем, входящих в проект Math" :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :depends-on (:math :fiveam) :perform (test-op (o s) (uiop:symbol-call :math-tests :test-math)) :components ((:module "src/tests" :serial t :components ((:file "package") (:file "all") (:file "core") (:file "2d-array") (:file "matrix") (:file "list-matr-tests") (:file "equation") (:file "ls-gauss") (:file "ls-gsll") (:file "ls-rotation") (:file "appr") (:file "coord") (:file "half-div") (:file "run") )))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defsystem "math/geom" :description "Функции вычисления площадей и объемов геометрических фигур и тел." :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :serial t :in-order-to ((test-op (test-op "math/ls-rotation/tests"))) ;;;; :depends-on ("math/arr-matr") :components ((:module "src/geom" :serial t :components ((:file "geom") (:file "geom-doc"))))) (defsystem "math/docs" :description " @b(Описание:) система @b(math/docs) содержит функции для извлечения сборки и публикации документации. Для публикации документации в системе должна быть установлена программа @b(rsync)." :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :depends-on ("math" "mnas-package" "codex") :components ((:module "src/docs" :serial nil :components ((:file "docs"))))) (defsystem "math/equation" :description "@b(Описание:) система @b(math/equation) содержит функции для нахождения корней линейных, квадратных, кубических и уравнений 4-ой степени (последнее не реализовано)." :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :serial t :in-order-to ((test-op (test-op "math/ls-rotation/tests"))) ;;;; :depends-on ("math/arr-matr") :components ((:module "src/equation" :serial t :components ((:file "equation") (:file "equation-doc"))))) (defsystem "math/matr" :description "@b(Описание:) система @b(math/matr) содержит некоторых операций над матрицами" :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :serial t :depends-on ("cl-utilities" "math/coord" "math/stat" "closer-mop") :components ((:module "src/matr" :serial t :components ((:file "matr") (:file "generics") (:file "methods/add") (:file "methods/anti-diagonal") (:file "methods/append") (:file "methods/average") (:file "methods/col") (:file "methods/cols") (:file "methods/copy") (:file "methods/dimensions") (:file "methods/equivalent") (:file "methods/main-diagonal") (:file "methods/mref") (:file "methods/multiply") (:file "methods/prepend") (:file "methods/rotate") (:file "methods/row") (:file "methods/rows") (:file "methods/squarep") (:file "methods/swap-cols") (:file "methods/swap-rows") (:file "methods/transpose") (:file "methods/unite-cols") (:file "methods/unite-rows") (:file "matr-doc"))))) (defsystem "math/obj" :description "@b(Описание:) система @b(math/obj) содержит описание некоторых геометрических объектов." :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :serial t :depends-on ("gsll" "math/stat" "vgplot") :components ((:module "src/obj" :serial t :components ((:file "obj"))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defsystem "math/x-o" :description "Консольная игра крестики-нолики" :author "Mykola Matvyeyev <[email protected]>" :license "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 or later" :serial t :in-order-to ((test-op (test-op "math/x-o/tests"))) :depends-on ( "math/core" "math/matr") :components ((:module "src/x-o" :serial t :components ((:file "x-o")))))
13,388
Common Lisp
.asd
292
33.061644
100
0.571133
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
0653678f8a3f662dfc0069209117d58b55a9788d357fc67cef03fe8360f6b477
11,075
[ -1 ]
11,077
FUNDING.yml
mnasoft_math/FUNDING.yml
# These are supported funding model platforms github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: mnasoft open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
678
Common Lisp
.l
11
60.545455
91
0.791291
mnasoft/math
14
1
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
d48a1b313e51fd912b55fdf88e514bb0804fbeb8b5967ad5b2dc9828d9816736
11,077
[ -1 ]
11,155
browser.lisp
lambdamikel_GenEd/src/browser.lisp
;;; ---------------------------------------------------------------------- (define-presentation-type concept ()) (define-presentation-method presentation-typep ((object t) (type concept)) (classic:cl-named-concept (classic:cl-name object))) (define-presentation-method present (object (type concept) stream (view textual-view) &key) (format stream "~S" (classic:cl-name object))) (define-presentation-method accept ((type concept) stream (view textual-view) &key) (completing-from-suggestions (stream) (dolist (concept (classic:cl-concept-descendants (classic:cl-named-concept 'classic:thing))) (suggest (format nil "~S" (classic:cl-name concept)) concept)))) (defun print-concept-node (concept-node stream) (with-output-as-presentation (stream concept-node 'concept :single-box t) (surrounding-output-with-border (stream :shape :ellipse) (format stream "~S" (classic:cl-name concept-node))))) (defun draw-concept-graph-arc-superconcept (stream from-node to-node x1 y1 x2 y2 &rest drawing-options &key path) (declare (ignore from-node to-node drawing-options)) (if (null path) (draw-arrow* stream x2 y2 x1 y1) (let ((x3 (first path)) (y3 (second path))) (draw-arrow* stream x3 y3 x1 y1) (draw-polygon* stream (append path (list x2 y2)) :filled nil :closed nil)))) (defun draw-concept-graph-arc-subconcept (stream from-node to-node x1 y1 x2 y2 &rest drawing-options &key path) (declare (ignore from-node to-node drawing-options)) (if (null path) (draw-arrow* stream x1 y1 x2 y2) (let ((x3 (first path)) (y3 (second path))) (draw-arrow* stream x1 y1 x3 y3) (draw-polygon* stream (append path (list x2 y2)) :filled nil :closed nil)))) (defun filter-concept-parents (concept) (classic:cl-concept-parents concept)) (defun filter-concept-children (concept) (classic:cl-concept-children concept)) (defmethod draw-concept-hierarchy ((frame gened) stream &key) (let ((current-concepts (gened-current-concepts frame))) (when current-concepts (updating-output (stream :unique-id 'concept-hierarchy :cache-test #'equal :cache-value current-concepts) (stream-set-cursor-position stream 10 10) (if (gened-show-super-concepts-p frame) (format-graph-from-roots current-concepts 'print-concept-node 'filter-concept-parents :graph-type :dag :generation-separation 30 :arc-drawer 'draw-concept-graph-arc-superconcept :stream stream :orientation ':vertical :merge-duplicates t) (format-graph-from-roots current-concepts 'print-concept-node 'filter-concept-children :graph-type :dag :generation-separation 30 :arc-drawer 'draw-concept-graph-arc-subconcept :stream stream :orientation ':horizontal :merge-duplicates t)))))) (defmethod draw-concept-description ((frame gened) stream &key) (let ((concept (gened-described-concept frame))) (updating-output (stream :unique-id 'concept-info :cache-value concept) (when concept (let ((*standard-output* stream)) (classic:cl-print-object concept)))))) ;;; ---------------------------------------------------------------------- (define-gened-command (com-clear-output-history :name t :menu nil) () (with-application-frame (gened-frame) (window-clear (get-frame-pane gened-frame 'listener-pane)))) (define-gened-command (com-show-concept-descendants :name t :menu nil) ((concept '(or concept expression))) (with-application-frame (gened-frame) (window-set-viewport-position (get-frame-pane gened-frame 'concept-hierarchy-display-pane) 0 0) (setf (gened-show-super-concepts-p gened-frame) nil) (setf (gened-current-concepts gened-frame) (list concept)))) (define-presentation-to-command-translator show-concept-descendants-translator (concept com-show-concept-descendants gened) (object) (list object)) (define-gened-command (com-show-concept-ancestors :name t :menu nil) ((concept '(or concept expression))) (with-application-frame (gened-frame) (window-set-viewport-position (get-frame-pane gened-frame 'concept-hierarchy-display-pane) 0 0) (setf (gened-show-super-concepts-p gened-frame) t) (setf (gened-current-concepts gened-frame) (list concept)))) (define-gesture-name :select-super :pointer-button (:left :shift)) (define-presentation-to-command-translator show-concept-ancestors-translator (concept com-show-concept-ancestors gened :gesture :select-super) (object) (list object)) (define-gened-command (com-show-concept-info :name t :menu nil) ((concept '(or concept expression))) (with-application-frame (gened-frame) (setf (gened-described-concept gened-frame) concept))) (define-presentation-to-command-translator show-concept-info-translator ((or concept expression) com-show-concept-info gened :gesture :describe :tester ((object) (setf *x* object) (classic:cl-concept? object))) (object) (list object))
5,364
Common Lisp
.lisp
142
31.65493
82
0.665694
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
a4914891a318fe7710935fd07e2fa84e30e47a561b1f22fbd17cfa4f08ef2da4
11,155
[ -1 ]
11,156
classesxx.lisp
lambdamikel_GenEd/src/classesxx.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defclass object-handle () ((x :accessor x :initarg :x) (y :accessor y :initarg :y) (parent-object :accessor parent-object :initarg :parent-object))) (defclass start-handle (object-handle) ()) (defclass end-handle (object-handle) ()) (defclass unfixed-object-handle (object-handle) ()) (defclass fixed-object-handle (object-handle) ((fixed-at-object :accessor fixed-at-object :initform nil))) (defclass unfixed-start-handle (unfixed-object-handle start-handle) ()) (defclass unfixed-end-handle (unfixed-object-handle end-handle) ()) (defclass fixed-start-handle (fixed-object-handle start-handle) ()) (defclass fixed-end-handle (fixed-object-handle end-handle) ()) ;;; ;;; ;;; (defclass linestyle-mixin () ((linestyle :initform nil :initarg :linestyle :accessor linestyle))) (defclass ink-mixin () ((ink :initform 0.0 :initarg :ink :accessor ink))) (defclass linethickness-mixin () ((linethickness :initform 1 :initarg :linethickness :accessor linethickness))) (defclass filled-mixin () ((filledp :initform nil :initarg :filledp :accessor filledp) (filled-ink :initform 0.0 :initarg :filled-ink :accessor filled-ink))) (defclass sit-mixin (linestyle-mixin ink-mixin linethickness-mixin) ()) ;;; ;;; ;;; (defclass thing () ((attached-handles :initform nil :accessor attached-handles) (tickval :initform 0 :accessor tickval) (associated-classic-ind :initform nil :accessor associated-classic-ind) (initialize :initform nil :initarg :initialize :accessor initialize) (xtrans :initform 0 :accessor xtrans :initarg :xtrans) (ytrans :initform 0 :accessor ytrans :initarg :ytrans) (parent-concepts :initform nil :accessor parent-concepts :initarg :parent-concepts) (ancestor-concepts :initform nil :accessor ancestor-concepts) (hidden :initform nil :accessor hiddenp :initarg :hiddenp) (output-record :accessor output-record1) (id-number :accessor id-number :initform 0) (highlighted :initform nil :accessor highlightedp) (br-left :accessor br-left) (br-right :accessor br-right) (br-top :accessor br-top) (br-bottom :accessor br-bottom))) (defclass basic-thing (thing) ((polygonized-representation :initform nil :accessor polygonized-representation))) ;;; ;;; ;;; (defclass rotateable-thing () ((rotangle :initform 0 :accessor rotangle))) (defclass scaleable-thing () ((xscale :initform 1.0 :accessor xscale :initarg :xscale) (yscale :initform 1.0 :accessor yscale :initarg :yscale) (init-x-extend :accessor init-x-extend) (init-y-extend :accessor init-y-extend))) (defclass scale-and-rotateable-thing (scaleable-thing rotateable-thing) ()) ;;; ;;; ;;; (defclass object-with-handles () ((handles :accessor handles :initarg :handles :initform nil) (initialize-handles :accessor initialize-handles :initform nil :initarg :initialize-handles))) (defclass pointlist-object () ((pointlist :initform nil :initarg :pointlist :accessor pointlist))) (defclass spline-object () ((spline-points :initform nil :accessor spline-points))) (defclass object-with-head () ((head :initform t :initarg :head :accessor head))) (defclass linesegment () ((startpoint :initform '(-10 -10) :initarg :startpoint :accessor startpoint) (endpoint :initform '(10 10) :initarg :endpoint :accessor endpoint))) (defclass directed-info-element () ((startpoint-related-with :initform nil :initarg :startpoint-related-with :accessor startpoint-related-with) (endpoint-related-with :initform nil :initarg :endpoint-related-with :accessor endpoint-related-with) (start-info-point :initform nil :initarg :start-info-point :accessor start-info-point) (end-info-point :initform nil :initarg :end-info-point :accessor end-info-point))) ;;; ;;; ;;; (defclass at-least-0d-object () ()) (defclass at-least-1d-object () ()) (defclass at-least-2d-object () ()) (defclass 0d (at-least-0d-object) ((part-of-cluster :initarg :part-of-cluster :initform nil :accessor part-of-cluster) (disjoint-with :initform nil :accessor disjoint-with) (start-linked-over-with :initform nil :accessor start-linked-over-with) (end-linked-over-with :initform nil :accessor end-linked-over-with) (start-linker-objects :initform nil :accessor start-linker-objects) (end-linker-objects :initform nil :accessor end-linker-objects) (in-relation-with-objects :initform nil :accessor in-relation-with-objects) (intersects-objects :initform nil :accessor intersects-objects) (intersects-0-objects :initform nil :accessor intersects-0-objects) (touching-objects :initform nil :accessor touching-objects) (contained-in-objects :initform nil :accessor contained-in-objects) (covered-by-objects :initform nil :accessor covered-by-objects) (directly-contained-by-object :initform nil :accessor directly-contained-by-object))) (defclass 1d (0d at-least-1d-object) ((intersects-1-objects :initform nil :accessor intersects-1-objects))) (defclass 2d (1d at-least-2d-object) ((intersects-2-objects :initform nil :accessor intersects-2-objects) (contains-objects :initform nil :accessor contains-objects) (directly-contains-objects :initform nil :accessor directly-contains-objects) (covers-objects :initform nil :accessor covers-objects))) ;;; ;;; ;;; (defclass composite-thing (thing 2d) ((liste :initform nil :accessor liste :initarg :liste))) ;;; ;;; ;;; (defclass g-point (basic-thing 0d linethickness-mixin ink-mixin) ()) (defclass info-point (basic-thing 0d) ((startpoint-of :initform nil :initarg :startpoint-of :accessor startpoint-of) (endpoint-of :initform nil :initarg :endpoint-of :accessor endpoint-of))) (defclass g-circle (basic-thing 2d scaleable-thing sit-mixin filled-mixin) ((radius :initform 0 :accessor radius :initarg :radius))) (defclass g-rectangle (basic-thing 2d scale-and-rotateable-thing sit-mixin filled-mixin) ((xextend :initform 10 :accessor xextend :initarg :xextend) (yextend :initform 10 :accessor yextend :initarg :yextend))) (defclass g-text (basic-thing 2d ink-mixin) ((text-string :initform "Text" :accessor text-string :initarg :text-string) (face :initform :bold :initarg :face :accessor face) (size :initform :large :initarg :size :accessor size) (family :initform :sans-serif :initarg :family :accessor family))) (defclass g-polygon (basic-thing 2d scale-and-rotateable-thing object-with-handles pointlist-object sit-mixin filled-mixin) ()) (defclass g-arrow (basic-thing 1d rotateable-thing object-with-handles linesegment object-with-head sit-mixin directed-info-element) ()) (defclass g-chain (basic-thing 1d rotateable-thing pointlist-object object-with-handles object-with-head sit-mixin directed-info-element) ()) (defclass g-spline-chain (basic-thing spline-object 1d rotateable-thing pointlist-object object-with-handles object-with-head sit-mixin directed-info-element) ()) (defclass g-spline-polygon (basic-thing spline-object 2d scale-and-rotateable-thing pointlist-object object-with-handles sit-mixin filled-mixin) ()) ;;; ;;; ;;; (defmethod startpoint ((object pointlist-object)) (list (first (pointlist object)) (second (pointlist object)))) (defmethod endpoint ((object pointlist-object)) (last (pointlist object) 2)) ;;; ;;; ;;; (defmethod print-object ((object thing) stream) (format stream "~A = ~D" (type-of object) (id-number object))) (defmethod print-object ((object object-handle) stream) (format stream "Handle Of ~A" (parent-object object))) (define-presentation-method present (object (type thing) stream (view textual-view) &key) (print-object object stream)) (define-presentation-method accept ((type thing) stream (view textual-view) &key) (with-application-frame (gened-frame) (with-slots (liste) gened-frame (completing-from-suggestions (stream) (dolist (elem liste) (suggest (write-to-string (id-number elem)))))))) ;;; ;;; ;;; (defun strange-polygon (object) (let ((pointlist (generate-brackets (pointlist object)))) (some #'(lambda (co1 co2 co3) (let* ((x1 (first co1)) (y1 (second co1)) (x2 (first co2)) (y2 (second co2)) (x3 (first co3)) (y3 (second co3))) (multiple-value-bind (d1 phi1) (distance-and-orientation x1 y1 x2 y2) (declare (ignore d1)) (multiple-value-bind (d2 phi2) (distance-and-orientation x2 y2 x3 y3) (declare (ignore d2)) (zerop (- (+ phi1 phi2) pi)))))) pointlist (cdr pointlist) (cddr pointlist)))) (defmethod strange-polygon-p ((object g-polygon)) (strange-polygon object)) (defmethod strange-polygon-p ((object g-spline-polygon)) (strange-polygon object)) ;;; ;;; ;;; (defmethod self-intersecting-p ((object pointlist-object)) (unless (<= (length (pointlist object)) 6) (let* ((pointlist (let ((brackets (generate-brackets (pointlist object)))) (if (or (typep object 'g-spline-polygon) (typep object 'g-polygon)) (append brackets (list (first brackets))) brackets))) (lines (mapcar #'(lambda (point1 point2) (let* ((p1 (make-geom-point (first point1) (second point1))) (p2 (make-geom-point (first point2) (second point2)))) (make-geom-line p1 p2))) pointlist (cdr pointlist)))) (some #'(lambda (l1) (let ((count (count-if #'(lambda (l2) (intersects l1 l2)) (remove l1 lines :test #'equal)))) (cond ((or (typep object 'g-polygon) (typep object 'g-spline-polygon)) (> count 2)) (t (or (and (eq l1 (first lines)) (> count 1)) (and (eq l1 (first (last lines))) (> count 1)) (> count 2)))))) lines)))) ;;; ;;; ;;; (defmethod object-ok-p ((object g-polygon)) (and (not (strange-polygon-p object)) (not (self-intersecting-p object)))) (defmethod object-ok-p ((object g-spline-polygon)) (and (not (strange-polygon-p object)) (not (self-intersecting-p object)))) (defmethod object-ok-p ((object pointlist-object)) (not (self-intersecting-p object))) (defmethod object-ok-p ((object linesegment)) (not (equal (startpoint object) (endpoint object)))) (defmethod object-ok-p ((object g-text)) (not (string= "" (text-string object)))) (defmethod object-ok-p ((object g-rectangle)) (not (or (zerop (xextend object)) (zerop (yextend object))))) (defmethod object-ok-p ((object g-circle)) (not (zerop (radius object)))) ;;; ;;; ;;; (defmethod pointlist-ok-p ((object pointlist-object)) t) (defun polygon-pointlist-ok-p (polygon) (>= (length (pointlist polygon)) 6)) ; mind. 3 Punkte! (defmethod pointlist-ok-p ((object g-polygon)) (polygon-pointlist-ok-p object)) (defmethod pointlist-ok-p ((object g-spline-polygon)) (polygon-pointlist-ok-p object)) ;;; ;;; ;;; (defmethod set-init-extend ((object t)) ()) (defmethod set-init-extend ((object scaleable-thing)) (let ((*global-scaling* 1)) (multiple-value-bind (xf yf xt yt) (get-bounding-rect object) (setf (init-x-extend object) (- xt xf) (init-y-extend object) (- yt yf))))) ;;; ;;; ;;; (defmethod init-object-properties ((object t)) ()) (defmethod init-object-properties ((object basic-thing)) (get-bounding-rect object) (make-poly-representation object) (call-next-method)) (defmethod init-object-properties ((object composite-thing)) (multiple-value-bind (x y) (get-bounding-rect-center object) (multiple-value-bind (x y) (scale-mouse-position x y :inverse t) (setf (xtrans object) x (ytrans object) y))) (call-next-method)) (defmethod init-object-properties ((object scaleable-thing)) (set-init-extend object) (call-next-method)) (defmethod init-object-properties ((object linesegment)) (make-object-handles object (list (startpoint object) (endpoint object))) (call-next-method)) (defmethod init-object-properties ((object pointlist-object)) (unless (handles object) (make-object-handles object (generate-brackets (pointlist object) ))) (call-next-method)) (defmethod init-object-properties ((object g-spline-chain)) (setf (spline-points object) (mapcan #'identity (filter-to-close-together-out (reverse (make-spline (make-spline-chain-list (generate-brackets (pointlist object) )) 4)) 3.0))) (call-next-method)) (defmethod init-object-properties ((object g-spline-polygon)) (setf (spline-points object) (mapcan #'identity (filter-to-close-together-out (reverse (make-spline (make-spline-polygon-list (generate-brackets (pointlist object))) 4 :polygon t)) 3.0))) (call-next-method)) ;;; ;;; ;;; (defmethod initialize-instance :after ((object thing) &key) (when (initialize object) (unless (parent-concepts object) (setf (parent-concepts object) (list (type-of object)))) (setf (id-number object) (get-id-number)))) (defmethod initialize-instance :after ((object object-with-head) &key) (when (initialize object) (with-application-frame (gened-frame) (with-slots (default-arrow-head) gened-frame (if default-arrow-head (setf (head object) t) (setf (head object) nil)))))) (defmethod initialize-instance :after ((object g-arrow) &key) (when (initialize object) (with-application-frame (gened-frame) (with-slots (default-arrow-head) gened-frame (setf (parent-concepts object) (if default-arrow-head '(g-arrow) '(g-line))))))) (defmethod initialize-instance :after ((object g-chain) &key) (when (initialize object) (setf (parent-concepts object) (if (head object) '(g-directed-chain) '(g-chain))))) (defmethod initialize-instance :after ((object g-spline-chain) &key) (when (initialize object) (setf (parent-concepts object) (if (head object) '(g-directed-spline-chain) '(g-spline-chain))))) ;;; ;;; ;;; (defmethod initialize-instance :after ((object ink-mixin) &key) (when (initialize object) (with-application-frame (gened-frame) (with-slots (default-ink) gened-frame (setf (ink object) default-ink))))) (defmethod initialize-instance :after ((object filled-mixin) &key) (when (initialize object) (with-application-frame (gened-frame) (with-slots (default-filled default-filled-ink) gened-frame (setf (filledp object) default-filled) (setf (filled-ink object) default-filled-ink))))) (defmethod initialize-instance :after ((object linestyle-mixin) &key) (when (initialize object) (with-application-frame (gened-frame) (with-slots (default-line-style) gened-frame (setf (linestyle object) (decode-line-style default-line-style)))))) (defmethod initialize-instance :after ((object linethickness-mixin) &key) (when (initialize object) (with-application-frame (gened-frame) (with-slots (default-line-thickness) gened-frame (setf (linethickness object) default-line-thickness))))) ;;; ;;; ;;; (defmethod initialize-instance :after ((object g-text) &key) (if (initialize object) (with-application-frame (gened-frame) (with-slots (default-text-family default-text-face default-text-size) gened-frame (setf (family object) default-text-family) (setf (face object) default-text-face) (setf (size object) default-text-size))))) (defmethod initialize-instance :after ((object linesegment) &key) (if (initialize-handles object) (make-object-handles object (list (startpoint object) (endpoint object))))) (defmethod initialize-instance :after ((object pointlist-object) &key) (if (initialize-handles object) (make-object-handles object (generate-brackets (pointlist object))))) ;;; ;;; ;;; (defmethod get-basic-concept ((object t)) (type-of object)) (defmethod get-basic-concept ((object g-arrow)) (if (head object) 'g-arrow 'g-line)) (defmethod get-basic-concept ((object g-chain)) (if (head object) 'g-directed-chain 'g-chain)) (defmethod get-basic-concept ((object g-spline-chain)) (if (head object) 'g-directed-spline-chain 'g-spline-chain))
16,636
Common Lisp
.lisp
462
31.688312
91
0.699491
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
66ee0777425fb0f33df2c267fc9494bf600f647c7464f491db2328605ce94bb3
11,156
[ -1 ]
11,157
polyrep.lisp
lambdamikel_GenEd/src/polyrep.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defun make-right-geom-polygon (object point-list &key (closed t)) (delete-polyrep-from-cache object) (make-geom-polygon (mapcar #'(lambda (point) (multiple-value-bind (x y) (let* ((xp (first point)) (yp (second point))) (transform-point-gs object xp yp)) (list x y))) point-list) :is-closed closed :tickval nil)) ;;; ;;; ;;; (defmethod transform-point-gs ((object basic-thing) x y &key (inverse nil)) (let* ((comptrans (get-transformation object)) (gstrans (make-scaling-transformation *global-scaling* *global-scaling*)) (trans (compose-transformations gstrans comptrans))) (multiple-value-bind (x y) (if inverse (untransform-position trans x y) (transform-position trans x y)) (values (round x) (round y))))) ;;; ;;; ;;; (defmethod make-poly-representation ((object g-polygon)) (with-slots (polygonized-representation pointlist) object (setf polygonized-representation (make-right-geom-polygon object (generate-brackets pointlist) :closed t)))) (defmethod make-poly-representation ((object g-chain)) (with-slots (polygonized-representation pointlist) object (setf polygonized-representation (make-right-geom-polygon object (generate-brackets pointlist) :closed nil))) (call-next-method)) (defmethod make-poly-representation ((object g-spline-polygon)) (with-slots (polygonized-representation pointlist) object (setf polygonized-representation (make-right-geom-polygon object (generate-brackets (spline-points object)) :closed t)))) (defmethod make-poly-representation ((object g-spline-chain)) (with-slots (polygonized-representation pointlist) object (setf polygonized-representation (make-right-geom-polygon object (generate-brackets (spline-points object)) :closed nil))) (call-next-method)) (defmethod make-poly-representation ((object g-rectangle)) (with-slots (xextend yextend polygonized-representation) object (setf polygonized-representation (make-right-geom-polygon object (list (list (- xextend) (- yextend)) (list xextend (- yextend)) (list xextend yextend) (list (- xextend) yextend)) :closed t)))) (defmethod make-poly-representation ((object g-text)) (with-slots (polygonized-representation) object (multiple-value-bind (xf yf xt yt) (get-bounding-rect object) (delete-polyrep-from-cache object) (setf polygonized-representation (make-geom-polygon (list (list xf yf) (list xt yf) (list xt yt) (list xf yt)) :is-closed t :tickval nil))))) (defmethod make-poly-representation ((object g-point)) (delete-polyrep-from-cache object) (setf (polygonized-representation object) (make-geom-point (xtrans object) (ytrans object) :tickval nil))) (defmethod make-poly-representation ((object info-point)) (delete-polyrep-from-cache object) (setf (polygonized-representation object) (make-geom-point (xtrans object) (ytrans object) :tickval nil))) (defmethod make-poly-representation ((object directed-info-element)) (with-slots (start-info-point end-info-point) object (let* ((startpoint (startpoint object)) (endpoint (endpoint object))) (multiple-value-bind (xs ys) (transform-point-gs object (first startpoint) (second startpoint)) (multiple-value-bind (xe ye) (transform-point-gs object (first endpoint) (second endpoint)) (let ((p1 (make-instance 'info-point :xtrans xs :ytrans ys :startpoint-of object :initialize t)) (p2 (make-instance 'info-point :xtrans xe :ytrans ye :endpoint-of object :initialize t))) (make-poly-representation p1) (make-poly-representation p2) (when start-info-point (setf (id-number p1) (id-number start-info-point)) (when (associated-classic-ind start-info-point) (setf (associated-classic-ind p1) (associated-classic-ind start-info-point)))) (when end-info-point (setf (id-number p2) (id-number end-info-point)) (when (associated-classic-ind end-info-point) (setf (associated-classic-ind p2) (associated-classic-ind end-info-point)))) (setf (start-info-point object) p1) (setf (end-info-point object) p2))))))) (defmethod make-poly-representation ((object linesegment)) (delete-polyrep-from-cache object) (with-slots (startpoint endpoint polygonized-representation) object (multiple-value-bind (xs ys) (transform-point-gs object (first startpoint) (second startpoint)) (multiple-value-bind (xe ye) (transform-point-gs object (first endpoint) (second endpoint)) (setf polygonized-representation (make-geom-line (make-geom-point xs ys) (make-geom-point xe ye) :tickval nil))))) (call-next-method)) (defmethod make-poly-representation ((object g-circle)) (with-slots (polygonized-representation radius) object (setf polygonized-representation (make-right-geom-polygon object (let ((fac (/ (* 2 pi) +circle-granularity+)) (collect nil)) (dotimes (i +circle-granularity+ collect) (let ((rad (* i fac))) (push (list (* radius (cos rad)) (* radius (sin rad))) collect)))) :closed t)))) (defmethod make-poly-representation ((object composite-thing)) (with-slots (liste) object (dolist (elem liste) (make-poly-representation elem)))) ;;; ;;; ;;; (defun get-poly-liste () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (atomize-all-clusters) (let* ((liste2 (install-points liste)) (poly-liste (mapcan #'(lambda (x) (when (typep x 'thing) (let ((poly-rep (when (slot-exists-p x 'polygonized-representation) (polygonized-representation x)))) (if poly-rep (list poly-rep))))) liste2))) (reinstall-all-clusters) poly-liste)))) (defmethod delete-polyrep-from-cache ((object basic-thing)) (let ((poly-liste (get-poly-liste)) (poly-elem (polygonized-representation object))) (call-next-method) (when poly-elem (delete-object-from-cache poly-elem poly-liste)))) (defmethod delete-polyrep-from-cache ((object t)) ()) (defmethod delete-polyrep-from-cache ((object directed-info-element)) (let ((start-info-point (start-info-point object)) (end-info-point (end-info-point object))) (when start-info-point (delete-polyrep-from-cache start-info-point)) (when end-info-point (delete-polyrep-from-cache end-info-point)))) (defmethod delete-polyrep-from-cache ((object info-point)) (let ((poly-liste (get-poly-liste)) (poly-elem (polygonized-representation object))) (when poly-elem (delete-object-from-cache poly-elem poly-liste)))) (defmethod delete-polyrep-from-cache ((object composite-thing)) (dolist (elem (liste object)) (delete-polyrep-from-cache elem)))
7,292
Common Lisp
.lisp
212
28.75
79
0.674532
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
91cc5e6a6d6f666abb0778a64fd9d942e001f05d6aa4ffe64a9f6362f89a0613
11,157
[ -1 ]
11,158
interface-to-classic2.lisp
lambdamikel_GenEd/src/interface-to-classic2.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; Error-Hook-Fn. ;;; (defun inconsistent-classic-object (code args path object) (if (and (cl-instance? object (cl-named-concept 'gened-thing)) (listp (cl-fillers object (cl-named-role 'belongs-to-clos-object)))) (let ((id (first (cl-fillers object (cl-named-role 'belongs-to-clos-object))))) (find-object id)))) ;;; ;;; (defmethod name-for ((object thing)) (concatenate 'string (generate-name (first (parent-concepts object))) "-" (write-to-string (id-number object)))) ;;; ;;; ;;; (defun add-information (object slot delta) (when delta (when *info* (format t "+ Information: Object ~A, Slot ~A~%" object slot)) (if (or (listp delta) (typep delta 'thing)) (if (listp delta) (insert-fillers-for-slotname object slot delta) (insert-fillers-for-slotname object slot (list delta))) (insert-filler-for-attribute object slot delta)))) (defun remove-information (object slot delta) (when delta (when *info* (format t "- Information: Object ~A, Slot ~A~%" object slot)) (if (or (listp delta) (typep delta 'thing)) (if (listp delta) (remove-fillers-for-slotname object slot delta) (remove-fillers-for-slotname object slot (list delta))) (remove-filler-for-attribute object slot delta)))) ;;; ;;; ;;; (defun create-classic-ind-for (object) (when (and *info* (not (associated-classic-ind object))) (terpri) (format t "Creating Classic Individual for Object ~A.~%" object)) (let* ((symbol (intern (name-for object))) (classic-ind (cl-create-ind symbol `(and ,@(parent-concepts object))))) (unless (eq classic-ind 'classic-error) (cl-ind-add (cl-named-ind symbol) `(fills belongs-to-clos-object ,(id-number object))) (setf (associated-classic-ind object) symbol)))) (defmethod create-classic-ind ((object thing)) (create-classic-ind-for object)) ;;; Nachdenken! Alle Relationen zwischen Part-Of-Objekten gehen verloren! (Black-Box!) (defmethod create-classic-ind ((object composite-thing)) (dolist (part (liste object)) (create-classic-ind part)) (create-classic-ind-for object)) ;;; ;;; ;;; (defun fill-all-roles-for-object (object) (dolist (slot (all-slots object)) (let ((cont (funcall slot object))) (add-information object slot cont)))) (defmethod fill-all-roles ((object thing)) (fill-all-roles-for-object object) (call-next-method)) (defmethod fill-all-roles ((object stored-relations)) (fill-all-roles-for-object object) (call-next-method)) (defmethod fill-all-roles ((object t)) ()) ;;; ;;; ;;; (defun remove-all-roles-for-object (object) (dolist (slot (all-slots object)) (let ((cont (funcall slot object))) (remove-information object slot cont)))) (defmethod remove-all-roles ((object thing)) (remove-all-roles-for-object object) (call-next-method)) (defmethod remove-all-roles ((object stored-relations)) (remove-all-roles-for-object object) (call-next-method)) (defmethod remove-all-roles ((object t)) ()) ;;; ;;; (defmethod delete-classic-ind ((object t)) (when *info* (terpri) (format t "Removing All Information for Object ~A.~%" object)) (remove-all-roles object)) (defmethod delete-classic-ind ((object composite-thing)) (when *info* (terpri) (format t "Removing All Information for Object ~A.~%" object)) (remove-all-roles object) (dolist (part (liste object)) (delete-classic-ind part))) ;;; ;;; ;;; (defun get-role-from-accessor (accessor-symbol) (case accessor-symbol (liste 'has-parts) (calc-linked-over-with 'linked-over-with) (calc-start-linked-over-with 'start-linked-over-with) (calc-end-linked-over-with 'end-linked-over-with) (calc-linker-objects 'linker-objects) (calc-start-linker-objects 'start-linker-objects) (calc-end-linker-objects 'end-linker-objects) (calc-startpoint-related-with 'startpoint-related-with) (calc-endpoint-related-with 'endpoint-related-with) (calc-points-related-with 'points-related-with) (part-of-cluster 'part-of) (calc-point-of 'point-part-of) (calc-startpoint-of 'startpoint-part-of-directed-element) (calc-endpoint-of 'endpoint-part-of-directed-element) (filledp 'filled-bool) (xtrans 'xtrans-integer) (ytrans 'ytrans-integer) (radius 'radius-real) (covered-by-objects 'covered-by-object) (otherwise accessor-symbol))) ;;; ;;; ;;; (defun update-classic-ind-concepts (object &key (remove nil) (clos-update t)) (with-application-frame (gened-frame) (with-slots (inc-mode) gened-frame (when inc-mode (let ((object-classic-ind (get-classic-ind object)) (parent-concepts (parent-concepts object)) (ancestor-concepts (ancestor-concepts object))) (when object-classic-ind (if remove (cl-ind-remove object-classic-ind `(and ,@parent-concepts ,@ancestor-concepts)) (cl-ind-add object-classic-ind `(and ,@parent-concepts ,@ancestor-concepts))) (if clos-update (update-parent-concepts)))))))) ;;; ;;; ;;; (defun create-classic-inds () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (elem liste) (create-classic-ind elem)) (dolist (elem liste) (fill-all-roles elem))))) ;;; ;;; ;;; (defmethod calc-points-related-with ((object directed-info-element)) (if (head object) nil (append (startpoint-related-with object) (endpoint-related-with object)))) (defmethod calc-startpoint-related-with ((object directed-info-element)) (if (head object) (startpoint-related-with object) nil)) (defmethod calc-endpoint-related-with ((object directed-info-element)) (if (head object) (endpoint-related-with object) nil)) ;;; (defmethod calc-linker-objects ((object 0d)) (remove-if #'head (append (start-linker-objects object) (end-linker-objects object)))) (defmethod calc-start-linker-objects ((object 0d)) (remove-if-not #'head (start-linker-objects object))) (defmethod calc-end-linker-objects ((object 0d)) (remove-if-not #'head (end-linker-objects object))) ;;; ;;; ;;; (defmethod calc-linked-over-with ((object 0d)) (mapcan #'(lambda (goal linker) (unless (head linker) (list goal))) (append (start-linked-over-with object) (end-linked-over-with object)) (append (start-linker-objects object) (end-linker-objects object)))) (defmethod calc-linked-over-with ((object s-0d)) (mapcan #'(lambda (goal linker) (let ((linker (get-stored-object linker))) (unless (head linker) (list goal)))) (append (start-linked-over-with object) (end-linked-over-with object)) (append (start-linker-objects object) (end-linker-objects object)))) (defmethod calc-start-linked-over-with ((object 0d)) (mapcan #'(lambda (goal linker) (if (head linker) (list goal))) (start-linked-over-with object) (end-linker-objects object))) (defmethod calc-start-linked-over-with ((object s-0d)) (mapcan #'(lambda (goal linker) (let ((linker (get-stored-object linker))) (if (head linker) (list goal)))) (start-linked-over-with object) (end-linker-objects object))) (defmethod calc-end-linked-over-with ((object 0d)) (mapcan #'(lambda (goal linker) (if (head linker) (list goal))) (end-linked-over-with object) (start-linker-objects object))) (defmethod calc-end-linked-over-with ((object s-0d)) (mapcan #'(lambda (goal linker) (let ((linker (get-stored-object linker))) (if (head linker) (list goal)))) (end-linked-over-with object) (start-linker-objects object))) ;;; ;;; ;;; (defmethod calc-point-of ((object info-point)) (let ((parent (or (startpoint-of object) (endpoint-of object)))) (if (head parent) nil (or (startpoint-of object) (endpoint-of object))))) (defmethod calc-point-of ((object s-info-point)) (if (parent-head object) nil (or (startpoint-of object) (endpoint-of object)))) (defmethod calc-startpoint-of ((object s-info-point)) (if (parent-head object) (startpoint-of object) nil)) (defmethod calc-startpoint-of ((object info-point)) (let ((parent (startpoint-of object))) (if parent (if (head parent) parent nil) nil))) (defmethod calc-endpoint-of ((object s-info-point)) (if (parent-head object) (endpoint-of object) nil)) (defmethod calc-endpoint-of ((object info-point)) (let ((parent (endpoint-of object))) (if parent (if (head parent) parent nil) nil))) ;;; ;;; ;;; (defun insert-filler-for-attribute (object attrib-name filler-to-add) (let ((object-classic-ind (get-classic-ind object)) (filler-to-add (if (numberp filler-to-add) (round filler-to-add) filler-to-add))) (when (and object-classic-ind filler-to-add) (let* ((role-symbol (get-role-from-accessor attrib-name)) (present-fillers (cl-fillers object-classic-ind (cl-named-role role-symbol)))) (unclose-all-roles-for-object-i.n. object) (if present-fillers (cl-ind-remove object-classic-ind `(fills ,role-symbol ,@present-fillers))) (cl-ind-add object-classic-ind `(fills ,role-symbol ,filler-to-add)))))) (defun insert-fillers-for-slotname (object slot-name fillers-to-add) (let ((object-classic-ind (get-classic-ind object))) (when object-classic-ind (let* ((role-symbol (get-role-from-accessor slot-name)) (present-fillers (cl-fillers object-classic-ind (cl-named-role role-symbol)))) (let ((filler-names (mapcar #'(lambda (object) (cl-name (get-classic-ind object))) fillers-to-add)) (present-filler-names (mapcar #'cl-ind-name present-fillers))) (unclose-all-roles-for-object-i.n. object) (dolist (filler-name filler-names) (let ((filler-ind (cl-named-ind filler-name))) (unclose-all-roles-for-classic-ind-i.n. filler-ind) (unless (member filler-name present-filler-names) (cl-ind-add object-classic-ind `(fills ,role-symbol ,filler-name)))))))))) ;;; ;;; ;;; (defun remove-all-fillers-for-slotname (object slot-name) (remove-fillers-for-slotname object slot-name (funcall slot-name object))) (defun remove-filler-for-attribute (object attrib-name filler-to-remove) (let* ((object-classic-ind (get-classic-ind object)) (role-symbol (get-role-from-accessor attrib-name)) (filler-to-remove (if (numberp filler-to-remove) (round filler-to-remove) filler-to-remove))) (when (and object-classic-ind filler-to-remove) (unclose-role-for-classic-ind-i.n. object-classic-ind role-symbol) (cl-ind-remove object-classic-ind `(fills ,role-symbol ,filler-to-remove))))) (defun remove-fillers-for-slotname (object slot-name fillers-to-remove) (let ((object-classic-ind (get-classic-ind object))) (when object-classic-ind (let* ( (role-symbol (get-role-from-accessor slot-name)) (role (cl-named-role role-symbol)) (inv-role (cl-role-inverse role)) (inv-role-symbol (cl-role-name inv-role)) (all-fillers (cl-fillers object-classic-ind role)) (all-filler-names (mapcar #'cl-name all-fillers)) (fillers-to-remove-names (mapcar #'(lambda (x) (cl-name (get-classic-ind x))) fillers-to-remove)) (told-fillers (cl-told-fillers (cl-told-ind object-classic-ind) role)) (told-filler-names (mapcar #'cl-told-ind-name told-fillers)) (derived-filler-names (set-difference all-filler-names told-filler-names)) (remove-told-filler-names (intersection fillers-to-remove-names told-filler-names)) (remove-derived-filler-names (intersection fillers-to-remove-names derived-filler-names))) (unclose-all-roles-for-classic-ind-i.n. object-classic-ind) (dolist (filler-name remove-told-filler-names) (unclose-all-roles-for-classic-ind-i.n. (cl-named-ind filler-name)) (cl-ind-remove object-classic-ind `(fills ,role-symbol ,filler-name))) (if (and inv-role-symbol remove-derived-filler-names) (let ((object-name (cl-name object-classic-ind))) (dolist (name remove-derived-filler-names) (let ((inverse-ind (cl-named-ind name))) (unclose-all-roles-for-classic-ind-i.n. inverse-ind) (cl-ind-remove inverse-ind `(fills ,inv-role-symbol ,object-name)))))))))) ;;; ;;; ;;; (defmethod get-classic-ind ((object thing)) (let ((classic-ind (cl-named-ind (associated-classic-ind object)))) (if classic-ind classic-ind (progn (format t "*** ERROR - NO CLASSIC-INDIVIDUAL~% FOR OBJECT ~A EXISTS! ***~%" object) nil)))) ;;; ;;; ;;; (define-gened-command (com-print-ind) ((object '(or thing object-handle) :gesture :classic-inspect)) (terpri) (terpri) (if (typep object 'thing) (cl-print-object (get-classic-ind object)) (if (and (or (typep object 'start-handle) (typep object 'end-handle)) (typep (parent-object object) 'directed-info-element)) (cl-print-object (get-classic-ind (if (typep object 'start-handle) (start-info-point (parent-object object)) (end-info-point (parent-object object)))))))) ;;; ;;; ;;; (defun close-role-for-object (object role-symbol) (let ((classic-ind (get-classic-ind object))) (when classic-ind (let* ( (cl-ind (if (cl-told-classic-ind? classic-ind) classic-ind (cl-told-ind classic-ind))) (role (cl-named-role role-symbol))) (unless (cl-told-ind-closed-role? cl-ind role) (cl-ind-close-role classic-ind role)))))) (defun close-roles-for-object (object role-set) (dolist (role-sym role-set) (close-role-for-object object role-sym))) (defun close-all-roles-for-object (object) (dolist (role-set +known-roles+) (close-roles-for-object object role-set))) (defun close-all-roles () (when *info* (terpri) (format t "Closing Roles for Objects...~%")) (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (role-set +known-roles+) (dolist (object liste) (close-roles-for-object object role-set))))) (update-parent-concepts)) (define-gened-command (com-gened-close-all-roles) () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (setf liste (install-points liste)) (close-all-roles) (setf liste (remove-points liste))))) ;;; ;;; ;;; (defun unclose-role-for-object-i.n. (object role-symbol) (let ((classic-ind (get-classic-ind object))) (when classic-ind (unclose-role-for-classic-ind-i.n. classic-ind role-symbol)))) (defun unclose-roles-for-object-i.n. (object role-set) (let ((classic-ind (get-classic-ind object))) (when classic-ind (dolist (role-symbol role-set) (unclose-role-for-classic-ind-i.n. classic-ind role-symbol))))) (defun unclose-role-for-classic-ind-i.n. (classic-ind role-symbol) (let* ((cl-ind (if (cl-told-classic-ind? classic-ind) classic-ind (cl-told-ind classic-ind))) (role (cl-named-role role-symbol))) (when (cl-told-ind-closed-role? cl-ind role) (cl-ind-unclose-role classic-ind role)))) (defun unclose-all-roles-for-object-i.n. (object) (mapc #'(lambda (role-set) (mapc #'(lambda (rol-sym) (unclose-role-for-object-i.n. object rol-sym)) (reverse role-set))) (reverse +known-roles+))) (defun unclose-all-roles-for-classic-ind-i.n. (classic-ind) (mapc #'(lambda (role-set) (mapc #'(lambda (rol-sym) (unclose-role-for-classic-ind-i.n. classic-ind rol-sym)) (reverse role-set))) (reverse +known-roles+))) (defun unclose-all-roles () (when *info* (terpri) (format t "Unclosing Roles for Objects...~%")) (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (role-set (reverse +known-roles+)) (dolist (object liste) (unclose-roles-for-object-i.n. object (reverse role-set))))))) (define-gened-command (com-gened-open-all-roles) () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (setf liste (install-points liste)) (unclose-all-roles) (setf liste (remove-points liste))))) ;;; ;;; ;;; (define-gened-command (com-gened-classify) () (with-application-frame (gened-frame) (with-slots (inc-mode liste) gened-frame (if inc-mode (progn (setf liste (install-points liste)) (close-all-roles) (setf liste (remove-points liste))) (progn (com-gened-clear-kb) (let ((*info* nil)) (calc-relations)) (setf liste (install-points liste)) (atomize-all-clusters) (create-classic-inds) (reinstall-all-clusters) (close-all-roles) (setf liste (remove-points liste)))) (update-parent-concepts) (redraw)))) ;;; ;;; ;;; (defun update-parent-concepts-for-object (object) (remove-all-concepts object :classic-ind-update nil) (let ((classic-ind (get-classic-ind object))) (when classic-ind (let* ((parents (mapcar #'cl-name (cl-ind-parents classic-ind))) (ancestors (mapcar #'cl-name (cl-ind-ancestors classic-ind))) (p-concepts (reverse (intersection +known-concepts+ parents))) (a-concepts (reverse (intersection +known-concepts+ ancestors)))) (mapc #'(lambda (parent ancestor) (push-concept object parent :classic-ind-update nil) (push-concept object ancestor :ancestor t :classic-ind-update nil)) p-concepts a-concepts))))) (defun update-parent-concepts () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (object liste) (update-parent-concepts-for-object object))))) ;;; ;;; ;;; (defmethod clear-classic-ind ((object basic-thing)) (setf (associated-classic-ind object) nil)) (defmethod clear-classic-ind ((object composite-thing)) (dolist (elem (liste object)) (clear-classic-ind elem)) (setf (associated-classic-ind object) nil)) (define-gened-command (com-gened-clear-kb) () (with-application-frame (gened-frame) (with-slots (liste stored-relations) gened-frame (cl-clear-kb) (setf liste (install-points liste)) (dolist (elem liste) (clear-classic-ind elem)) (setf liste (remove-points liste)) (setf stored-relations nil))))
18,992
Common Lisp
.lisp
602
26.622924
88
0.663191
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
c0b6029d2f7c77831a6982a1e5f4a2fb878c5e747ebc34e28a4bde71ef59653c
11,158
[ -1 ]
11,159
gened-sysdcl-fs.lisp
lambdamikel_GenEd/src/gened-sysdcl-fs.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: CL-User; Base: 10 -*- (cl:in-package cl-user) (define-system geometry (:default-pathname "gened:geometry;" :subsystem t) (:serial "newgeo13")) (define-system splines (:default-pathname "gened:splines;" :subsystem t) (:serial "spline3")) #| (load-system-definition 'classic-extensions) |# (define-system knowledge (:default-pathname "gened:knowledge;" :subsystem t) (:serial #| classic-extensions |# "knowledge8")) (define-system specific-commands (:default-pathname "gened:specific-commands;" :subsystem t) (:serial "speccom")) (define-system gened-fs (:default-pathname "gened:sources;") (:serial "gened-packages" "values" "classesxx" "comtable" "frame" (:parallel splines geometry) "helpaux" "polyrep" "transfor" "draw" "creator" "cluster" "handles" "inout" "copy" "spatial5" "inspect" "delete" "undo" "main" "rel-copy2" "interface-to-classic3" knowledge #| specific-commands |# "concepts" "delta2" "init2"))
1,163
Common Lisp
.lisp
48
19.125
76
0.639042
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
67cf428215139610d1e12c0e42ab2d7444c8697398dd378f750b01208a7a28e0
11,159
[ -1 ]
11,160
handles.lisp
lambdamikel_GenEd/src/handles.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defmethod move-object-handle ((object object-handle)) (make-undo-object (parent-object object) 'move-object-handle) (when *info* (format t "~%Press Left Mouse-Button To Release!~%")) (let ((*concept-labels* nil) (parent (parent-object object))) (loop (interactive-master-creator object #'(lambda (x y) (change-object-handle object x y)) :drawer-function #'(lambda (object stream) (draw parent stream :handle-handling-active t :handling-active t))) (if (object-ok-p parent) (progn (tick-object parent) (adjust-object-origin parent) (do-incremental-updates) (return)) (beep))))) (define-gened-command (com-move-object-handle) ((object 'object-handle :gesture :move)) (move-object-handle object)) (define-gened-command (com-gened-move-object-handle :name "Move Object-Handle") () (let ((source-object (accept-handle 'object-handle '(start end fixed unfixed normal)))) (move-object-handle source-object)) (only-tick-all-objects) (redraw)) ;;; ;;; ;;; (defun accept-handle (handle-type display-options) (let ((*handles-symbol-list* display-options)) (only-tick-all-objects) (redraw) (prog1 (accept handle-type) (terpri)))) (defmethod fix-handle ((object object-handle)) (let ((x (x object)) (y (y object)) (parent-object (parent-object object))) (multiple-value-bind (x y) (transform-point parent-object x y) (multiple-value-bind (x y) (scale-mouse-position x y) (with-application-frame (gened-frame) (with-slots (liste) gened-frame (or (some #'(lambda (elem) (unless (eq parent-object elem) (multiple-value-bind (xf yf xt yt) (get-bounding-rect elem) (let ((rect (make-rectangle* (- xf +br-fix-inc+) (- yf +br-fix-inc+) (+ xt +br-fix-inc+) (+ yt +br-fix-inc+)))) (when (region-contains-position-p rect x y) (change-class object (cond ((typep object 'start-handle) 'fixed-start-handle) ((typep object 'end-handle) 'fixed-end-handle) ((typep object 'object-handle) 'fixed-object-handle))) (only-tick-object parent-object) (setf (fixed-at-object object) elem) (push object (attached-handles elem))))))) liste) (notify-user gened-frame "Not in Any Bounding-Rectangle!")))))))) (define-gened-command (com-gened-fix-handle :name "Fix Object-Handle") () (if (any-unfixed-handles) (let* ((source-object (accept-handle 'unfixed-object-handle '(normal start end)))) (fix-handle source-object) (only-tick-all-objects) (redraw)))) (define-gened-command (com-fix-object-handle) ((object 'unfixed-object-handle :gesture :fix/free)) (fix-handle object)) ;;; ;;; ;;; (defmethod free-handle ((object fixed-object-handle)) (let* ((fixed-at-object (fixed-at-object object)) (attached-handles (attached-handles fixed-at-object))) (setf (attached-handles fixed-at-object) (delete object attached-handles)) (setf (fixed-at-object object) nil) (only-tick-object (parent-object object)) (change-class object (cond ((typep object 'fixed-start-handle) 'unfixed-start-handle) ((typep object 'fixed-end-handle) 'unfixed-end-handle) ((typep object 'fixed-object-handle) 'unfixed-object-handle))))) (defmethod free-all-handles ((object t)) ()) (defmethod free-all-handles ((object thing)) (dolist (handle (attached-handles object)) (free-handle handle))) (defmethod free-my-handles ((object t)) ()) (defmethod free-my-handles ((object object-with-handles)) (dolist (handle (handles object)) (if (and (typep handle 'fixed-object-handle) (fixed-at-object handle)) (free-handle handle)))) ;;; ;;; ;;; (define-gened-command (com-gened-free-handle :name "Free Object-Handle") () (if (any-fixed-handles) (let* ((source-object (accept-handle 'fixed-object-handle '(fixed)))) (free-handle source-object)))) (define-gened-command (com-free-object-handle) ((object 'fixed-object-handle :gesture :fix/free)) (free-handle object) (only-tick-all-objects) (redraw)) ;;; ;;; ;;; (defmethod translate-fixed-handles-relative ((object thing) deltax deltay) (when (attached-handles object) (let* ((handles (attached-handles object))) (dolist (elem handles) (change-object-handle-relative elem deltax deltay))))) (defmethod change-object-handle ((object object-handle) x y) ; x, y : screen-coordinates (multiple-value-bind (newx newy) (transform-point (parent-object object) x y :inverse t) (let ((oldx (x object)) (oldy (y object))) (setf (x object) newx) (setf (y object) newy) (search-and-change (parent-object object) newx newy oldx oldy)))) (defmethod change-object-handle-relative ((object object-handle) deltax deltay) (let ((oldx (x object)) (oldy (y object))) (incf (x object) deltax) (incf (y object) deltay) (search-and-change (parent-object object) (x object) (y object) oldx oldy))) ;;; ;;; ;;; (defmethod make-object-handles ((object t) pointlist) (declare (ignore pointlist)) ()) (defmethod make-object-handles ((object object-with-handles) pointlist) (setf (handles object) (loop for elem in pointlist collect (make-instance (cond ((equal elem (first pointlist)) 'unfixed-start-handle) ((equal elem (first (last pointlist))) 'unfixed-end-handle) (t 'unfixed-object-handle)) :x (first elem) :y (second elem) :parent-object object))))
5,786
Common Lisp
.lisp
171
28.836257
89
0.658624
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
b4283db6e4b024339d0200ab6dc1204626be5b2b57f9b304ed0a857e15bfbeab
11,160
[ -1 ]
11,161
spatial5.lisp
lambdamikel_GenEd/src/spatial5.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defparameter *accessor-table* (make-hash-table)) (defmacro define-relation-accessors (&rest names) `(progn (defparameter +relation-accessor-symbols+ ',names) (clrhash *accessor-table*) (dolist (name +relation-accessor-symbols+) (setf (gethash name *accessor-table*) (fdefinition `(setf ,name)))))) (defun find-accessor (name) (gethash name *accessor-table*)) ;;; ---------------------------------------------------------------------- (define-relation-accessors touching-objects intersects-objects intersects-0-objects intersects-1-objects intersects-2-objects contains-objects contained-in-objects directly-contains-objects directly-contained-by-object covers-objects covered-by-objects start-linked-over-with end-linked-over-with startpoint-related-with endpoint-related-with start-linker-objects end-linker-objects disjoint-with in-relation-with-objects) (defconstant +info-relation-accessor-symbols+ '( touching-objects intersects-objects intersects-0-objects intersects-1-objects intersects-2-objects contained-in-objects directly-contained-by-object covered-by-objects start-linked-over-with end-linked-over-with disjoint-with)) (defconstant +map-accessors-to-pretty-names+ '((touching-objects . (touches touches)) (intersects-objects . (intersects intersects)) (intersects-0-objects . (intersects>dim=0 intersects>dim=0)) (intersects-1-objects . (intersects>dim=1 intersects>dim=1)) (intersects-2-objects . (intersects>dim=2 intersects>dim=2)) (contained-in-objects . (is-inside contains)) (directly-contained-by-object . (directly-inside directly-contains)) (covered-by-objects . (covers is-covered-by)) (start-linked-over-with . (is-end-linked-over-with is-start-linked-over-with)) (end-linked-over-with . (is-start-linked-over-with is-end-linked-over-with)) (disjoint-with . (is-disjoint-with is-disjoint-with)))) (defconstant +map-relations-to-accessors+ '((touches . (touching-objects)) (intersects . (intersects-objects)) (intersects-0 . (intersects-0-objects intersects-objects)) (intersects-1 . (intersects-1-objects intersects-objects)) (intersects-2 . (intersects-2-objects intersects-objects)) (contains . (contained-in-objects)) (is-inside . (contains-objects)) (covers . (contained-in-objects covered-by-objects directly-contained-by-object)) (is-covered-by . (contains-objects covers-objects directly-contains-objects)) (is-disjoint-with . (disjoint-with)))) (defconstant +map-accessors-to-roles+ '((start-info-point . has-startpoint) (end-info-point . has-endpoint) (disjoint-with . disjoint-with) (start-linked-over-with . start-linked-over-with) (end-linked-over-with . end-linked-over-with) (in-relation-with-objects . in-relation-with-objects) (intersects-objects . intersects-objects) (intersects-0-objects . intersects-0-objects) (touching-objects . touching-objects) (contained-in-objects . contained-in-objects) (covered-by-objects . covered-by-object) ; richtig geschr.! (mal m. s, mal ohne!) (directly-contained-by-object . directly-contained-by-object) (intersects-1-objects . intersects-1-objects) (intersects-2-objects . intersects-2-objects) (contains-objects . contains) (directly-contains-objects . directly-contains-objects) (start-linker-objects . start-linker-objects) (end-linker-objects . end-linker-objects) (covers-objects . covers-objects))) ;;; ;;; ;;; (defun store-output-regions () (with-application-frame (gened-frame) (let ((stream (get-frame-pane gened-frame 'display)) (*bounding-boxes* t) (*handles-symbol-list* nil)) (with-slots (liste) gened-frame (dolist (object liste) (unless (typep object 'info-point) (let ((record (with-output-recording-options (stream :draw nil :record t) (with-output-to-output-record (stream) (draw object stream))))) (setf (output-record1 object) record)))))))) (defun get-accessor-function-from-name (symbol) (fdefinition `(setf ,symbol))) ;;; ;;; ;;; (defun clear-stored-relations (liste) (dolist (elem liste) (dolist (accessor +relation-accessor-symbols+) (when (slot-exists-p elem accessor) (funcall (find-accessor accessor) nil elem))))) (defun show-topo-info (elem1 elem2 relation) (multiple-value-bind (dist orient) (distance-and-orientation (xtrans elem1) (ytrans elem1) (xtrans elem2) (ytrans elem2)) (format t "~% Relation:~% ~A~% ~A~% ~A." elem1 relation elem2) (format t "~%Polar-Distance: (~D | ~D)~%" (round dist) (round (* 180 (/ orient pi)))))) (defun find-all-cluster-elements (cluster) (if (typep cluster 'composite-thing) (let ((liste (liste cluster))) (mapcan #'find-all-cluster-elements liste)) (list cluster))) (defun make-all-disjoint (liste) (dolist (elem1 liste) (dolist (elem2 liste) (unless (eq elem1 elem2) (pushnew elem1 (disjoint-with elem2)))))) (defun remove-wrong-disjoints (liste) (dolist (elem1 liste) (dolist (elem2 liste) (if (and (not (eq elem1 elem2)) (member elem1 (in-relation-with-objects elem2))) (setf (disjoint-with elem2) (delete elem1 (disjoint-with elem2))))))) (defun remove-not-in-list (liste) (dolist (elem liste) (dolist (slot +relation-accessor-symbols+) (when (slot-exists-p elem slot) (let ((content (funcall slot elem))) (dolist (rel-elem content) (unless (member rel-elem liste) (funcall (find-accessor slot) (delete rel-elem content) elem)))))))) (defun install-relations-for-clusters () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (cluster1 liste) (let ((elems-of-cluster1 (find-all-cluster-elements cluster1))) (dolist (cluster2 liste) (if (and (not (eq cluster1 cluster2)) (or (typep cluster1 'composite-thing) (typep cluster2 'composite-thing))) (let* ((elems-of-cluster2 (find-all-cluster-elements cluster2))) (cond ( (some #'(lambda (x) (some #'(lambda (y) (member y (intersects-objects x))) elems-of-cluster2)) elems-of-cluster1) (memoize-relation cluster1 cluster2 'intersects)) ( (and (some #'(lambda (x) (and (typep x '2d) (some #'(lambda (y) (member y (covers-objects x))) elems-of-cluster2))) elems-of-cluster1) (some #'(lambda (x) (and (typep x '2d) (every #'(lambda (y) (or (member y (contains-objects x)) (member y (covers-objects x)))) elems-of-cluster2))) elems-of-cluster1)) (memoize-relation cluster1 cluster2 'covers) (memoize-relation cluster2 cluster1 'is-covered-by)) ( (some #'(lambda (x) (and (typep x '2d) (every #'(lambda (y) (member y (contains-objects x))) elems-of-cluster2))) elems-of-cluster1) (memoize-relation cluster1 cluster2 'contains) (memoize-relation cluster2 cluster1 'is-inside)) ( (and (some #'(lambda (x) (some #'(lambda (y) (member y (touching-objects x))) elems-of-cluster2)) elems-of-cluster1) (not (some #'(lambda (x) (some #'(lambda (y) (and (member y (in-relation-with-objects x)) (not (member y (touching-objects x))) ; !!! nachdenken! )) elems-of-cluster2)) elems-of-cluster1))) (memoize-relation cluster1 cluster2 'touches))))))))))) (defun memoize-relation (elem1 elem2 relation) #| (multiple-value-bind (dist orient) (distance-and-orientation (xtrans elem1) (ytrans elem1) (xtrans elem2) (ytrans elem2)) |# (unless (eq relation 'is-disjoint-with) (push elem1 (in-relation-with-objects elem2))) (dolist (accessor (rest (assoc relation +map-relations-to-accessors+))) (when (slot-exists-p elem2 accessor) (funcall (find-accessor accessor) (cons elem1 (funcall accessor elem2)) elem2)))) ;;; ;;; ;;; (defun store-infos-for-arrows-and-so () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (elem liste) (when (and (typep elem 'directed-info-element) (> (length (in-relation-with-objects elem)) 1)) (let ((startpoint (start-info-point elem)) (endpoint (end-info-point elem)) (related-start-object) (related-end-object)) (dolist (inter-elem (intersects-objects elem)) (when (typep inter-elem 'basic-thing) (when (member inter-elem (contained-in-objects startpoint)) (setf related-start-object inter-elem)) (when (member inter-elem (contained-in-objects endpoint)) (setf related-end-object inter-elem)))) (dolist (touch-elem (touching-objects elem)) (when (typep touch-elem 'basic-thing) (when (member startpoint (touching-objects touch-elem)) (setf related-start-object touch-elem)) (when (member endpoint (touching-objects touch-elem)) (setf related-end-object touch-elem)))) (dolist (cov-elem (covered-by-objects elem)) (when (typep cov-elem 'basic-thing) (when (member cov-elem (covered-by-objects startpoint)) (setf related-start-object cov-elem)) (when (member cov-elem (covered-by-objects endpoint)) (setf related-end-object cov-elem)))) (when (and related-start-object related-end-object) (push related-start-object (startpoint-related-with elem)) (push related-start-object (in-relation-with-objects related-end-object)) (push related-end-object (end-linked-over-with related-start-object)) (push related-end-object (endpoint-related-with elem)) (push related-end-object (in-relation-with-objects related-start-object)) (push related-start-object (start-linked-over-with related-end-object)) (pushnew elem (start-linker-objects related-start-object)) (pushnew elem (end-linker-objects related-end-object))))))))) (defun find-topmost-cluster (elem) (let ((cluster elem)) (loop (if (null (part-of-cluster cluster)) (return cluster) (setf cluster (part-of-cluster cluster)))))) (defun propagate-for-arrows-and-so (liste) (dolist (elem liste) (when (and (typep elem 'directed-info-element) (startpoint-related-with elem) (endpoint-related-with elem)) (let ((srw (first (startpoint-related-with elem))) (erw (first (endpoint-related-with elem)))) (when (and srw erw) (let ((cluster1 (find-topmost-cluster srw)) (cluster2 (find-topmost-cluster erw))) (when (not (and (eq cluster1 srw) (eq cluster2 erw))) (push cluster1 (startpoint-related-with elem)) (push cluster2 (endpoint-related-with elem)) (push cluster1 (start-linked-over-with cluster2)) (push cluster1 (in-relation-with-objects cluster2)) (push cluster2 (end-linked-over-with cluster1)) (push cluster2 (in-relation-with-objects cluster1)) (pushnew elem (start-linker-objects cluster1)) (pushnew elem (end-linker-objects cluster2))))))))) (defun resolve-covering-conflicts (liste) (dolist (elem liste) (when (and (typep elem '2d)) (let ((cov-elems (covers-objects elem))) (when (> (length cov-elems) 1) (dolist (cov-elem cov-elems) (when (typep cov-elem '2d) (let* ((cov-cov-elems (covers-objects cov-elem)) (conflict-elem (find-if #'(lambda (X) (member x cov-elems)) cov-cov-elems))) (when conflict-elem (setf (covers-objects elem) (delete conflict-elem cov-elems)) (setf (covered-by-objects conflict-elem) (delete elem (covered-by-objects conflict-elem))) (setf (directly-contains-objects elem) (delete conflict-elem (directly-contains-objects elem))) (if (eq (first (directly-contained-by-object conflict-elem)) elem) (setf (directly-contained-by-object conflict-elem) nil)) (push conflict-elem (contains-objects elem)) (push elem (contained-in-objects conflict-elem))))))))))) (defun remove-cluster-parts (liste) (let ((liste2 liste)) (dolist (elem liste) (if (typep elem 'composite-thing) (setf liste2 (set-difference liste2 (liste elem))))) liste2)) (defun calculate-directly-containing (liste) (flet ((memoize (elem1 elem2) (pushnew elem2 (directly-contains-objects elem1)) (setf (directly-contained-by-object elem2) (list elem1)))) (dolist (elem liste) (let* ((contained-in-objects (remove-cluster-parts (remove-duplicates (contained-in-objects elem)))) (l (length contained-in-objects))) (dolist (elem2 contained-in-objects) (when (or (and (typep elem2 'thing) (= (length (remove-cluster-parts (remove-duplicates (contained-in-objects elem2)))) (1- l))) nil) (memoize elem2 elem))))))) (defun install-points (liste) (mapcan #'(lambda (elem) (if (typep elem 'directed-info-element) (list (start-info-point elem) (end-info-point elem) elem) (list elem))) liste)) (defun remove-points (liste) (remove-if #'(lambda (x) (typep x 'info-point)) liste)) (defun calc-relations () (with-application-frame (gened-frame) (with-slots (liste saved-liste calc-int-dim) gened-frame (clear-stored-relations liste) (setf liste (install-points liste)) (atomize-all-clusters) (store-output-regions) (clear-stored-relations liste) (dolist (elem1 liste) (dolist (elem2 liste) (unless (eq elem1 elem2) (if (or (typep elem1 'info-point) (typep elem2 'info-point) (not (eql +nowhere+ (region-intersection (output-record1 elem1) (output-record1 elem2))))) (let ((relation (relate-poly-to-poly-unary-tres (polygonized-representation elem1) (polygonized-representation elem2) (calc-right-tres) :dim calc-int-dim))) (memoize-relation elem1 elem2 relation)) (memoize-relation elem1 elem2 'is-disjoint-with))))) (resolve-covering-conflicts liste) (reinstall-all-clusters) (make-all-disjoint liste) (store-infos-for-arrows-and-so) (propagate-for-arrows-and-so liste) (calculate-directly-containing liste) (install-relations-for-clusters) (calculate-directly-containing liste) (remove-wrong-disjoints liste) (remove-not-in-list liste) (setf liste (remove-points liste)) (when *info* (show-infos))))) (define-gened-command (com-gened-show-relations :name "Show Topological Relations") () (let ((*info* t)) (calc-relations))) (define-gened-command (com-gened-calc-relations :name "Calculate Topological Relations") () (let ((*info* nil)) (calc-relations))) (defun show-infos () (with-application-frame (gened-frame) (let ((mem-list nil)) (format t "~%~%Hash-Table-Size: ~D~%" (hash-table-count geometry::*hash-table*)) (with-slots (liste) gened-frame (dolist (elem liste) (mapc #'(lambda (relation-accessor-symbol) (when (slot-exists-p elem relation-accessor-symbol) (let ((relation-symbols (rest (assoc relation-accessor-symbol +map-accessors-to-pretty-names+)))) (dolist (rel-elem (funcall (symbol-function relation-accessor-symbol) elem)) (when (and (not (member (list (first relation-symbols) elem rel-elem) mem-list :test #'equal)) (not (member (list (second relation-symbols) elem rel-elem) mem-list :test #'equal))) (push (list (first relation-symbols) elem rel-elem) mem-list) (push (list (second relation-symbols) rel-elem elem) mem-list) (show-topo-info elem rel-elem (first relation-symbols)) (show-topo-info rel-elem elem (second relation-symbols))))))) +info-relation-accessor-symbols+)))))) ;;; ;;; ;;; (defmethod show-map-over ((object thing) accessor) (with-application-frame (gened-frame) (with-slots (liste) gened-frame (unhighlight-all-objects) (dolist (elem (funcall accessor object)) (highlight-object elem))))) (define-gened-command (com-gened-show-touching :name "Show Touching Objects") () (if (any-visible-objects) (let ((object (accept 'at-least-0d-object))) (terpri) (show-map-over object #'touching-objects)))) (define-gened-command (com-show-touching-objects) ((object 'at-least-0d-object :gesture nil)) (show-map-over object #'touching-objects)) ;;; ;;; ;;; (define-gened-command (com-gened-show-intersecting :name "Show Intersecting Objects") () (if (any-visible-objects) (let ((object (accept 'at-least-0d-object))) (terpri) (show-map-over object #'intersects-objects)))) (define-gened-command (com-show-intersecting-objects) ((object 'at-least-0d-object :gesture nil)) (show-map-over object #'intersects-objects)) (define-gened-command (com-gened-show-intersecting-dim=0 :name "Show Intersecting Objects, DIM = 0") () (if (any-visible-objects) (let ((object (accept 'at-least-0d-object))) (terpri) (show-map-over object #'intersects-0-objects)))) (define-gened-command (com-gened-show-intersecting-dim=1 :name "Show Intersecting Objects, DIM = 1") () (if (any-visible-objects) (let ((object (accept 'at-least-1d-object))) (terpri) (show-map-over object #'intersects-1-objects)))) (define-gened-command (com-gened-show-intersecting-dim=2 :name "Show Intersecting Objects, DIM = 2") () (if (any-visible-objects) (let ((object (accept 'at-least-2d-object))) (terpri) (show-map-over object #'intersects-2-objects)))) ;;; ;;; ;;; (define-gened-command (com-gened-show-contained :name "Show Contained In Objects") () (if (any-visible-objects) (let ((object (accept 'at-least-0d-object))) (terpri) (show-map-over object #'contained-in-objects)))) (define-gened-command (com-show-contained-in-objects) ((object 'at-least-0d-object :gesture nil)) (show-map-over object #'contained-in-objects)) ;;; ;;; ;;; (define-gened-command (com-gened-show-containing :name "Show Containing Objects") () (if (any-visible-2d-objects) (let ((object (accept 'at-least-2d-object))) (terpri) (show-map-over object #'contains-objects)))) (define-gened-command (com-show-containing-objects) ((object 'at-least-2d-object :gesture nil)) (show-map-over object #'contains-objects)) ;;; ;;; ;;; (define-gened-command (com-gened-show-directly-contained :name "Show Directly Contained In Object") () (if (any-visible-objects) (let ((object (accept 'at-least-0d-object))) (terpri) (show-map-over object #'directly-contained-by-object)))) (define-gened-command (com-show-directly-contained-in-object) ((object 'at-least-0d-object :gesture nil)) (show-map-over object #'directly-contained-by-object)) ;;; ;;; ;;; (define-gened-command (com-gened-show-directly-containing :name "Show Directly Containing Objects") () (if (any-visible-2d-objects) (let ((object (accept 'at-least-2d-object))) (terpri) (show-map-over object #'directly-contains-objects)))) (define-gened-command (com-show-directly-containing-objects) ((object 'at-least-2d-object :gesture nil)) (show-map-over object #'directly-contains-objects)) ;;; ;;; ;;; (define-gened-command (com-gened-show-covered :name "Show Covered By Objects") () (if (any-visible-objects) (let ((object (accept 'at-least-0d-object))) (terpri) (show-map-over object #'covered-by-objects)))) (define-gened-command (com-show-covered-by-objects) ((object 'at-least-0d-object :gesture nil)) (show-map-over object #'covered-by-objects)) ;;; ;;; ;;; (define-gened-command (com-gened-show-covering :name "Show Covering Objects") () (if (any-visible-2d-objects) (let ((object (accept 'at-least-2d-object))) (terpri) (show-map-over object #'covers-objects)))) (define-gened-command (com-show-covering-objects) ((object 'at-least-2d-object :gesture nil)) (show-map-over object #'covers-objects)) ;;; ;;; ;;; (define-gened-command (com-gened-show-disjoint :name "Show Disjoint Objects") () (if (any-visible-objects) (let ((object (accept 'at-least-0d-object))) (terpri) (show-map-over object #'disjoint-with)))) (define-gened-command (com-show-disjoint-objects) ((object 'at-least-0d-object :gesture nil)) (show-map-over object #'disjoint-with)) ;;; ;;; ;;; (define-gened-command (com-gened-show-related :name "Show Related Objects") () (if (any-visible-objects) (let ((object (accept 'at-least-0d-object))) (terpri) (show-map-over object #'in-relation-with-objects)))) (define-gened-command (com-show-related-objects) ((object 'at-least-0d-object :gesture nil)) (show-map-over object #'in-relation-with-objects)) ;;; ;;; ;;; (defmethod points-related-with ((object directed-info-element)) (append (startpoint-related-with object) (endpoint-related-with object))) (defmethod linked-over-with ((object thing)) (append (start-linked-over-with object) (end-linked-over-with object))) (defmethod linker-objects ((object thing)) (append (start-linker-objects object) (end-linker-objects object))) ;;; ;;; ;;; (define-gened-command (com-gened-show-linked :name "Show Linked Objects") () (when (any-visible-objects) (let* ((object (accept '(or g-arrow g-spline-chain g-chain)))) (terpri) (show-map-over object #'points-related-with)))) (define-gened-command (com-gened-show-start-linked :name "Show Start-Linked Objects") () (when (any-visible-directed-objects) (let ((object (accept '(or g-arrow g-spline-chain g-chain)))) (terpri) (when (head object) (show-map-over object #'startpoint-related-with))))) (define-gened-command (com-gened-show-end-linked :name "Show End-Linked Objects") () (when (any-visible-directed-objects) (let ((object (accept '(or g-arrow g-spline-chain g-chain)))) (terpri) (when (head object) (show-map-over object #'endpoint-related-with))))) ;;; ;;; ;;; (define-gened-command (com-gened-show-opposite :name "Show Opposite Objects") () (when (any-visible-objects) (let ((object (accept 'at-least-0d-object))) (terpri) (show-map-over object #'linked-over-with)))) ;;; ;;; ;;; (define-gened-command (com-gened-show-linker :name "Show Linker Objects") () (when (any-visible-objects) (let ((object (accept 'at-least-0d-object))) (terpri) (show-map-over object #'linker-objects)))) (define-gened-command (com-gened-show-start-linker :name "Show Start-Linker Objects") () (when (any-visible-objects) (let ((object (accept 'at-least-0d-object))) (terpri) (show-map-over object #'start-linker-objects)))) (define-gened-command (com-gened-show-end-linker :name "Show End-Linker Objects") () (when (any-visible-objects) (let ((object (accept 'at-least-0d-object))) (terpri) (show-map-over object #'end-linker-objects))))
24,257
Common Lisp
.lisp
649
31.137134
100
0.662826
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
027aac86847ec10bc7c07de1d59d704d30cffdbb37992fbb4be3a0ca5740a8fe
11,161
[ -1 ]
11,162
mac-init.lisp
lambdamikel_GenEd/src/mac-init.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defparameter *spline-chain* (make-instance 'g-spline-chain :pointlist '(-23 -13 -12 6 -8 -10 0 0 8 -4 16 14) :initialize-handles t :head t :parent-concepts '("directed-spline-chain"))) (defparameter *spline-polygon* (make-instance 'g-spline-polygon :pointlist '(8 16 10 12 16 16 22 18 24 12 22 8 16 0 8 -8 4 -16 0 -20 -8 -16 -10 -8 -12 0 -16 4 -12 12 -4 16) :initialize-handles t :parent-concepts '("spline-polygon"))) (defparameter *label-object* nil) ; wird spaeter gebunden, Frame muss erst existieren! (defparameter *label-shadow-object* nil) (defun load-label-object () (setf *label-object* (load-object (concatenate 'string +objects-dir+ "label-object"))) (setf *label-shadow-object* (load-object (concatenate 'string +objects-dir+ "label-shadow-object"))) (translate-object *label-object* 0 0) (translate-object *label-shadow-object* 3 3)) (let ((liste (make-spline (make-spline-chain-list (generate-brackets (pointlist *spline-chain*))) 3))) (setf (spline-points *spline-chain*) (append (mapcan #'identity liste) '(-28 -20)))) (let ((liste (make-spline (make-spline-polygon-list (generate-brackets (pointlist *spline-polygon*))) 6))) (setf (spline-points *spline-polygon*) (mapcan #'identity liste))) (defparameter *sample-graphic-objects* (list (list 'g-circle (make-instance 'g-circle :radius 20)) (list 'g-rectangle (make-instance 'g-rectangle :xextend 20 :yextend 16)) (list 'g-arrow (make-instance 'g-arrow :startpoint '(-20 20) :endpoint '(20 -20) :initialize-handles t :head t)) (list 'g-chain (make-instance 'g-chain :pointlist '(-20 -10 -12 6 -8 -10 0 0 4 -4 12 8 20 20) :initialize-handles t :head t)) (list 'g-spline-chain *spline-chain*) (list 'g-spline-polygon *spline-polygon*) (list 'g-polygon (make-instance 'g-polygon :pointlist '(-16 12 16 20 12 8 16 -12 8 -20 -20 -12 -16 -8) :initialize-handles t)) (list 'g-text (make-instance 'g-text :text-string "ABC" :size :normal :face :italic :family :sans-serif)) (list 'g-point (make-instance 'g-point :linethickness 3)) (list 'g-concept (make-instance 'g-text :text-string "*!@?" :size :normal)))) ;;; ;;; ;;; (defun load-concepts () (mapc #'(lambda (x) (init-object-properties (second x))) *library*)) (defparameter *library* nil) (defun get-visualisations-of-concept (item) (find-it *library* #'(lambda (x) (eql (first x) item)))) (defun get-graphic-object (item) (second item)) (defun get-nth-visualisation-of-concept (item nth) (get-graphic-object (nth nth (get-visualisations-of-concept item)))) ;;; ;;; ;;; #| (cl-add-error-hook #'inconsistent-classic-object) |#
3,066
Common Lisp
.lisp
102
24.95098
104
0.63176
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
5fee3e306bd8cd1b9538c850c925376c112b1184b49118f7339c816ba29ee691
11,162
[ -1 ]
11,163
mac-frame2.lisp
lambdamikel_GenEd/src/mac-frame2.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (define-application-frame gened () ( (liste :initform nil) (stored-relations :initform nil) (saved-liste :initform nil) (prev-op-liste :initform nil) (mode :initform 'g-circle) (concept-type :initform nil) (calc-int-dim :initform nil) (inc-mode :initform nil) (default-arrow-head :initform t) (default-line-thickness :initform 2) (default-line-style :initform :solid) (default-ink :initform 0.4) (default-text-family :initform :sans-serif) (default-text-face :initform :bold) (default-text-size :initform :normal) (default-filled-ink :initform 0.8) (default-filled :initform nil) (buffer-counter :initform 0) (object-copy-buffer :initform (make-array +buffer-size+))) (:command-table (gened :inherit-from (concept-table file-table tool-table manipulate-table reasoning-table spatial-table) :menu (("File" :menu file-table) ("Tools" :menu tool-table) ("Manipulate" :menu manipulate-table) ("Reasoning" :menu reasoning-table) ("Concepts" :menu concept-table) ("Spatial" :menu spatial-table)))) (:panes (pointer-documentation-pane (make-clim-stream-pane :type 'pointer-documentation-pane :foreground +white+ :background +black+ :text-style (make-text-style :sans-serif :bold :small) :scroll-bars nil :min-height '(1 :line) :max-height '(1 :line) :height '(1 :line))) (display :application :display-function 'draw-gened :textcursor nil :scroll-bars :both :redisplay-after-commands nil :incremental-redisplay t) (label :application :scroll-bars nil :redisplay-after-commands nil :incremental-redisplay t :display-function 'draw-label :foreground +white+ :background +black+) (infos :application :textcursor nil :text-style (parse-text-style '(:sans-serif :roman :very-small)) :end-of-line-action :allow :scroll-bars :both :incremental-redisplay nil) #| (command :interactor :Height '(3 :line)) |# (options1 :accept-values :scroll-bars nil :width :compute :height :compute :display-function `(accept-values-pane-displayer :displayer ,#'(lambda (frame stream) (accept-options1 frame stream)))) (options2 :accept-values :scroll-bars nil :width :compute :height :compute :display-function `(accept-values-pane-displayer :displayer ,#'(lambda (frame stream) (accept-options2 frame stream)))) (elements :accept-values :scroll-bars nil :width :compute :height :compute :display-function `(accept-values-pane-displayer :displayer ,#'(lambda (frame stream) (accept-elements frame stream)))) (buttons :accept-values :scroll-bars nil :width 160 :max-width 160 :display-function `(accept-values-pane-displayer :displayer ,#'(lambda (frame stream) (accept-buttons frame stream))))) (:layouts (:default (vertically () (horizontally () (vertically () elements options1 options2) (outlining (:thichness 2) label)) (horizontally () (scrolling () buttons) (horizontally () (2/3 display) (1/3 infos))) #| command |# pointer-documentation-pane)))) #| (defmethod read-frame-command ((frame gened) &key (stream *standard-input*)) (read-command (frame-command-table frame) :use-keystrokes t :stream stream)) |# (defun accept-it (stream type default prompt query-id &key (view 'gadget-dialog-view) (min-width 0) (min-height 0) orientation) (let (object ptype changed) (formatting-cell (stream :align-x (ecase orientation (:horizontal :left) (:vertical :center)) :align-y :center :min-width min-width :min-height min-height) (multiple-value-setq (object ptype changed) (accept type :stream stream :default default :query-identifier query-id :prompt prompt :view view))) (values object changed))) (defmethod accept-options1 ((frame gened) stream &key (orientation :horizontal)) (with-slots (default-line-style default-line-thickness default-ink default-arrow-head) frame (formatting-table (stream) (flet ((do-body (stream) (multiple-value-bind (real) (accept-it stream 'ink default-ink "Ink" 'ink :orientation orientation) (setf default-ink real) (multiple-value-bind (thickness) (accept-it stream 'line-thickness default-line-thickness "Thickness" 'thickness :orientation orientation) (setf default-line-thickness thickness) (multiple-value-bind (line-style) (accept-it stream 'line-style-type default-line-style "Style" 'style :orientation orientation) (setf default-line-style line-style)) (multiple-value-bind (bool) (accept-it stream 'boolean default-arrow-head "Head " 'head :orientation orientation) (setf default-arrow-head bool)))))) (ecase orientation (:horizontal (formatting-row (stream) (do-body stream))) (:vertical (formatting-column (stream) (do-body stream)))))))) (defmethod accept-options2 ((frame gened) stream &key (orientation :horizontal)) (with-slots (default-filled default-filled-ink default-text-family default-text-face default-text-size ) frame (formatting-table (stream) (flet ((do-body (stream) (multiple-value-bind (real) (accept-it stream 'ink default-filled-ink "Ink" 'ink :orientation orientation) (setf default-filled-ink real) (multiple-value-bind (text-style) (accept-it stream 'p-text-style (list default-text-family default-text-face) "Style" 'text-style :orientation orientation) (setf default-text-family (first text-style)) (setf default-text-face (second text-style)) (multiple-value-bind (text-size) (accept-it stream 'p-text-size default-text-size "Size" 'text-size :orientation orientation) (setf default-text-size text-size) (multiple-value-bind (bool) (accept-it stream 'boolean default-filled "Filled" 'filled :orientation orientation) (setf default-filled bool))))))) (ecase orientation (:horizontal (formatting-row (stream) (do-body stream))) (:vertical (formatting-column (stream) (do-body stream)))))))) ;;; ;;; ;;; (defun get-symbol-list () (with-application-frame (gened-frame) (with-slots (calc-int-dim inc-mode) gened-frame (append (when *bounding-boxes* (list 'boxes)) (when *origins* (list 'origins)) (when *info* (list 'infos)) (when *pretty-hl* (list 'pretty)) (when calc-int-dim (list 'dimensions)) (when inc-mode (list 'incremental)) (when *classic-warnings* (list 'warnings)))))) (defun text-cell (stream format-string &key (orientation :center)) (formatting-cell (stream :align-x orientation) (write-string format-string stream) (write-string " " stream))) (defmethod accept-buttons ((frame gened) stream &key (orientation :vertical)) (with-slots (calc-int-dim inc-mode) frame (let ((last-symbol-list (get-symbol-list))) (formatting-table (stream :y-spacing '(1 :character)) (flet ((do-body (stream) (text-cell stream "Global Display Options:") (multiple-value-bind (symbol-list changed0p) (accept-it stream '(subset-completion (VISIBLE HIDDEN PRIMITIVE COMPOSITE)) *global-display-options* nil 'global-display-options :orientation orientation :view 'list-pane-view) (setf *global-display-options* symbol-list) (text-cell stream "Object Display Options:") (multiple-value-bind (symbol-list changed1p) (accept-it stream '(subset-completion (INTERIOR BORDER)) (list (if *global-border* 'BORDER) (if *global-filled* 'INTERIOR)) nil 'object-display-options :orientation orientation :view 'list-pane-view) (setf *global-filled* (and (member 'INTERIOR symbol-list) t) *global-border* (and (member 'BORDER symbol-list) t)) (text-cell stream "Object Handle Options:") (multiple-value-bind (symbol-list changed2p) (accept-it stream `(subset-completion (NORMAL FIXED UNFIXED START END)) *handles-symbol-list* nil 'handles :orientation orientation :view 'list-pane-view) (setf *handles-symbol-list* symbol-list) (text-cell stream "Global Display Scaling:") (multiple-value-bind (number changed3p) (accept-it stream `(completion (1/2 1 2)) *global-scaling* nil 'gs :view 'list-pane-view :orientation orientation) (setf *global-scaling* number) (text-cell stream "Concept Label Options:") (multiple-value-bind (symbol-list changed4p) (accept-it stream '(subset-completion (IDs PARENTS ANCESTORS)) *concept-labels* nil 'labels :view 'list-pane-view :orientation orientation) (setf *concept-labels* symbol-list) (text-cell stream "Others:") (multiple-value-bind (symbol-list changed5p) (accept-it stream '(subset-completion (Boxes Origins Pretty Infos Warnings Dimensions Incremental)) (get-symbol-list) nil 'others :orientation orientation :view 'list-pane-view) (setf *pretty-hl* (member 'pretty symbol-list)) (setf *bounding-boxes* (member 'boxes symbol-list)) (setf *origins* (member 'origins symbol-list)) (setf *info* (member 'infos symbol-list)) (setf *classic-warnings* (member 'warnings symbol-list)) (set-classic-infos *classic-warnings*) (setf calc-int-dim (member 'dimensions symbol-list)) (setf inc-mode (member 'incremental symbol-list)) (when (or changed0p changed1p changed2p changed3p changed4p changed5p) (when changed5p (when (or (and (member 'dimensions symbol-list) (not (member 'dimensions last-symbol-list))) (and (not (member 'dimensions symbol-list)) (member 'dimensions last-symbol-list))) (clear-hashtable) (do-incremental-updates)) (when (or (and (member 'incremental symbol-list) (not (member 'incremental last-symbol-list))) (and (not (member 'incremental symbol-list)) (member 'incremental last-symbol-list))) (when inc-mode (clear-knowledge-base) (do-incremental-updates)))) (if changed3p (progn (tick-all-objects) (do-incremental-updates)) (only-tick-all-objects))))))))))) (ecase orientation (:horizontal (formatting-row (stream) (do-body stream))) (:vertical (formatting-column (stream) (do-body stream))))))))) (defmethod accept-elements ((frame gened) stream &key &allow-other-keys) (with-slots (mode) frame (formatting-table (stream) (formatting-column (stream) (formatting-cell (stream :align-x :center) (let ((element (accept 'elements :stream stream :default mode #| :prompt "Element" |#))) (setf mode element))))))) ;;; ;;; ;;; (define-presentation-type line-thickness () :inherit-from `((completion (1 2 3 4)) :name-key identity :printer present-line-thickness :highlighter highlight-line-thickness)) (defun present-line-thickness (object stream &key acceptably) (declare (ignore acceptably)) (let ((y (stream-line-height stream))) (with-room-for-graphics (stream) (draw-rectangle* stream 0 2 13 (- y 2) :filled nil :ink +background-ink+) (draw-line* stream 0 (floor y 2) 13 (floor y 2) :line-thickness object)))) (defun highlight-line-thickness (continuation object stream) (surrounding-output-with-border (stream) (funcall continuation object stream))) ;;; ;;; ;;; (define-presentation-type line-style-type () :inherit-from `((completion (:solid :pattern1 :pattern2 :pattern3)) :name-key identity :printer present-line-style :highlighter highlight-line-style)) (defun decode-line-style (object) (second (assoc object +line-pattern-list+))) (defun encode-line-style (object) (first (rassoc (list object) +line-pattern-list+ :test #'equal))) (defun present-line-style (object stream &key acceptably) (declare (ignore acceptably)) (let ((y (stream-line-height stream))) (with-room-for-graphics (stream) (draw-rectangle* stream 0 2 11 (- y 2) :filled nil :ink +background-ink+) (draw-line* stream 0 (floor y 2) 11 (floor y 2) :line-dashes (decode-line-style object))))) (defun highlight-line-style (continuation object stream) (surrounding-output-with-border (stream) (funcall continuation object stream))) ;;; ;;; ;;; (define-presentation-type ink () :inherit-from '((completion (0.4 0.6 0.8 0.9)) :name-key identity :printer present-ink)) (defun present-ink (object stream &key acceptably) (declare (ignore acceptably)) (let ((y (stream-line-height stream))) (with-room-for-graphics (stream) (draw-rectangle* stream 0 2 8 (- y 2) :filled t :ink (make-gray-color object))))) ;;; ;;; ;;; (define-presentation-type p-text-style () :inherit-from `((completion ((:sans-serif :bold) (:serif :italic) (:sans-serif nil) (:fix :bold)) :test equalp) :name-key identity :printer present-text-style)) (defun present-text-style (object stream &key) (let ((text-style (parse-text-style (append object '(:very-small))))) (with-text-style (stream text-style) (draw-text* stream "A" 0 0 :ink +black+)))) (define-presentation-type p-text-size () :inherit-from '((completion (:tiny :very-small :normal :very-large :huge)) :name-key identity :printer present-text-size)) (defun present-text-size (object stream &key) (case object (:tiny (write-string "T" stream)) (:very-small (write-string "S" stream)) (:normal (write-string "N" stream)) (:very-large (write-string "L" stream)) (:huge (write-string "H" stream)))) ;;; ;;; ;;; (define-presentation-type elements () :inherit-from `((completion (g-concept g-circle g-rectangle g-arrow g-chain g-spline-chain g-polygon g-spline-polygon g-text g-point)) :name-key identity :printer present-elements :highlighter highlight-element)) (defun present-elements (object stream &key) (let ((*concept-labels* nil) (*handles-symbol-list* nil) (*bounding-boxes* nil) (*origins* nil) (*global-scaling* 0.7)) (draw (second (assoc object *sample-graphic-objects*)) stream))) (defun highlight-element (continuation object stream) (surrounding-output-with-border (stream) (funcall continuation object stream))) ;;; ;;; ;;; (defmethod run-frame-top-level :before ((frame gened) &key) (initialize-gened frame)) #| (defmethod frame-standard-input ((frame gened)) (get-frame-pane frame 'command)) |# (defmethod frame-standard-output ((frame gened)) (get-frame-pane frame 'infos)) (defmethod initialize-gened ((frame gened)) (load-concepts) (load-label-object) (setf *current-file* "NONAME") (setf *global-scaling* 1) (setf *cl-error-msg-stream* (get-frame-pane frame 'infos)) (setf *cl-warn-msg-stream* (get-frame-pane frame 'infos)) (cl-set-classic-error-mode nil) (setf *classic-print-right-margin* 40)) (defun set-classic-infos (bool) (cl-set-classic-warn-mode bool)) (defmethod frame-error-output ((frame gened)) (get-frame-pane frame 'infos)) (defun clear-info-pane () (with-application-frame (gened-frame) (let ((stream (get-frame-pane gened-frame 'infos))) (window-clear stream)))) ;;; ;;; ;;; (defmethod draw-label ((frame gened) stream &key max-width max-height) (declare (ignore max-width max-height)) (updating-output (stream :unique-id *current-file* :cache-value *current-file*) (multiple-value-bind (x y) (window-inside-size stream) (with-translation (stream (+ 4 (/ x 2)) (+ 12 (/ y 2))) (let ((*origins* nil) (*concept-labels* nil) (*bounding-boxes* nil) (*pretty-hl* nil) (*global-border* t) (*global-filled* t) (*global-scaling* 1.0) (name (let ((num (position #\/ *current-file* :from-end t))) (subseq *current-file* (if num (1+ num) 0) (length *current-file*))))) (draw *label-shadow-object* stream) (draw *label-object* stream) (format stream "File: ~A" name)))))) ;;; ;;; ;;; (define-gesture-name :move :pointer-button (:left)) (define-gesture-name :create :pointer-button (:left :shift)) (define-gesture-name :delete :pointer-button (:middle :shift)) (define-gesture-name :inspect :pointer-button (:left :meta)) (define-gesture-name :classic-inspect :pointer-button (:right :meta)) (define-gesture-name :copy :pointer-button (:middle :control)) (define-gesture-name :scale :pointer-button (:right :shift)) (define-gesture-name :rotate :pointer-button (:left :control)) (define-gesture-name :atomize :pointer-button (:left :control)) (define-gesture-name :fix/free :pointer-button (:middle)) ;;; ----------------------------- (defparameter *gened-text-style* (make-text-style :sans-serif :roman :normal )) (defvar *gened-frame*) (defun gened (&key (force t) (process t)) (let ((port (find-port))) (setf (clim:text-style-mapping port *gened-text-style*) "-*-lucida-medium-r-normal-*-12-*-*-*-*-*-*-*") (when (or force (null *gened-frame*)) (setf *gened-frame* (make-application-frame 'gened :left 10 :top 10 :width 900 :height 600 )) #+:Allegro (if process (mp:process-run-function "Model Browser" #'(lambda () (run-frame-top-level *gened-frame*))) (run-frame-top-level *gened-frame*)) #-:Allegro (run-frame-top-level *gened-frame*) *gened-frame*)))
18,986
Common Lisp
.lisp
548
27.974453
88
0.648348
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
b5b8f06743fba72acb553372f62e2a54dcbf997944103b8340bf84ba12538796
11,163
[ -1 ]
11,164
values.lisp
lambdamikel_GenEd/src/values.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defconstant +objects-dir+ "gened:objects;") (defconstant +scenes-dir+ "gened:scenes;") (defconstant +libraries-dir+ "gened:libraries;") (defconstant +prints-dir+ "gened:prints;") ;;; ;;; ;;; (defconstant +labels-text-style+ (parse-text-style '(:sans-serif nil :tiny))) (defconstant +labels-text-style2+ (parse-text-style '(:sans-serif :italic :tiny))) (defconstant +labels-text-height+ 10) ;;; ;;; ;;; (defparameter *handles-symbol-list* '(normal start end)) (defparameter *bounding-boxes* t) (defparameter *origins* t) (defparameter *concept-labels* '(ids)) (defparameter *info* t) (defparameter *global-scaling* 1) (defparameter *classic-warnings* t) (defparameter *pretty-hl* t) (defparameter *global-display-options* '(visible primitive composite)) (defparameter *global-filled* t) (defparameter *global-border* t) (defparameter *current-file* "NONAME") ;;; ;;; ;;; (defparameter *handle-space* 3) (defparameter *org-space* 2) (defparameter *id-number* 1) ;;; Undo-Buffer (defconstant +buffer-size+ 10) ;;; Touching-Treshold und Granularitaet der Circle-Poly.Repr. (defconstant +tres-touch+ 4.0) (defconstant +circle-granularity+ 20) ;;; best. Strich-Muster (defconstant +line-pattern-list+ `((:solid nil) (:pattern1 (1 1)) (:pattern2 (2 2)) (:pattern3 (4 1)))) ;;; Bounding-Rectangle-Constants (defconstant +br-space+ 2) (defconstant +br-fix-inc+ 5) (defconstant +br-ink+ +black+) (defconstant +br-line-thickness+ 1) (defconstant +br-line-dashes+ '(1 3)) (defconstant +br-line-dashes2+ '(1 6)) (defconstant +br-highlight-thickness+ 2) (defconstant +printing-inc+ 0.3) ;;; Origin-Muster (defconstant +origin-dashes+ '(1 1)) ;;; (defconstant +mr-line-thickness+ 1) ;;; (defconstant +dash-pattern+ '(1 1))
1,886
Common Lisp
.lisp
64
27.359375
74
0.711086
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
a0e04250f7767e83ccba52886241c6fcf90b625a6b3e6faf6033222396f41311
11,164
[ -1 ]
11,165
mac-frame.lisp
lambdamikel_GenEd/src/mac-frame.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (define-application-frame gened () ( (liste :initform nil) (stored-relations :initform nil) (saved-liste :initform nil) (prev-op-liste :initform nil) (mode :initform 'g-circle) (concept-type :initform nil) (calc-int-dim :initform nil) (inc-mode :initform nil) (default-arrow-head :initform t) (default-line-thickness :initform 2) (default-line-style :initform :solid) (default-ink :initform 0.4) (default-text-family :initform :sans-serif) (default-text-face :initform :bold) (default-text-size :initform :normal) (default-filled-ink :initform 0.8) (default-filled :initform nil) (buffer-counter :initform 0) (object-copy-buffer :initform (make-array +buffer-size+))) (:command-table (gened :inherit-from (concept-table file-table tool-table manipulate-table reasoning-table spatial-table) :menu (("File" :menu file-table) ("Tools" :menu tool-table) ("Manipulate" :menu manipulate-table) ("Reasoning" :menu reasoning-table) ("Concepts" :menu concept-table) ("Spatial" :menu spatial-table)))) (:panes (pointer-documentation-pane (make-clim-stream-pane :type 'pointer-documentation-pane :foreground +white+ :background +black+ :text-style (make-text-style :sans-serif :bold :small) :scroll-bars nil :min-height '(1 :line) :max-height '(1 :line) :height '(1 :line))) (display :application :display-function 'draw-gened :textcursor nil :scroll-bars :both :redisplay-after-commands nil :incremental-redisplay t) (label :application :scroll-bars nil :redisplay-after-commands nil :incremental-redisplay t :display-function 'draw-label :foreground +white+ :background +black+) (infos :application :textcursor nil :text-style (parse-text-style '(:sans-serif :roman :very-small)) :end-of-line-action :allow :scroll-bars :both :incremental-redisplay nil) #| (command :interactor :Height '(3 :line)) |# (options1 :accept-values :borders t :scroll-bars nil :min-width :compute :width :compute :max-width :compute :min-height :compute :display-function `(accept-values-pane-displayer :displayer ,#'(lambda (frame stream) (accept-options1 frame stream)))) (elements :accept-values :borders t :scroll-bars nil :min-height :compute :height :compute :max-height :compute :display-function `(accept-values-pane-displayer :displayer ,#'(lambda (frame stream) (accept-elements frame stream)))) (buttons :accept-values :borders nil :scroll-bars nil :width 160 :max-width 160 :display-function `(accept-values-pane-displayer :displayer ,#'(lambda (frame stream) (accept-buttons frame stream))))) (:layouts (:default (vertically () (horizontally () (vertically () elements options1) (outlining (:thichness 2) label)) (horizontally () (scrolling () buttons) (horizontally () (2/3 display) (1/3 infos))) #| command |# pointer-documentation-pane)))) (defun accept-it (stream type default prompt query-id &key (view 'gadget-dialog-view) (min-width 0) (min-height 0) (orientation :horizontal)) (let (object ptype changed) (formatting-cell (stream :align-x (ecase orientation (:horizontal :center) (:vertical :center)) :align-y :center :min-width min-width :min-height min-height) (multiple-value-setq (object ptype changed) (accept type :stream stream :default default :query-identifier query-id :prompt prompt :view view))) (values object changed))) (defmethod accept-options1 ((frame gened) stream) (with-slots (default-line-style default-line-thickness default-ink default-arrow-head default-filled default-filled-ink default-text-family default-text-face default-text-size ) frame (flet ((do-body1 (stream) (formatting-column (stream) (multiple-value-bind (real) (accept-it stream 'ink default-ink "Ink" 'ink1) (setf default-ink real)) (multiple-value-bind (real) (accept-it stream 'ink default-filled-ink "Ink" 'ink2) (setf default-filled-ink real))) (formatting-column (Stream) (multiple-value-bind (thickness) (accept-it stream 'line-thickness default-line-thickness "Thickness" 'thickness) (setf default-line-thickness thickness)) (multiple-value-bind (text-style) (accept-it stream 'p-text-style (list default-text-family default-text-face) "Style" 'text-style) (setf default-text-family (first text-style)) (setf default-text-face (second text-style)))) (formatting-column (stream) (multiple-value-bind (line-style) (accept-it stream 'line-style-type default-line-style "Style" 'style) (setf default-line-style line-style)) (multiple-value-bind (text-size) (accept-it stream 'p-text-size default-text-size "Size" 'text-size) (setf default-text-size text-size))) (formatting-column (stream) (multiple-value-bind (bool) (accept-it stream 'boolean default-arrow-head "Head " 'head) (setf default-arrow-head bool)) (multiple-value-bind (bool) (accept-it stream 'boolean default-filled "Filled" 'filled) (setf default-filled bool))))) (formatting-table (stream) (do-body1 stream))))) ;;; ;;; ;;; (defun get-symbol-list () (with-application-frame (gened-frame) (with-slots (calc-int-dim inc-mode) gened-frame (append (when *bounding-boxes* (list 'boxes)) (when *origins* (list 'origins)) (when *info* (list 'infos)) (when *pretty-hl* (list 'pretty)) (when calc-int-dim (list 'dimensions)) (when inc-mode (list 'incremental)) (when *classic-warnings* (list 'warnings)))))) (defun text-cell (stream format-string &key (orientation :center)) (formatting-cell (stream :align-x orientation) (write-string (concatenate 'string " " format-string) stream))) (defmethod accept-buttons ((frame gened) stream) (with-slots (calc-int-dim inc-mode) frame (let ((last-symbol-list (get-symbol-list))) (formatting-table (stream :y-spacing '(1 :character)) (flet ((do-body (stream) (text-cell stream "Global Display Options:") (multiple-value-bind (symbol-list changed0p) (accept-it stream '(subset-completion (VISIBLE HIDDEN PRIMITIVE COMPOSITE)) *global-display-options* nil 'global-display-options :orientation :vertical :view 'list-pane-view) (setf *global-display-options* symbol-list) (text-cell stream "Object Display Options:") (multiple-value-bind (symbol-list changed1p) (accept-it stream '(subset-completion (INTERIOR BORDER)) (list (if *global-border* 'BORDER) (if *global-filled* 'INTERIOR)) nil 'object-display-options :orientation :vertical :view 'list-pane-view) (setf *global-filled* (and (member 'INTERIOR symbol-list) t) *global-border* (and (member 'BORDER symbol-list) t)) (text-cell stream "Object Handle Options:") (multiple-value-bind (symbol-list changed2p) (accept-it stream `(subset-completion (NORMAL FIXED UNFIXED START END)) *handles-symbol-list* nil 'handles :orientation :vertical :view 'list-pane-view) (setf *handles-symbol-list* symbol-list) (text-cell stream "Global Display Scaling:") (multiple-value-bind (number changed3p) (accept-it stream `(completion (1/2 1 2)) *global-scaling* nil 'gs :view 'list-pane-view :orientation :vertical) (setf *global-scaling* number) (text-cell stream "Concept Label Options:") (multiple-value-bind (symbol-list changed4p) (accept-it stream '(subset-completion (IDs PARENTS ANCESTORS)) *concept-labels* nil 'labels :view 'list-pane-view :orientation :vertical) (setf *concept-labels* symbol-list) (text-cell stream "Others:") (multiple-value-bind (symbol-list changed5p) (accept-it stream '(subset-completion (Boxes Origins Pretty Infos Warnings Dimensions Incremental)) (get-symbol-list) nil 'others :orientation :vertical :view 'list-pane-view) (setf *pretty-hl* (member 'pretty symbol-list)) (setf *bounding-boxes* (member 'boxes symbol-list)) (setf *origins* (member 'origins symbol-list)) (setf *info* (member 'infos symbol-list)) (setf *classic-warnings* (member 'warnings symbol-list)) (set-classic-infos *classic-warnings*) (setf calc-int-dim (member 'dimensions symbol-list)) (setf inc-mode (member 'incremental symbol-list)) (when (or changed0p changed1p changed2p changed3p changed4p changed5p) (when changed5p (when (or (and (member 'dimensions symbol-list) (not (member 'dimensions last-symbol-list))) (and (not (member 'dimensions symbol-list)) (member 'dimensions last-symbol-list))) (clear-hashtable) (do-incremental-updates)) (when (or (and (member 'incremental symbol-list) (not (member 'incremental last-symbol-list))) (and (not (member 'incremental symbol-list)) (member 'incremental last-symbol-list))) (when inc-mode (clear-knowledge-base) (do-incremental-updates)))) (if changed3p (progn (tick-all-objects) (do-incremental-updates)) (only-tick-all-objects))))))))))) (formatting-column (stream) (do-body stream))))))) (defmethod accept-elements ((frame gened) stream &key &allow-other-keys) (with-slots (mode) frame (formatting-table (stream) (formatting-row (stream) (formatting-cell (stream :align-x :center) (let ((element (accept 'elements :stream stream :default mode :prompt "Element"))) (setf mode element))))))) ;;; ;;; ;;; (defconstant +length+ 12) (define-presentation-type line-thickness () :inherit-from `((completion (1 2 3 4)) :name-key identity :printer present-line-thickness :highlighter highlight-line-thickness)) (defun present-line-thickness (object stream &key acceptably) (declare (ignore acceptably)) (let ((y (stream-line-height stream))) (with-room-for-graphics (stream) (draw-rectangle* stream 0 2 +length+ (- y 2) :filled nil :ink +background-ink+) (draw-line* stream 0 (floor y 2) +length+ (floor y 2) :line-thickness object)))) (defun highlight-line-thickness (continuation object stream) (surrounding-output-with-border (stream) (funcall continuation object stream))) ;;; ;;; ;;; (define-presentation-type line-style-type () :inherit-from `((completion (:solid :pattern1 :pattern2 :pattern3)) :name-key identity :printer present-line-style :highlighter highlight-line-style)) (defun decode-line-style (object) (second (assoc object +line-pattern-list+))) (defun encode-line-style (object) (first (rassoc (list object) +line-pattern-list+ :test #'equal))) (defun present-line-style (object stream &key acceptably) (declare (ignore acceptably)) (let ((y (stream-line-height stream))) (with-room-for-graphics (stream) (draw-rectangle* stream 0 2 +length+ (- y 2) :filled nil :ink +background-ink+) (draw-line* stream 0 (floor y 2) +length+ (floor y 2) :line-dashes (decode-line-style object))))) (defun highlight-line-style (continuation object stream) (surrounding-output-with-border (stream) (funcall continuation object stream))) ;;; ;;; ;;; (define-presentation-type ink () :inherit-from '((completion (0.4 0.6 0.8 0.9)) :name-key identity :printer present-ink)) (defun present-ink (object stream &key acceptably) (declare (ignore acceptably)) (let ((y (stream-line-height stream))) (with-room-for-graphics (stream) (draw-rectangle* stream 0 2 +length+ (- y 2) :filled t :ink (make-gray-color object))))) ;;; ;;; ;;; (define-presentation-type p-text-style () :inherit-from `((completion ((:sans-serif :bold) (:serif :italic) (:sans-serif nil) (:fix :bold)) :test equalp) :name-key identity :printer present-text-style)) (defun present-text-style (object stream &key) (let ((text-style (parse-text-style (append object '(:very-small))))) (with-text-style (stream text-style) (draw-text* stream "ABC" 0 0 :ink +black+)))) (define-presentation-type p-text-size () :inherit-from '((completion (:tiny :very-small :normal :very-large :huge)) :name-key identity :printer present-text-size)) (defun present-text-size (object stream &key) (case object (:tiny (write-string "T" stream)) (:very-small (write-string "S" stream)) (:normal (write-string "N" stream)) (:very-large (write-string "L" stream)) (:huge (write-string "H" stream)))) ;;; ;;; ;;; (define-presentation-type elements () :inherit-from `((completion (g-concept g-circle g-rectangle g-arrow g-chain g-spline-chain g-polygon g-spline-polygon g-text g-point)) :name-key identity :printer present-elements :highlighter highlight-element)) (defun present-elements (object stream &key) (let ((*concept-labels* nil) (*handles-symbol-list* nil) (*bounding-boxes* nil) (*origins* nil) (*global-scaling* 0.8)) (draw (second (assoc object *sample-graphic-objects*)) stream))) (defun highlight-element (continuation object stream) (surrounding-output-with-border (stream) (funcall continuation object stream))) ;;; ;;; ;;; (defmethod run-frame-top-level :before ((frame gened) &key) (initialize-gened frame)) #| (defmethod frame-standard-input ((frame gened)) (get-frame-pane frame 'command)) |# (defmethod frame-standard-output ((frame gened)) (get-frame-pane frame 'infos)) (defmethod initialize-gened ((frame gened)) (load-concepts) (load-label-object) (setf *current-file* "NONAME") (setf *global-scaling* 1) (setf *cl-error-msg-stream* (get-frame-pane frame 'infos)) (setf *cl-warn-msg-stream* (get-frame-pane frame 'infos)) (cl-set-classic-error-mode nil) (setf *classic-print-right-margin* 40)) (defun set-classic-infos (bool) (cl-set-classic-warn-mode bool)) (defmethod frame-error-output ((frame gened)) (get-frame-pane frame 'infos)) (defun clear-info-pane () (with-application-frame (gened-frame) (let ((stream (get-frame-pane gened-frame 'infos))) (window-clear stream)))) ;;; ;;; ;;; (defmethod draw-label ((frame gened) stream &key max-width max-height) (declare (ignore max-width max-height)) (updating-output (stream :unique-id *current-file* :cache-value *current-file*) (multiple-value-bind (x y) (window-inside-size stream) (with-translation (stream (- (/ x 2) 10) (+ 12 (/ y 2))) (let ((*origins* nil) (*concept-labels* nil) (*bounding-boxes* nil) (*pretty-hl* nil) (*global-border* t) (*global-filled* t) (*global-scaling* 0.8) (name (let ((num (position #\/ *current-file* :from-end t))) (subseq *current-file* (if num (1+ num) 0) (length *current-file*))))) (draw *label-shadow-object* stream) (draw *label-object* stream) (format stream "File: ~A" name)))))) ;;; ;;; ;;; (define-gesture-name :move :pointer-button (:left)) (define-gesture-name :create :pointer-button (:left :shift)) (define-gesture-name :delete :pointer-button (:middle :shift)) (define-gesture-name :inspect :pointer-button (:left :meta)) (define-gesture-name :classic-inspect :pointer-button (:right :meta)) (define-gesture-name :copy :pointer-button (:middle :control)) (define-gesture-name :scale :pointer-button (:right :shift)) (define-gesture-name :rotate :pointer-button (:left :control)) (define-gesture-name :atomize :pointer-button (:left :control)) (define-gesture-name :fix/free :pointer-button (:middle)) ;;; ----------------------------- (defparameter *gened-text-style* (make-text-style :sans-serif :roman :normal )) (defvar *gened-frame*) (defun gened (&key (force t) (process t)) (let ((port (find-port))) (setf (clim:text-style-mapping port *gened-text-style*) "-*-lucida-medium-r-normal-*-12-*-*-*-*-*-*-*") (when (or force (null *gened-frame*)) (setf *gened-frame* (make-application-frame 'gened :left 10 :top 10 :width 1000 :height 700 )) #+:Allegro (if process (mp:process-run-function "Model Browser" #'(lambda () (run-frame-top-level *gened-frame*))) (run-frame-top-level *gened-frame*)) #-:Allegro (run-frame-top-level *gened-frame*) *gened-frame*)))
17,946
Common Lisp
.lisp
519
27.957611
88
0.647515
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
f59cca95ef823b30169f6afbfff0adce3f73ce5ecf5627a192e35fd31e8b0a99
11,165
[ -1 ]
11,166
main.lisp
lambdamikel_GenEd/src/main.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defmethod only-tick-object ((object thing)) (incf (tickval object))) (defun only-tick-all-objects () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (elem liste) (only-tick-object elem))))) (defmethod tick-object ((object thing)) (incf (tickval object)) (make-poly-representation object)) (defun tick-all-objects () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (elem liste) (tick-object elem))))) (defun tick-all-text-objects () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (elem liste) (when (typep elem 'g-text) (tick-object elem)))))) ;;; ;;; ;;; (defmethod search-and-change ((object linesegment) newx newy oldx oldy) (let ((startpoint (startpoint object))) (if (and (= (first startpoint) oldx) (= (second startpoint) oldy)) (setf (startpoint object) (list newx newy)) (setf (endpoint object) (list newx newy))))) (defmethod search-and-change ((object pointlist-object) newx newy oldx oldy) (let ((pointlist (pointlist object))) (setf (pointlist object) (loop for x in pointlist by #'cddr for y in (rest pointlist) by #'cddr append (if (and (= x oldx) (= y oldy)) (list newx newy) (list x y)))))) ;;; ;;; ;;; (defmethod adjust-object-origin ((object t)) ()) (defmethod adjust-object-origin ((object linesegment)) (let ((startpoint (startpoint object)) (endpoint (endpoint object))) (only-tick-object object) (multiple-value-bind (newstartx newstarty) (transform-point object (first startpoint) (second startpoint)) (multiple-value-bind (newendx newendy) (transform-point object (first endpoint) (second endpoint)) (multiple-value-bind (newlist orgx orgy) (normalize-pointlist (list (list newstartx newstarty) (list newendx newendy))) (let ((newlist (generate-brackets newlist))) (setf (xtrans object) orgx (ytrans object) orgy (startpoint object) (second newlist) (endpoint object) (first newlist) (rotangle object) 0) (setf (x (first (handles object))) (- newstartx orgx)) (setf (y (first (handles object))) (- newstarty orgy)) (setf (x (second (handles object))) (- newendx orgx)) (setf (y (second (handles object))) (- newendy orgy)))))))) (defmethod adjust-object-origin ((object pointlist-object)) (let ((pointlist (generate-brackets (pointlist object))) (collect ())) (only-tick-object object) (dolist (elem pointlist) (multiple-value-bind (newx newy) (transform-point object (first elem) (second elem)) (push (list newx newy) collect))) (multiple-value-bind (newlist orgx orgy) (normalize-pointlist collect) (let ((nested-newlist (generate-brackets newlist))) (setf (xtrans object) orgx (ytrans object) orgy (pointlist object) newlist) (if (typep object 'rotateable-thing) (setf (rotangle object) 0)) (if (typep object 'scaleable-thing) (setf (xscale object) 1.0 (yscale object) 1.0)) (mapc #'(lambda (newpoint oldhandle) (setf (x oldhandle) (first newpoint)) (setf (y oldhandle) (second newpoint))) nested-newlist (handles object)))))) (defmethod adjust-object-origin ((object spline-object)) (only-tick-object object) (call-next-method) (init-object-properties object)) ;;; ;;; ;;; (defmethod adjust-all-attached-objects ((object t)) (dolist (handle (attached-handles object)) (adjust-object-origin (parent-object handle)) (tick-object (parent-object handle)))) ;;; ;;; ;;; (defmethod adjust-parent-concept ((object g-arrow)) (substitute-concept object 'g-arrow 'g-line)) (defmethod adjust-parent-concept ((object g-chain)) (substitute-concept object 'g-directed-chain 'g-chain)) (defmethod adjust-parent-concept ((object g-spline-chain)) (substitute-concept object 'g-directed-spline-chain 'g-spline-chain)) (defun substitute-concept (object from-concept to-concept) #+:classic (update-classic-ind-concepts object :remove t :clos-update nil) (if (not (head object)) (progn (setf (parent-concepts object) (subst to-concept from-concept (parent-concepts object))) (setf (ancestor-concepts object) (subst to-concept from-concept (ancestor-concepts object)))) (progn (setf (parent-concepts object) (subst from-concept to-concept (parent-concepts object))) (setf (ancestor-concepts object) (subst from-concept to-concept (ancestor-concepts object))))) #+:classic (update-classic-ind-concepts object :clos-update t) (only-tick-object object)) ;;; ;;; ;;; (defmethod get-right-inks ((object t) &key (handling-active nil) &allow-other-keys) (if handling-active (values +flipping-ink+ +flipping-ink+ +dash-pattern+ 1) (values (make-gray-color 0.0) (make-gray-color 0.0) nil 1))) (defmethod get-right-inks ((object fixed-object-handle) &key (handling-active nil) &allow-other-keys) (if handling-active (values +flipping-ink+ +flipping-ink+ +dash-pattern+ 1) (values (make-gray-color 0.0) (make-gray-color 1.0) nil 1))) ;;; ;;; ;;; (defmethod highlight-object ((object t)) ()) (defmethod highlight-object ((object thing)) (only-tick-object object) (setf (highlightedp object) t)) (defmethod unhighlight-object ((object t)) ()) (defmethod unhighlight-object ((object thing)) (only-tick-object object) (setf (highlightedp object) nil)) (defun unhighlight-all-objects () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (elem liste) (unhighlight-object elem))))) ;;; ;;; ;;; (defmethod get-bounding-rect ((object thing) &key (handling-active nil)) (let ((stream (get-frame-pane *application-frame* 'display)) (*bounding-boxes* nil) (*handles-symbol-list* nil) (*origins* nil) (*concept-labels* nil) (*global-border* t) (highlighted (highlightedp object))) (if highlighted (unhighlight-object object)) (multiple-value-bind (xf yf xt yt) (bounding-rectangle* (with-output-to-output-record (stream) (draw object stream :handling-active handling-active))) (with-slots (br-left br-right br-top br-bottom) object (setf br-left xf br-right xt br-top yf br-bottom yt)) (if highlighted (highlight-object object)) (values xf yf xt yt)))) (defmethod get-bounding-rect-center ((object thing) &key (handling-active nil)) (multiple-value-bind (xf yf xt yt) (get-bounding-rect object :handling-active handling-active) (values (/ (+ xf xt) 2) (/ (+ yf yt) 2)))) ;;; ;;; ;;; (defun refresh () (with-application-frame (gened-frame) (let ((stream (get-frame-pane gened-frame 'display))) (window-refresh stream)))) (defun redraw () (with-application-frame (gened-frame) (let ((stream (get-frame-pane gened-frame 'display))) (redisplay-frame-pane gened-frame stream)))) ;;; ;;; ;;; (defun new () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (clear-hashtable) (setf liste nil) (init-undo-buffer) (do-incremental-updates) (setf *current-file* "NONAME")))) (define-gened-command (com-gened-new :name "New Scene") () (with-application-frame (gened-frame) (let ((yes-or-no (notify-user gened-frame "New Scene selected! Are you sure?" :style :question))) (if yes-or-no (new))))) ;;; ;;; ;;; (define-gened-command (com-gened-exit :name "Exit Gened") () (with-application-frame (gened-frame) (let ((yes-or-no (notify-user gened-frame "Exit Gened selected! Are you sure?" :style :question))) (if yes-or-no (frame-exit gened-frame))))) ;;; ;;; ;;; (defmethod to-front ((object thing)) (with-application-frame (gened-frame) (with-slots (liste) gened-frame (only-tick-all-objects) (setf liste (delete object liste)) (push object liste)))) (define-gened-command (com-gened-to-front :name "Bring Object To Front") () (if (any-visible-objects) (let ((source-object (accept 'thing))) (terpri) (to-front source-object)))) (define-gened-command (com-bring-object-to-front) ((object 'thing :gesture nil)) (to-front object)) ;;; ;;; ;;; (define-gened-command (com-gened-find-object :name "Find Object") () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (let* ((stream (get-frame-pane gened-frame 'display)) (id-number (accepting-values (stream :own-window t :label "Enter Object's ID-Number:") (accept 'integer :stream stream :view 'gadget-dialog-view :default *id-number*)))) (find-object id-number))))) (defun find-object (id-number) (let ((object (get-object id-number))) (highlight-object object))) (defun get-object (id-number &key (saved-object-list nil)) (with-application-frame (gened-frame) (with-slots (prev-op-liste liste) gened-frame (find-if #'(lambda (elem) (when (= (id-number elem) id-number) elem)) (if saved-object-list prev-op-liste liste))))) ;;; ;;; ;;; (define-gened-command (com-gened-unmark-all-objects :name "Unmark All Objects") () (unhighlight-all-objects)) ;;; ;;; ;;; (defmethod to-back ((object thing)) (with-application-frame (gened-frame) (with-slots (liste) gened-frame (only-tick-all-objects) (setf liste (delete object liste)) (setf liste (nconc liste (list object)))))) (define-gened-command (com-gened-to-back :name "Bring Object To Back") () (if (any-visible-objects) (let ((source-object (accept 'thing))) (terpri) (to-back source-object)))) (define-gened-command (com-bring-object-to-back) ((object 'thing :gesture nil)) (to-back object)) ;;; ;;; ;;; (define-gened-command (com-gened-hide-object :name "Hide Object") () (if (any-visible-objects) (let ((*global-border* t) (*global-filled* t) (*global-display-options* '(visible composite primitive))) (only-tick-all-objects) (redraw) (let* ((source-object (accept 'thing))) (terpri) (setf (hiddenp source-object) t))))) (define-gened-command (com-hide-object) ((object 'thing :gesture nil)) (setf (hiddenp object) t)) (define-gened-command (com-gened-show-object :name "Show Object") () (if (any-invisible-objects) (let ((*global-border* t) (*global-filled* t) (*global-display-options* '(hidden composite primitive))) (only-tick-all-objects) (redraw) (let* ((source-object (accept 'thing))) (terpri) (setf (hiddenp source-object) nil))))) (define-gened-command (com-show-object) ((object 'thing :gesture nil)) (setf (hiddenp object) nil)) ;;; ;;; ;;; (defun save-object-list () (with-application-frame (gened-frame) (with-slots (liste prev-op-liste) gened-frame (setf prev-op-liste (copy-list liste)))))
11,209
Common Lisp
.lisp
356
27.185393
82
0.669971
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
19dad8e174cc1ce3a03a60d9970d37c9b38f938fab6d6877f29a861b3a23f700
11,166
[ -1 ]
11,168
init2.lisp
lambdamikel_GenEd/src/init2.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defparameter *spline-chain* (make-instance 'g-spline-chain :pointlist '(-23 -13 -12 6 -8 -10 0 0 8 -4 16 14) :initialize-handles t :head t :parent-concepts '("directed-spline-chain"))) (defparameter *spline-polygon* (make-instance 'g-spline-polygon :pointlist '(8 16 10 12 16 16 22 18 24 12 22 8 16 0 8 -8 4 -16 0 -20 -8 -16 -10 -8 -12 0 -16 4 -12 12 -4 16) :initialize-handles t :parent-concepts '("spline-polygon"))) (defparameter *label-object* nil) ; wird spaeter gebunden, Frame muss erst existieren! (defparameter *label-shadow-object* nil) (defun load-label-object () (setf *label-object* (load-object (make-pathname :host (pathname-host gened::+objects-dir+) :directory (pathname-directory gened::+objects-dir+) :name "label-object"))) (setf *label-shadow-object* (load-object (make-pathname :host (pathname-host gened::+objects-dir+) :directory (pathname-directory gened::+objects-dir+) :name "label-shadow-object"))) (translate-object *label-object* 0 0) (translate-object *label-shadow-object* 3 3)) (let ((liste (make-spline (make-spline-chain-list (generate-brackets (pointlist *spline-chain*))) 3))) (setf (spline-points *spline-chain*) (append (mapcan #'identity liste) '(-28 -20)))) (let ((liste (make-spline (make-spline-polygon-list (generate-brackets (pointlist *spline-polygon*))) 6))) (setf (spline-points *spline-polygon*) (mapcan #'identity liste))) (defparameter *sample-graphic-objects* (list (list 'g-circle (make-instance 'g-circle :radius 20)) (list 'g-rectangle (make-instance 'g-rectangle :xextend 20 :yextend 16)) (list 'g-arrow (make-instance 'g-arrow :startpoint '(-20 20) :endpoint '(20 -20) :initialize-handles t :head t)) (list 'g-chain (make-instance 'g-chain :pointlist '(-20 -10 -12 6 -8 -10 0 0 4 -4 12 8 20 20) :initialize-handles t :head t)) (list 'g-spline-chain *spline-chain*) (list 'g-spline-polygon *spline-polygon*) (list 'g-polygon (make-instance 'g-polygon :pointlist '(-16 12 16 20 12 8 16 -12 8 -20 -20 -12 -16 -8) :initialize-handles t)) (list 'g-text (make-instance 'g-text :text-string "ABC" :size :normal :face :italic :family :sans-serif)) (list 'g-point (make-instance 'g-point :linethickness 3)) (list 'g-concept (make-instance 'g-text :text-string "*!@?" :size :normal)))) ;;; ;;; ;;; (defun load-concepts () (mapc #'(lambda (x) (init-object-properties (second x))) *library*)) (defparameter *library* nil) (defun get-visualisations-of-concept (item) (find-it *library* #'(lambda (x) (eql (first x) item)))) (defun get-graphic-object (item) (second item)) (defun get-nth-visualisation-of-concept (item nth) (get-graphic-object (nth nth (get-visualisations-of-concept item)))) ;;; ;;; ;;; #| (cl-add-error-hook #'inconsistent-classic-object) |#
3,281
Common Lisp
.lisp
102
26.558824
104
0.627325
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
3cc787df9dd52bc894900b29c8a574fb7955bafac762b61ca30d54eedabd1937
11,168
[ -1 ]
11,169
rel-copy2.lisp
lambdamikel_GenEd/src/rel-copy2.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defclass stored-relations () ((belongs-to :accessor belongs-to :initarg :belongs-to) (id-number :accessor id-number :initarg :id-number) (xtrans :accessor xtrans) (ytrans :accessor ytrans))) (defclass s-object-with-head () ((head :accessor head))) (defclass s-0d (stored-relations 0d) ()) (defclass s-1d (stored-relations 1d) ()) (defclass s-directed-1d (stored-relations 1d directed-info-element s-object-with-head) ()) (defclass s-2d (stored-relations 2d) ()) (defclass s-filled-mixin () ((filledp :accessor filledp))) (defclass s-composite-thing (stored-relations 2d) ((liste :accessor liste :initform nil))) (defclass s-info-point (stored-relations 0d) ((startpoint-of :initform nil :initarg :startpoint-of :accessor startpoint-of) (endpoint-of :initform nil :initarg :endpoint-of :accessor endpoint-of))) (defclass s-g-text (stored-relations 2d) ((text-string :accessor text-string))) (defclass s-g-circle (stored-relations 2d s-filled-mixin) ((radius :accessor radius))) (defclass s-g-rectangle (stored-relations 2d s-filled-mixin) ()) (defclass s-g-polygon (stored-relations 2d s-filled-mixin) ()) (defclass s-g-spline-polygon (stored-relations 2d s-filled-mixin) ()) ;;; ;;; ;;; (defmethod print-object ((object stored-relations) stream) (print-object (belongs-to object) stream)) (defmethod get-classic-ind ((object stored-relations)) (get-classic-ind (belongs-to object))) ;;; ;;; ;;; (defmethod copy-relations ((source-object t) (destination-object stored-relations)) (setf (belongs-to destination-object) source-object) (setf (xtrans destination-object) (xtrans source-object)) (setf (ytrans destination-object) (ytrans source-object))) (defmethod copy-relations ((source-object composite-thing) (destination-object s-composite-thing)) (dolist (elem (liste source-object)) (push (make-stored-relation elem) (liste destination-object))) (call-next-method)) (defmethod copy-relations ((source-object filled-mixin) (destination-object s-filled-mixin)) (setf (filledp destination-object) (filledp source-object)) (call-next-method)) (defmethod copy-relations ((source-object g-circle) (destination-object s-g-circle)) (setf (radius destination-object) (radius source-object)) (call-next-method)) (defmethod copy-relations ((source-object g-text) (destination-object s-g-text)) (setf (text-string destination-object) (text-string source-object)) (call-next-method)) (defmethod copy-relations ((source-object info-point) (destination-object s-info-point)) (setf (startpoint-of destination-object) (get-stored-object (startpoint-of source-object))) (setf (endpoint-of destination-object) (get-stored-object (endpoint-of source-object))) (call-next-method)) ;;; ;;; ;;; (defmethod copy-relations ((source-object 0d) (destination-object 0d)) (with-slots (part-of-cluster disjoint-with start-linked-over-with end-linked-over-with start-linker-objects end-linker-objects in-relation-with-objects intersects-objects intersects-0-objects touching-objects contained-in-objects covered-by-objects directly-contained-by-object) destination-object (setf part-of-cluster (get-stored-object (part-of-cluster source-object))) (setf disjoint-with (get-stored-object (disjoint-with source-object))) (setf start-linked-over-with (get-stored-object (start-linked-over-with source-object))) (setf end-linked-over-with (get-stored-object (end-linked-over-with source-object))) (setf start-linker-objects (get-stored-object (start-linker-objects source-object))) (setf end-linker-objects (get-stored-object (end-linker-objects source-object))) (setf in-relation-with-objects (get-stored-object (in-relation-with-objects source-object))) (setf intersects-objects (get-stored-object (intersects-objects source-object))) (setf intersects-0-objects (get-stored-object (intersects-0-objects source-object))) (setf touching-objects (get-stored-object (touching-objects source-object))) (setf contained-in-objects (get-stored-object (contained-in-objects source-object))) (setf covered-by-objects (get-stored-object (covered-by-objects source-object))) (setf directly-contained-by-object (get-stored-object (directly-contained-by-object source-object)))) (call-next-method)) (defmethod copy-relations ((source-object 1d) (destination-object 1d)) (with-slots (intersects-1-objects) destination-object (setf intersects-1-objects (get-stored-object (intersects-1-objects source-object)))) (call-next-method)) (defmethod copy-relations ((source-object 2d) (destination-object 2d)) (with-slots (intersects-2-objects contains-objects covers-objects directly-contains-objects) destination-object (setf intersects-2-objects (get-stored-object (intersects-2-objects source-object))) (setf contains-objects (get-stored-object (contains-objects source-object))) (setf covers-objects (get-stored-object (covers-objects source-object))) (setf directly-contains-objects (get-stored-object (directly-contains-objects source-object)))) (call-next-method)) (defmethod copy-relations ((source-object directed-info-element) (destination-object s-directed-1d)) (setf (startpoint-related-with destination-object) (get-stored-object (startpoint-related-with source-object))) (setf (endpoint-related-with destination-object) (get-stored-object (endpoint-related-with source-object))) (setf (head destination-object) (head source-object)) (call-next-method)) ;;; ;;; ;;; (defun remove-stored-object-relations () (with-application-frame (gened-frame) (with-slots (liste stored-relations) gened-frame (setf stored-relations nil)))) (defun store-object-relations () (with-application-frame (gened-frame) (with-slots (liste stored-relations) gened-frame (setf stored-relations nil) (dolist (elem liste) (let ((rel (make-stored-relation elem))) (push rel stored-relations))) (dolist (elem liste) (copy-relations elem (get-stored-object elem)))))) (defun make-stored-relation (elem) (let ((instance (make-instance (cond ((typep elem 'composite-thing) 's-composite-thing) ((typep elem 'directed-info-element) 's-directed-1d) ((typep elem 'g-circle) 's-g-circle) ((typep elem 'g-text) 's-g-text) ((typep elem 'g-rectangle) 's-g-rectangle) ((typep elem 'g-polygon) 's-g-polygon) ((typep elem 'g-spline-polygon) 's-g-spline-polygon) ((typep elem '2d) 's-2d) ((typep elem '1d) 's-1d) ((typep elem 'info-point) 's-info-point) ((typep elem '0d) 's-0d)) :id-number (id-number elem) :belongs-to elem))) instance)) (defmethod get-stored-object ((objects cons)) (with-application-frame (gened-frame) (with-slots (stored-relations) gened-frame (mapcar #'(lambda (object) (find (id-number object) stored-relations :key #'id-number)) objects)))) (defmethod get-stored-object ((object t)) (with-application-frame (gened-frame) (with-slots (stored-relations) gened-frame (find (id-number object) stored-relations :key #'id-number)))) (defmethod get-stored-object ((object null)) nil)
7,616
Common Lisp
.lisp
194
34.690722
113
0.711934
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
3639c0631b0bc40b08ed763e2c1ecdf345a61d2e07e4cf135ad4b4f7cf18e558
11,169
[ -1 ]
11,170
comtable.lisp
lambdamikel_GenEd/src/comtable.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) (define-command-table concept-table :menu (("Select Concept-Visualisation" :command (com-gened-select-concept-visualisation)) ("divide1" :divider nil) ("Assign Concept To Object" :command (com-gened-assign-to-concept)) ("Remove Concept From Object" :command (com-gened-remove-concept)) ("divide2" :divider nil) ("Only Basic Concept For Object" :command (com-gened-only-basic-concept)) ("Only Basic Concept For All Objects" :command (com-gened-only-basic-concept-all-objects)) ("Only One Concept For Object" :command (com-gened-only-one-concept)) ("divide3" :divider nil) ("Store Object Into Library" :command (com-gened-store-into-library)) ("Remove Object From Library" :command (com-gened-remove-from-library)) ("divide4" :divider nil) ("Clear Library" :command (com-gened-clear-library)))) (define-command-table reasoning-table :menu (("Show Topological Relations" :command (com-gened-show-relations)) ("Calculate Topological Relations" :command (com-gened-calc-relations)) ("divide1" :divider nil) ("Close All Roles For All Objects" :command (com-gened-close-all-roles)) ("divide2" :divider nil) ("Open All Roles For All Objects" :command (com-gened-open-all-roles)) ("divide3" :divider nil) ("Clear Knowledge-Base" :command (com-gened-clear-kb)) ("Classic, Classify!" :command (com-gened-classify)))) (define-command-table file-table :menu (("Load Scene" :command (com-gened-load-scene)) ("Save Scene" :command (com-gened-save-scene)) ("Print Scene" :command (com-gened-print-scene)) ("Save Scene As Postscript" :command (com-gened-save-postscript)) ("divide1" :divider nil) ("Load Object" :command (com-gened-load-object)) ("Save Object" :command (com-gened-save-object)) ("divide2" :divider nil) ("Load Library" :command (com-gened-load-library)) ("Save Library" :command (com-gened-save-library)) ("divide3" :divider nil) ("New Scene" :command (com-gened-new)) ("Exit Gened" :command (com-gened-exit)))) (define-command-table manipulate-table :menu (("UNDO NOTHING" :command (com-gened-undo)) ("divide1" :divider nil) ("Move Object" :command (com-gened-move-object)) ("Scale Object" :command (com-gened-scale-object)) ("Rotate Object" :command (com-gened-rotate-object)) ("divide2" :divider nil) ("Delete Object" :command (com-gened-delete-object)) ("Copy Object" :command (com-gened-copy-object)) ("divide3" :divider nil) ("Inspect Object" :command (com-gened-inspect-object)))) (define-command-table tool-table :menu (("Compose Composite Object" :command (com-gened-build-cluster)) ("Decompose Composite Object" :command (com-gened-atomize-cluster)) ("divide1" :divider nil) ("Move Object-Handle" :command (com-gened-move-object-handle)) ("Fix Object-Handle" :command (com-gened-fix-handle)) ("Free Object-Handle" :command (com-gened-free-handle)) ("divide2" :divider nil) ("Hide Object" :command (com-gened-hide-object)) ("Show Object" :command (com-gened-show-object)) ("divide3" :divider nil) ("Bring Object To Front" :command (com-gened-to-front)) ("Bring Object To Back" :command (com-gened-to-back)) ("divide4" :divider nil) ("Find Object" :command (com-gened-find-object)) ("Unmark All Objects" :command (com-gened-unmark-all-objects)) ("Clear Info-Window" :command (clear-info-pane)) ("Redraw All" :command (refresh)))) (define-command-table spatial-table :menu (("Show Touching Objects" :command (com-gened-show-touching)) ("divide1" :divider nil) ("Show Intersecting Objects" :command (com-gened-show-intersecting)) ("Show Intersecting Objects, DIM = 0" :command (com-gened-show-intersecting-dim=0)) ("Show Intersecting Objects, DIM = 1" :command (com-gened-show-intersecting-dim=1)) ("Show Intersecting Objects, DIM = 2" :command (com-gened-show-intersecting-dim=2)) ("divide2" :divider nil) ("Show Contained In Objects" :command (com-gened-show-contained)) ("Show Containing Objects" :command (com-gened-show-containing)) ("divide3" :divider nil) ("Show Directly Contained In Object" :command (com-gened-show-directly-contained)) ("Show Directly Containing Objects" :command (com-gened-show-directly-containing)) ("divide4" :divider nil) ("Show Covered By Objects" :command (com-gened-show-covered)) ("Show Covering Objects" :command (com-gened-show-covering)) ("divide5" :divider nil) ("Show Disjoint Objects" :command (com-gened-show-disjoint)) ("Show Related Objects" :command (com-gened-show-related)) ("divide6" :divider nil) ("Show Linker Objects" :command (com-gened-show-linker)) ("Show Start-Linker Objects" :command (com-gened-show-start-linker)) ("Show End-Linker Objects" :command (com-gened-show-end-linker)) ("divide7" :divider nil) ("Show Linked Objects" :command (com-gened-show-linked)) ("Show Start-Linked Object" :command (com-gened-show-start-linked)) ("Show End-Linked Object" :command (com-gened-show-end-linked)) ("divide8" :divider nil) ("Show Opposite Linked" :command (com-gened-show-opposite))))
5,403
Common Lisp
.lisp
98
49.397959
98
0.69446
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
1499e24dd7a0c1ea7843875eaec3c6eeae9431760720b54012260b773ae15e0b
11,170
[ -1 ]
11,171
spatial3.lisp
lambdamikel_GenEd/src/spatial3.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) (defun store-output-regions () (with-application-frame (gened-frame) (let ((stream (get-frame-pane gened-frame 'display)) (*bounding-boxes* t) (*handles-symbol-list* nil)) (with-slots (liste) gened-frame (dolist (object liste) (let ((record (with-output-recording-options (stream :draw nil :record t) (with-output-to-output-record (stream) (draw object stream))))) (setf (output-record object) record))))))) ;;; ;;; ;;; ;;; (defun clear-stored-relations (liste) (dolist (elem liste) (setf (disjoint-with elem) nil) (setf (start-linked-over-with elem) nil) (setf (end-linked-over-with elem) nil) (setf (in-relation-with-objects elem) nil) (setf (touching-objects elem) nil) (setf (contained-in-objects elem) nil) (setf (covered-by-objects elem) nil) (setf (directly-contained-by-object elem) nil) (when (typep elem 'directed-info-element) (setf (startpoint-related-with elem) nil) (setf (endpoint-related-with elem) nil)) (when (typep elem 'at-least-1d) (setf (intersects-objects elem) nil)) (when (typep elem '2d) (setf (contains-objects elem) nil) (setf (covers-objects elem) nil) (setf (directly-contains-objects elem) nil) ))) (defun show-topo-info (elem1 elem2 relation stream) (when *info* (multiple-value-bind (dist orient) (distance-and-orientation (xtrans elem1) (ytrans elem1) (xtrans elem2) (ytrans elem2)) (format stream "~% Relation:~% ~A~% ~A~% ~A.~%" elem1 relation elem2) (format stream "Polar-Distance: (~D | ~D)~%" (round dist) (round (* 180 (/ orient pi))))))) (defun find-all-cluster-elements (cluster) (if (typep cluster 'composite-thing) (let ((liste (liste cluster))) (mapcan #'find-all-cluster-elements liste)) (list cluster))) (defun make-all-disjoint (liste) (dolist (elem1 liste) (dolist (elem2 liste) (unless (eq elem1 elem2) (push elem1 (disjoint-with elem2)))))) (defun remove-wrong-disjoints (liste) (dolist (elem1 liste) (dolist (elem2 liste) (if (and (not (eq elem1 elem2)) (member elem1 (in-relation-with-objects elem2))) (setf (disjoint-with elem2) (delete elem1 (disjoint-with elem2))))))) (defun install-relations-for-clusters () (with-application-frame (gened-frame) (let ((stream (get-frame-pane gened-frame 'infos))) (with-slots (liste) gened-frame (dolist (cluster1 liste) (let ((elems-of-cluster1 (find-all-cluster-elements cluster1))) (dolist (cluster2 liste) (if (and (not (eq cluster1 cluster2)) (or (typep cluster1 'composite-thing) (typep cluster2 'composite-thing))) (let* ((elems-of-cluster2 (find-all-cluster-elements cluster2))) (cond ( (some #'(lambda (x) (and (typep x 'at-least-1d) (some #'(lambda (y) (member y (intersects-objects x))) elems-of-cluster2))) elems-of-cluster1) (memoize-relation cluster1 cluster2 'intersects)) ( (and (some #'(lambda (x) (and (typep x '2d) (some #'(lambda (y) (member y (covers-objects x))) elems-of-cluster2))) elems-of-cluster1) (some #'(lambda (x) (and (typep x '2d) (every #'(lambda (y) (or (member y (contains-objects x)) (member y (covers-objects x)))) elems-of-cluster2))) elems-of-cluster1)) (memoize-relation cluster1 cluster2 'covers) (memoize-relation cluster2 cluster1 'is-covered-by)) ( (some #'(lambda (x) (and (typep x '2d) (every #'(lambda (y) (member y (contains-objects x))) elems-of-cluster2))) elems-of-cluster1) (memoize-relation cluster1 cluster2 'contains) (memoize-relation cluster2 cluster1 'is-inside)) ( (and (some #'(lambda (x) (some #'(lambda (y) (member y (touching-objects x))) elems-of-cluster2)) elems-of-cluster1) (not (some #'(lambda (x) (some #'(lambda (y) (and (member y (in-relation-with-objects x)) (not (member y (touching-objects x))))) elems-of-cluster2)) elems-of-cluster1))) (memoize-relation cluster1 cluster2 'touches)) )))))))))) (defun memoize-relation (elem1 elem2 relation) (multiple-value-bind (dist orient) (distance-and-orientation (xtrans elem1) (ytrans elem1) (xtrans elem2) (ytrans elem2)) (unless (eq relation 'is-disjoint-with) (push elem1 (in-relation-with-objects elem2))) (ecase relation (intersects (push elem1 (intersects-objects elem2))) (touches (push elem1 (touching-objects elem2))) (is-inside (push elem1 (contains-objects elem2))) (contains (push elem1 (contained-in-objects elem2))) (is-covered-by (push elem1 (covers-objects elem2)) (push elem1 (contains-objects elem2)) (push elem1 (directly-contains-objects elem2))) (covers (push elem1 (covered-by-objects elem2)) (push elem1 (contained-in-objects elem2)) (push elem1 (directly-contained-by-object elem2))) (is-disjoint-with (push elem1 (disjoint-with elem2)))))) ;;; ;;; ;;; (defun store-infos-for-arrows-and-so () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (elem liste) (when (and (typep elem 'directed-info-element) (> (length (in-relation-with-objects elem)) 1)) (let ((startpoint (make-geom-point (+ (xtrans elem) (first (startpoint elem))) (+ (ytrans elem) (second (startpoint elem))))) (endpoint (make-geom-point (+ (xtrans elem) (first (endpoint elem))) (+ (ytrans elem) (second (endpoint elem))))) (related-start-object) (related-end-object)) (dolist (touch-elem (touching-objects elem)) (when (typep touch-elem 'basic-thing) (when (touching-tres startpoint (polygonized-representation touch-elem) (* 1 (calc-right-tres))) (setf related-start-object touch-elem)) (when (touching-tres endpoint (polygonized-representation touch-elem) (* 1 (calc-right-tres))) (setf related-end-object touch-elem)))) (dolist (inter-elem (intersects-objects elem)) (when (typep inter-elem 'basic-thing) (when (inside startpoint (polygonized-representation inter-elem)) (setf related-start-object inter-elem)) (when (inside endpoint (polygonized-representation inter-elem)) (setf related-end-object inter-elem)))) (dolist (cov-elem (covered-by-objects elem)) (when (typep cov-elem 'basic-thing) (when (covers-tres (polygonized-representation cov-elem) startpoint (calc-right-tres)) (setf related-start-object cov-elem)) (when (covers-tres (polygonized-representation cov-elem) endpoint (calc-right-tres)) (setf related-end-object cov-elem)))) (when related-start-object (push related-start-object (startpoint-related-with elem)) (when related-end-object (push related-start-object (in-relation-with-objects related-end-object)) (push (list related-end-object elem) (end-linked-over-with related-start-object)))) (when related-end-object (push related-end-object (endpoint-related-with elem)) (when related-start-object (push related-end-object (in-relation-with-objects related-start-object)) (push (list related-start-object elem) (start-linked-over-with related-end-object)))) )))))) (defun find-topmost-cluster (elem) (let ((cluster elem)) (loop (if (null (part-of-cluster cluster)) (return cluster) (setf cluster (part-of-cluster cluster)))))) #| (defun propagate-for-arrows-and-so (liste) (dolist (elem liste) (when (and (typep elem 'directed-info-element) (startpoint-related-with elem) (endpoint-related-with elem)) (let ((srw (startpoint-related-with elem)) (erw (endpoint-related-with elem))) (if (and srw erw) (let ((cluster srw)) (loop (setf cluster (mapcan #'(lambda (x) (if x (let ((part-of (part-of-cluster x))) (when part-of (list part-of))))) cluster)) (if cluster (dolist (elem2 cluster) (push elem2 (startpoint-related-with elem))) (return))) (let ((cluster erw)) (loop (setf cluster (mapcan #'(lambda (x) (if x (let ((part-of (part-of-cluster x))) (when part-of (list part-of))))) cluster)) (if cluster (dolist (elem2 cluster) (push elem2 (endpoint-related-with elem))) (return)))))))))) |# (defun propagate-for-arrows-and-so (liste) (dolist (elem liste) (when (and (typep elem 'directed-info-element) (startpoint-related-with elem) (endpoint-related-with elem)) (let ((srw (first (startpoint-related-with elem))) (erw (first (endpoint-related-with elem)))) (when (and srw erw) (let ((cluster1 (find-topmost-cluster srw)) (cluster2 (find-topmost-cluster erw))) (when (not (and (eq cluster1 srw) (eq cluster2 erw))) (push cluster1 (startpoint-related-with elem)) (push cluster2 (endpoint-related-with elem)) (push (list cluster1 elem) (start-linked-over-with cluster2)) (push cluster1 (in-relation-with-objects cluster2)) (push (list cluster2 elem) (end-linked-over-with cluster1)) (push cluster2 (in-relation-with-objects cluster1)) ))))))) (defun resolve-covering-conflicts (liste) (dolist (elem liste) (when (and (typep elem '2d)) (let ((cov-elems (covers-objects elem))) (when (> (length cov-elems) 1) (dolist (cov-elem cov-elems) (when (typep cov-elem '2d) (let* ((cov-cov-elems (covers-objects cov-elem)) (conflict-elem (find-if #'(lambda (X) (member x cov-elems)) cov-cov-elems))) (when conflict-elem (setf (covers-objects elem) (delete conflict-elem cov-elems)) (setf (covered-by-objects conflict-elem) (delete elem (covered-by-objects conflict-elem))) (setf (directly-contains-objects elem) (delete conflict-elem (directly-contains-objects elem))) (if (eq (first (directly-contained-by-object conflict-elem)) elem) (setf (directly-contained-by-object conflict-elem) nil)) (push conflict-elem (contains-objects elem)) (push elem (contained-in-objects conflict-elem)) ))))))))) (defun calculate-directly-containing (liste) (flet ((memoize (elem1 elem2) (push elem2 (directly-contains-objects elem1)) (setf (directly-contained-by-object elem2) (list elem1)))) (dolist (elem liste) (let* ((contained-in-objects (remove-duplicates (contained-in-objects elem))) (l (length contained-in-objects))) (dolist (elem2 contained-in-objects) (when (or (and (typep elem2 'basic-thing) (= (length (remove-duplicates (contained-in-objects elem2))) (1- l))) (and (typep elem2 'composite-thing) (= (length (remove-duplicates (contained-in-objects elem2))) (- l 2)))) #| (format t "~A directly-contains ~A ~%" elem2 elem) |# (memoize elem2 elem))))))) (defun only-dublicates (liste &optional (akku nil)) (cond ((null liste) akku) (t (let* ((elem (first liste)) (relem (list (second elem) (first elem)))) (if (member relem liste :test #'equal) (only-dublicates (cdr (delete relem liste :test #'equal)) (cons elem akku)) (only-dublicates (cdr liste) akku)))))) (define-gened-command (com-gened-calc-relations :name "Calculate Relations") () (with-application-frame (gened-frame) (with-slots (liste saved-liste) gened-frame (clear-stored-relations liste) (atomize-all-clusters) (clear-stored-relations liste) (store-output-regions) (dolist (elem1 liste) (dolist (elem2 liste) (unless (eq elem1 elem2) (if (not (eql +nowhere+ (region-intersection (output-record elem1) (output-record elem2)))) (let ((relation (relate-poly-to-poly-unary-tres (polygonized-representation elem1) (polygonized-representation elem2) (calc-right-tres)))) (memoize-relation elem1 elem2 relation)) (memoize-relation elem1 elem2 'is-disjoint-with)) ))) (resolve-covering-conflicts liste) (reinstall-all-clusters) (make-all-disjoint liste) (store-infos-for-arrows-and-so) (propagate-for-arrows-and-so liste) (calculate-directly-containing liste) (install-relations-for-clusters) (calculate-directly-containing liste) (remove-wrong-disjoints liste) (show-infos) ))) (defun show-infos () (with-application-frame (gened-frame) (let ((stream (get-frame-pane gened-frame 'infos)) (mem-list nil)) (window-clear stream) (with-slots (liste) gened-frame (dolist (elem liste) (mapcar #'(lambda (relation-accessor-symbol relation-symbol-list) (when (slot-exists-p elem relation-accessor-symbol) (let ((relation-symbol (first relation-symbol-list)) (inverse-relation-symbol (second relation-symbol-list))) (dolist (rel-elem (funcall (symbol-function relation-accessor-symbol) elem)) (when (and (member rel-elem liste) (not (member (list relation-symbol elem rel-elem) mem-list :test #'equal))) (push (list relation-symbol elem rel-elem) mem-list) (push (list relation-symbol rel-elem elem) mem-list) (show-topo-info elem rel-elem relation-symbol stream) (show-topo-info rel-elem elem inverse-relation-symbol stream)))))) '(touching-objects intersects-objects directly-contained-by-object contained-in-objects covered-by-objects linked-over-with disjoint-with) '((touches touches) (intersects intersects) (directly-contained-in directly-contains) (contained-in contains) (is-covered-by covers) (is-linked-over-with is-linked-over-with) (is-disjoint-with is-disjoint-with)))))))) ;;; ;;; ;;; (defmethod show-map-over ((object thing) accessor) (dolist (elem (funcall accessor object)) (highlight-object elem)) (let ((*bounding-boxes* t)) (redraw))) (define-gened-command (com-gened-show-touching :name "Show Touching Objects") () (if (any-visible-objects) (let ((object (accept 'thing))) (show-map-over object #'touching-objects)))) (define-gened-command (com-show-touching :name "Show Touching Objects") ((object 'thing :gesture nil)) (show-map-over object #'touching-objects)) ;;; ;;; (define-gened-command (com-gened-show-intersecting :name "Show Intersecting Objects") () (if (any-visible-objects) (let ((object (accept 'thing))) (show-map-over object #'intersects-objects)))) (define-gened-command (com-show-intersecting :name "Show Intersecting Objects") ((object 'thing :gesture nil)) (show-map-over object #'intersects-objects)) ;;; ;;; (define-gened-command (com-gened-show-contained :name "Show Contained In Objects") () (if (any-visible-objects) (let ((object (accept 'thing))) (show-map-over object #'contained-in-objects)))) (define-gened-command (com-show-contained :name "Show Contained In Objects") ((object 'thing :gesture nil)) (show-map-over object #'contained-in-objects)) ;;; ;;; (define-gened-command (com-gened-show-containing :name "Show Containing Objects") () (if (any-visible-objects) (let ((object (accept 'thing))) (show-map-over object #'contains-objects)))) (define-gened-command (com-show-containing :name "Show Containing Objects") ((object 'thing :gesture nil)) (show-map-over object #'contains-objects)) ;;; ;;; (define-gened-command (com-gened-show-directly-contained :name "Show Directly Contained In Object") () (if (any-visible-objects) (let ((object (accept 'thing))) (show-map-over object #'directly-contained-by-object)))) (define-gened-command (com-show-directly-contained :name "Show Directly Contained In Object") ((object 'thing :gesture nil)) (show-map-over object #'directly-contained-by-object)) ;;; ;;; (define-gened-command (com-gened-show-directly-containing :name "Show Directly Containing Objects") () (if (any-visible-objects) (let ((object (accept 'thing))) (show-map-over object #'directly-contains-objects)))) (define-gened-command (com-show-directly-containing :name "Show Directly Containing Objects") ((object 'thing :gesture nil)) (show-map-over object #'directly-contains-objects)) ;;; ;;; (define-gened-command (com-gened-show-covered :name "Show Covered By Objects") () (if (any-visible-objects) (let ((object (accept 'thing))) (show-map-over object #'covered-by-objects)))) (define-gened-command (com-show-covered :name "Show Coverd By Objects") ((object 'thing :gesture nil)) (show-map-over object #'covered-by-objects)) ;;; ;;; (define-gened-command (com-gened-show-covering :name "Show Covering Objects") () (if (any-visible-objects) (let ((object (accept 'thing))) (show-map-over object #'covers-objects)))) (define-gened-command (com-show-covering :name "Show Covering Objects") ((object 'thing :gesture nil)) (show-map-over object #'covers-objects)) ;;; ;;; (define-gened-command (com-gened-show-disjoint :name "Show Disjoint Objects") () (if (any-visible-objects) (let ((object (accept 'thing))) (show-map-over object #'disjoint-with)))) (define-gened-command (com-show-disjoint :name "Show Disjoint Objects") ((object 'thing :gesture nil)) (show-map-over object #'disjoint-with)) ;;; ;;; (define-gened-command (com-gened-show-related :name "Show Related Objects") () (if (any-visible-objects) (let ((object (accept 'thing))) (show-map-over object #'in-relation-with-objects)))) (define-gened-command (com-show-related :name "Show Related Objects") ((object 'thing :gesture nil)) (show-map-over object #'in-relation-with-objects)) ;;; ;;; (define-gened-command (com-gened-show-linked :name "Show Linked Objects") () (when (any-visible-objects) (let* ((object (accept 'directed-info-element))) (highlight-object (first (endpoint-related-with object))) (highlight-object (first (startpoint-related-with object)))) (let ((*bounding-boxes* t)) (redraw)))) (define-gened-command (com-gened-show-start-linked :name "Show Start-Linked Objects") () (when (any-visible-directed-objects) (let ((object (accept 'directed-info-element))) (highlight-object (first (startpoint-related-with object)))) (let ((*bounding-boxes* t)) (redraw)))) (define-gened-command (com-gened-show-end-linked :name "Show End-Linked Objects") () (when (any-visible-directed-objects) (let ((object (accept 'directed-info-element))) (highlight-object (first (endpoint-related-with object)))) (let ((*bounding-boxes* t)) (redraw)))) ;;; ;;; ;;; (define-gened-command (com-gened-show-opposite :name "Show Opposite Objects") () (when (any-visible-objects) (let ((object (accept 'thing))) (mapc #'(lambda (x) (highlight-object (first x))) (append (start-linked-over-with object) (end-linked-over-with object)))) (let ((*bounding-boxes* t)) (redraw)))) ;;;; (define-gened-command (com-gened-show-linker :name "Show Linker Objects") () (when (any-visible-objects) (let ((object (accept 'thing))) (mapc #'(lambda (x) (highlight-object (second x))) (append (start-linked-over-with object) (end-linked-over-with object))) (let ((*bounding-boxes* t)) (redraw)))))
20,603
Common Lisp
.lisp
560
30.232143
99
0.648469
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
f5ffd58a26fb7f406e0f30ade83c3aa06cdfe843edbe654b9ace4b3f93991797
11,171
[ -1 ]
11,172
creator.lisp
lambdamikel_GenEd/src/creator.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defmethod create ((object g-point) (orgx integer) (orgy integer)) (init-object-properties object)) (defmethod create ((object g-rectangle) (orgx integer) (orgy integer)) (when *info* (format t "~%Press Left Mouse-Button To Release!~%")) (loop (interactive-master-creator object #'(lambda (nowx nowy) (with-slots (xtrans ytrans xextend yextend) object (let ((dx (/ (- nowx orgx) 2)) (dy (/ (- nowy orgy) 2))) (setf xtrans (/ (+ nowx orgx) 2) ytrans (/ (+ nowy orgy) 2) xextend dx yextend dy))))) (if (object-ok-p object) (return) (beep))) (init-object-properties object)) (defmethod create ((object linesegment) (orgx integer) (orgy integer)) (when *info* (format t "~%Press Left Mouse-Button To Release!~%")) (loop (interactive-master-creator object #'(lambda (nowx nowy) (with-slots (xtrans ytrans startpoint endpoint) object (let ((dx (/ (- nowx orgx) 2)) (dy (/ (- nowy orgy) 2))) (setf xtrans (/ (+ nowx orgx) 2) ytrans (/ (+ nowy orgy) 2) startpoint (list (- dx) (- dy)) endpoint (list dx dy)))))) (if (object-ok-p object) (return) (beep))) (init-object-properties object)) (defmethod create ((object g-text) (orgx integer) (orgy integer)) (let ((stream (get-frame-pane *application-frame* 'display))) (loop (setf (text-string object) (accepting-values (stream :own-window t :label "Enter Text:") (accept 'string :stream stream :view 'gadget-dialog-view :default "Text" :default-type 'string))) (if (object-ok-p object) (return) (beep))) (init-object-properties object))) (defmethod create ((object g-circle) (orgx integer) (orgy integer)) (when *info* (format t "~%Press Left Mouse-Button To Release!~%")) (loop (interactive-master-creator object #'(lambda (nowx nowy) (with-slots (xtrans ytrans radius) object (let* ((dx (- nowx orgx)) (dy (- nowy orgy)) (d (round (sqrt (+ (* dx dx) (* dy dy)))))) (setf xtrans orgx ytrans orgy radius d))))) (if (object-ok-p object) (return) (beep))) (init-object-properties object)) (defmethod create ((object pointlist-object) (orgx integer) (orgy integer)) (when *info* (format t "~%Press Left Mouse-Button To Fix Point,~% Middle Button To Delete Last Point,~% Right Mouse-Button To Finish!~%")) (setf (pointlist object) '(0 0)) (let ((templist (list (list orgx orgy) (list orgx orgy))) (stream (get-frame-pane *application-frame* 'display))) (with-output-recording-options (stream :draw t :record nil) (flet ((draw-it () (draw object stream :handling-active t) (transform-and-draw object stream #'(lambda () (draw-marker* stream (pointlist object) 2 :ink +flipping-ink+ :line-thickness +mr-line-thickness+))))) (draw-it) (block track-pointer (tracking-pointer (stream) (:pointer-motion (x y) (multiple-value-bind (x y) (scale-mouse-position x y :inverse t) (with-slots (pointlist xtrans ytrans) object (draw-it) (setf (first templist) (list x y)) (multiple-value-bind (newtemplist newxtrans newytrans) (normalize-pointlist templist) (setf xtrans newxtrans) (setf ytrans newytrans) (setf pointlist newtemplist) (draw-it))))) (:pointer-button-press (x y event) (multiple-value-bind (x y) (scale-mouse-position x y :inverse t) (let ((button-event (pointer-event-button event))) (if (or (and (not (member (list x y) (rest templist) :test #'equal)) (object-ok-p object)) (eql button-event +pointer-middle-button+)) (cond ((eql button-event +pointer-right-button+) (if (pointlist-ok-p object) (progn (draw-it) (init-object-properties object) (return-from track-pointer)) (beep))) ((and (eql button-event +pointer-middle-button+) (> (length templist) 1)) (pop templist)) ((eql button-event +pointer-left-button+) (push (list x y) templist)) (t (beep))) (beep))))))))))) ;;; ;;; ;;; (defun create-object (x y) (let ((*global-border* t)) (multiple-value-bind (x y) (scale-mouse-position x y :inverse t) (with-application-frame (gened-frame) (with-slots (liste mode concept-type) gened-frame (if (not (eq mode 'g-concept)) (let ((object (make-instance mode :xtrans x :ytrans y :initialize t))) (push object liste) (create object x y) (make-undo-object object 'create)) (if (null concept-type) (notify-user gened-frame "Select a concept first!" :style :error) (let* ((object (get-nth-visualisation-of-concept (first concept-type) (second concept-type))) (object2 (make-instance (type-of object) :initialize nil))) (copy-values object object2) (translate-object object2 x y) (push object2 liste) (make-poly-representation object2) (make-undo-object object2 'create)))))))) (do-incremental-updates)) (define-gened-command (com-create-object :name "Create Object") ((x 'integer) (y 'integer)) (create-object x y)) (define-presentation-to-command-translator create (blank-area com-create-object gened :gesture :create) (x y) (list x y))
5,942
Common Lisp
.lisp
169
27.402367
145
0.599677
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
8adc1ee9a2740fbbd954094d48c297d28dfd511859bd658b6fce39144239bd37
11,172
[ -1 ]
11,173
delta2.lisp
lambdamikel_GenEd/src/delta2.lisp
;;; -*- Mode: LISP; Syntax: Ansi-Common-Lisp; Package: GENED -*- (in-package gened) ;;; ;;; ;;; #-:classic (defun do-incremental-updates (&key (backward nil)) nil) #+:classic (defun do-incremental-updates (&key (backward nil)) (with-application-frame (gened-frame) (with-slots (inc-mode liste stored-relations) gened-frame (when inc-mode (let ((*info* nil)) (calc-relations)) (setf liste (install-points liste)) (let ((delta1 (set-difference liste stored-relations :key #'id-number)) (delta2 (set-difference stored-relations liste :key #'id-number))) (if backward (progn (dolist (elem delta2) (delete-classic-ind elem)) (dolist (elem delta1) ; Objekte, die neu hinzugekommen sind (create-classic-ind elem)) (dolist (elem delta1) (fill-all-roles elem))) (progn (dolist (elem delta2) (delete-classic-ind elem)) (dolist (elem delta1) ; Objekte, die neu hinzugekommen sind (create-classic-ind elem)) (dolist (elem delta1) (fill-all-roles elem)))) (dolist (copy stored-relations) (let ((original (get-object (id-number copy)))) (when (not (or (member (id-number copy) delta1 :key #'id-number) (member (id-number copy) delta2 :key #'id-number))) (when *info* (format t "~%Updating DELTA for Object ~A~%" original)) (do-incremental-classic-updates original copy :backward backward))))) (update-parent-concepts) (store-object-relations) (setf liste (remove-points liste)))))) #-:classic (defun do-incremental-classic-updates (orig-object copy &key (backward nil)) nil) #+:classic (defun do-incremental-classic-updates (orig-object copy &key (backward nil)) (dolist (slot (object-delta orig-object copy)) (let ((prev-cont (if backward (funcall slot orig-object) (funcall slot copy))) (cont (if backward (funcall slot copy) (funcall slot orig-object)))) (if (and (listp cont) (listp prev-cont)) (if (subsetp prev-cont cont :key #'id-number) (if backward (remove-information orig-object slot (set-difference cont prev-cont :key #'id-number)) (add-information orig-object slot (set-difference cont prev-cont :key #'id-number))) (if (subsetp cont prev-cont :key #'id-number) (if backward (add-information orig-object slot (set-difference prev-cont cont :key #'id-number)) (remove-information orig-object slot (set-difference prev-cont cont :key #'id-number))))) (if backward (progn (remove-information orig-object slot cont) (add-information orig-object slot prev-cont)) (progn (remove-information orig-object slot prev-cont) (add-information orig-object slot cont))))))) ;;; ;;; ;;; (defgeneric all-slots (object) (:method-combination append)) ;;; ;;; ;;; (defun get-unique-slot-output (content) (when content (if (atom content) (list content) content))) (defun get-delta (object1 object2 slot-names) (mapcan #'(lambda (rel-sym) (let ((l1 (funcall rel-sym object1)) (l2 (funcall rel-sym object2))) (when (or (and l1 (not l2)) (and l2 (not l1)) (and (listp l1) (listp l2) (not (and (subsetp l1 l2 :key #'id-number) (subsetp l2 l1 :key #'id-number)))) (not (equalp l1 l2))) (list rel-sym)))) slot-names)) ;;; ;;; ;;; (defmethod all-slots append ((object composite-thing)) '(liste)) (defmethod all-slots append ((object s-composite-thing)) '(liste)) (defmethod all-slots append ((object filled-mixin)) '(filledp)) (defmethod all-slots append ((object s-filled-mixin)) '(filledp)) (defmethod all-slots append ((object g-text)) '(text-string)) (defmethod all-slots append ((object s-g-text)) '(text-string)) (defmethod all-slots append ((object g-circle)) '(radius)) (defmethod all-slots append ((object s-g-circle)) '(radius)) (defmethod all-slots append ((object thing)) '(xtrans ytrans)) (defmethod all-slots append ((object stored-relations)) '(xtrans ytrans)) (defmethod all-slots append ((object 0d)) '(part-of-cluster ; disjoint-with calc-linker-objects calc-start-linker-objects calc-end-linker-objects calc-linked-over-with calc-start-linked-over-with calc-end-linked-over-with intersects-objects intersects-0-objects touching-objects directly-contained-by-object contained-in-objects covered-by-objects)) (defmethod all-slots append ((object 1d)) '(intersects-1-objects)) (defmethod all-slots append ((object 2d)) '(intersects-2-objects directly-contains-objects contains-objects covers-objects)) ;;; Achtung: calc-... sind VIRTUELLE SLOTS, die erst berechnet werden muessen! -> MAPPING in "interface-to-classic" (defmethod all-slots append ((object directed-info-element)) '(calc-startpoint-related-with calc-endpoint-related-with calc-points-related-with)) (defmethod all-slots append ((object s-directed-1d)) '(calc-startpoint-related-with calc-endpoint-related-with calc-points-related-with)) (defmethod all-slots append ((object s-info-point)) '(calc-startpoint-of calc-endpoint-of calc-point-of)) (defmethod all-slots append ((object info-point)) '(calc-startpoint-of calc-endpoint-of calc-point-of)) ;;; ;;; ;;; (defmethod object-delta ((object1 0d) (object2 0d)) (get-delta object1 object2 (union (all-slots object1) (all-slots object2))))
5,687
Common Lisp
.lisp
177
26.915254
115
0.674266
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
dda0b3dcb2bb94520cd0e9a369d1dee173ad3dac3d459416354b215e4f26025d
11,173
[ -1 ]
11,174
delete.lisp
lambdamikel_GenEd/src/delete.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defmethod delete-it ((object basic-thing)) (with-application-frame (gened-frame) (with-slots (liste) gened-frame (delete-polyrep-from-cache object) (setf liste (delete object liste :test #'equal))))) (defmethod delete-it ((object composite-thing)) (dolist (elem (liste object)) (delete-it elem)) (with-application-frame (gened-frame) (with-slots (liste) gened-frame (setf liste (delete object liste :test #'equal))))) (defmethod delete-object ((object thing) &key (undo-object t)) (if undo-object (make-undo-object object 'delete)) (delete-it object) (free-all-handles object) (free-my-handles object) (do-incremental-updates)) (define-gened-command (com-delete-object) ((object 'thing :gesture :delete)) (delete-object object)) (define-gened-command (com-gened-delete-object :name "Delete Object") () (if (any-visible-objects) (let ((source-object (accept 'thing))) (terpri) (delete-object source-object))))
1,092
Common Lisp
.lisp
31
31.774194
74
0.693257
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
330a7afced10c9bbfa435488a6397cab9033224867bc6b01c9b1412ec82aeee3
11,174
[ -1 ]
11,175
concepts.lisp
lambdamikel_GenEd/src/concepts.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defun generate-name (symbol) (write-to-string symbol :escape nil)) (defun construct-concept-menu () (mapcar #'(lambda (concept) (list concept ':items (let ((num 0)) (loop for visu in (get-visualisations-of-concept concept) collect (cons (list concept num) visu) do (incf num))))) +library-concepts+)) (defun select-visualisation () (let ((*handles-symbol-list* nil) (*concept-labels* nil) (*bounding-boxes* t) (*global-scaling* 1)) (load-concepts) (with-application-frame (gened-frame) (if (null +library-concepts+) (notify-user gened-frame "No known concepts at all!" :style :error) (let ((item (menu-choose (construct-concept-menu) :label "Select A Concept-Visualisation!" :printer #'(lambda (item stream) (if (not (member ':items item)) (let ((graphic-object (third item))) (multiple-value-bind (xf yf xt yt) (get-bounding-rect graphic-object) (with-scaling (stream (/ 50 (- xt xf)) (/ 50 (- yt yf))) (draw graphic-object stream)))) (princ (first item) stream)))))) (if (and item (atom item)) (progn (notify-user gened-frame (format nil "No visualisation selected for ~A!" item) :style :error) nil) item)))))) (defun select-concept (object &key (only-library-concepts nil)) (let ((object (cond ((typep object 'start-handle) (start-info-point (parent-object object))) ((typep object 'end-handle) (end-info-point (parent-object object))) (t object)))) (let ((concepts (let ((concepts (remove-duplicates (append (parent-concepts object) (ancestor-concepts object))))) (if only-library-concepts (reverse (intersection +library-concepts+ concepts)) concepts)))) (if (null concepts) 'error (menu-choose concepts :label "Select One Of Objects Concepts!"))))) (define-gened-command (com-gened-select-concept-visualisation :name "Select Concept-Visualisation") () (with-application-frame (gened-frame) (with-slots (concept-type) gened-frame (let ((item (select-visualisation))) (setf concept-type item))))) ;;; ;;; ;;; (defmethod remove-concept-from-object ((object thing) &key (classic-ind-update t)) (with-application-frame (gened-frame) (let ((item (select-concept object))) (if (eq item 'error) (notify-user gened-frame "No more concepts to remove!" :style :error) (unless (null item) #+:classic (when classic-ind-update (update-classic-ind-concepts object :remove t)) (setf (parent-concepts object) (delete item (parent-concepts object))) (setf (ancestor-concepts object) (delete item (ancestor-concepts object))) #+:classic (when classic-ind-update (update-classic-ind-concepts object)))))) (only-tick-object object)) (defmethod remove-concept-from-object ((object start-handle) &key (classic-ind-update t)) (let ((object (parent-object object))) (remove-concept-from-object (start-info-point object) :classic-ind-update classic-ind-update))) (defmethod remove-concept-from-object ((object end-handle) &key (classic-ind-update t)) (let ((object (parent-object object))) (remove-concept-from-object (end-info-point object) :classic-ind-update classic-ind-update))) (define-gened-command (com-gened-remove-concept :name "Remove Concept From Object") () (if (any-visible-objects) (let ((source-object (accept '(or thing object-handle)))) (terpri) (remove-concept-from-object source-object)))) (define-gened-command (com-remove-concept-from-object) ((object '(or thing object-handle) :gesture nil)) (remove-concept-from-object object)) ;;; ;;; ;;; (define-gened-command (com-gened-remove-from-library :name "Remove Object From Library") () (let ((item (select-visualisation))) (when item (setf *library* (remove (list (first item) (get-nth-visualisation-of-concept (first item) (second item))) *library* :test #'equal))))) ;;; ;;; ;;; (defun get-concept-name (symbol) (write-to-string symbol :escape nil)) (defmethod push-concept ((object thing) concept-symbol &key (into-library nil) (ancestor nil) (classic-ind-update t)) (if ancestor (unless (member concept-symbol (ancestor-concepts object)) (push concept-symbol (ancestor-concepts object))) (unless (member concept-symbol (parent-concepts object)) (push concept-symbol (parent-concepts object)))) (when into-library (store-into-library object)) (only-tick-object object) #+:classic-ind (when classic-ind-update (update-classic-ind-concepts object))) (defmethod push-concept ((object start-handle) concept-symbol &key (into-library nil) (ancestor nil) (classic-ind-update t)) (let ((object (parent-object object))) (push-concept (start-info-point object) concept-symbol :into-library into-library :ancestor ancestor :classic-ind-update classic-ind-update))) (defmethod push-concept ((object end-handle) concept-symbol &key (into-library nil) (ancestor nil) (classic-ind-update t)) (let ((object (parent-object object))) (push-concept (end-info-point object) concept-symbol :into-library into-library :ancestor ancestor :classic-ind-update classic-ind-update))) ;;; ;;; ;;; (defmethod remove-all-concepts ((object thing) &key (classic-ind-update t)) #+:classic (when classic-ind-update (update-classic-ind-concepts object :remove t)) (setf (parent-concepts object) nil) (setf (ancestor-concepts object) nil) (only-tick-object object)) (defmethod remove-all-concepts ((object start-handle) &key (classic-ind-update t)) (let ((object (parent-object object))) (remove-all-concepts (start-info-point object) :classic-ind-update classic-ind-update))) (defmethod remove-all-concepts ((object end-handle) &key (classic-ind-update t)) (let ((object (parent-object object))) (remove-all-concepts (end-info-point object) :classic-ind-update classic-ind-update))) (defmethod assign-to-concept ((object t)) ; object thing (load-concepts) (with-application-frame (gened-frame) (if (null +library-concepts+) (notify-user gened-frame "No concepts at all!" :style :error) (let ((item (menu-choose +library-concepts+ :label "Select A Library-Concept!"))) (unless (null item) (push-concept object item)))))) ;;; ;;; ;;; (defmethod store-into-library ((object thing)) (with-application-frame (gened-frame) (let ((concept (select-concept object :only-library-concepts t))) (if (eq concept 'error) (notify-user gened-frame "No concepts at all!" :style :error) (if (not (null concept)) (let ((visualisations (mapcar #'second (get-visualisations-of-concept concept)))) (unless (member object visualisations :test #'eq) (let ((destination-object (make-instance (type-of object) :initialize nil))) (setf (parent-concepts destination-object) (list concept)) (copy-values object destination-object) (push (list concept destination-object) *library*)))) (notify-user gened-frame "No concept selected!" :style :error)))))) ;;; ;;; ;;; (define-gened-command (com-gened-assign-to-concept :name "Assign Concept To Object") () (if (any-visible-objects) (let ((source-object (accept '(or thing object-handle)))) (terpri) (assign-to-concept source-object)))) (define-gened-command (com-assign-concept-to-object) ((object '(or thing object-handle) :gesture nil)) (assign-to-concept object)) ;;; ;;; ;;; (define-gened-command (com-gened-store-into-library :name "Store Object Into Library") () (if (any-visible-objects) (let ((source-object (accept 'thing))) (terpri) (store-into-library source-object)))) (define-gened-command (com-store-object-into-library) ((object 'thing :gesture nil)) (store-into-library object)) ;;; ;;; ;;; (define-gened-command (com-gened-clear-library :name "Clear Library") () (with-application-frame (gened-frame) (let ((yes-or-no (notify-user gened-frame "Clear Library selected! Are you sure?" :style :question))) (if yes-or-no (With-slots (liste) gened-frame (setf *library* nil)))))) ;;; ;;; ;;; (defmethod remove-all-but-basic-concept ((object thing) &key (classic-ind-update t)) (remove-all-but-one-concept object (get-basic-concept object) :classic-ind-update classic-ind-update)) (defmethod remove-all-but-basic-concept ((object object-handle) &key (classic-ind-update t)) (remove-all-but-one-concept object 'info-point :classic-ind-update classic-ind-update)) (define-gened-command (com-gened-only-basic-concept :name "Only Basic-Concept For Object") () (if (any-visible-objects) (let ((source-object (accept '(or thing object-handle)))) (terpri) (remove-all-but-basic-concept source-object)))) (define-gened-command (com-only-basic-concept-for-object) ((object '(or thing object-handle) :gesture nil)) (remove-all-but-basic-concept object)) ;;; ;;; ;;; (defmethod remove-all-but-one-concept ((object thing) concept &key (classic-ind-update t)) #+:classic (when classic-ind-update (update-classic-ind-concepts object :remove t)) (setf (parent-concepts object) (list concept)) (setf (ancestor-concepts object) nil) (only-tick-object object) #+:classic (when classic-ind-update (update-classic-ind-concepts object))) (defmethod remove-all-but-one-concept ((object start-handle) concept &key (classic-ind-update t)) (let ((object (parent-object object))) (remove-all-but-one-concept (start-info-point object) concept :classic-ind-update classic-ind-update))) (defmethod remove-all-but-one-concept ((object end-handle) concept &key (classic-ind-update t)) (let ((object (parent-object object))) (remove-all-but-one-concept (end-info-point object) concept :classic-ind-update classic-ind-update))) ;;; ;;; ;;; (defmethod only-one-concept ((object t)) (with-application-frame (gened-frame) (if (null +library-concepts+) (notify-user gened-frame "No concepts at all!" :style :error) (let ((item (menu-choose +library-concepts+ :label "Select A Library-Concept!"))) (unless (null item) (remove-all-but-one-concept object item)))))) (define-gened-command (com-gened-only-one-concept :name "Only One Concept For Object") () (if (any-visible-objects) (let* ((source-object (accept '(or thing object-handle)))) (terpri) (only-one-concept source-object)))) (define-gened-command (com-only-one-concept-for-object) ((object '(or thing object-handle) :gesture nil)) (only-one-concept object)) ;;; ;;; ;;; (define-gened-command (com-gened-only-basic-concept-all-objects :name "Only Basic-Concept For All Objects") () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (setf liste (install-points liste)) (dolist (object liste) (remove-all-but-basic-concept object)) (setf liste (remove-points liste)))) (redraw))
11,589
Common Lisp
.lisp
346
28.687861
107
0.670817
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
651ea97b6d63cbb0a3bfe961af6ee41df97bcb27966b531f9f02ac765ff676ee
11,175
[ -1 ]
11,176
frame.lisp
lambdamikel_GenEd/src/frame.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (define-application-frame gened () ( (liste :initform nil) (stored-relations :initform nil) (saved-liste :initform nil) (prev-op-liste :initform nil) (mode :initform 'g-circle) (concept-type :initform nil) (calc-int-dim :initform nil) (inc-mode :initform nil) (default-arrow-head :initform t) (default-line-thickness :initform 2) (default-line-style :initform :solid) (default-ink :initform 0.4) (default-text-family :initform :sans-serif) (default-text-face :initform :bold) (default-text-size :initform :normal) (default-filled-ink :initform 0.8) (default-filled :initform nil) (buffer-counter :initform 0) (object-copy-buffer :initform (make-array +buffer-size+))) (:command-table (gened :inherit-from (concept-table file-table tool-table manipulate-table reasoning-table spatial-table) :menu (("File" :menu file-table) ("Tools" :menu tool-table) ("Manipulate" :menu manipulate-table) ("Reasoning" :menu reasoning-table) ("Concepts" :menu concept-table) ("Spatial" :menu spatial-table)))) (:panes (pointer-documentation-pane (make-clim-stream-pane :type 'pointer-documentation-pane :foreground +white+ :background +black+ :text-style (make-text-style :sans-serif :bold :small) :scroll-bars nil :min-height '(1 :line) :height '(1 :line))) (display :application :display-function 'draw-gened :textcursor nil :width 600 :redisplay-after-commands nil :incremental-redisplay t) (label :application :scroll-bars nil :min-width 200 :redisplay-after-commands nil :incremental-redisplay t :display-function 'draw-label :foreground +white+ :background +black+) (infos :application :textcursor nil :text-style (parse-text-style '(:sans-serif :roman :very-small)) :width 300 :end-of-line-action :allow :scroll-bars :both :incremental-redisplay nil) (command :interactor :height '(2 :line)) (options1 :accept-values :min-height :compute :min-width :compute :width :compute :max-width :compute :scroll-bars nil :display-function `(accept-values-pane-displayer :displayer ,#'(lambda (frame stream) (accept-options1 frame stream)))) (options2 :accept-values :min-height :compute :min-width :compute :width :compute :max-width :compute :scroll-bars nil :display-function `(accept-values-pane-displayer :displayer ,#'(lambda (frame stream) (accept-options2 frame stream)))) (elements :accept-values :scroll-bars nil :min-height :compute :height :compute :max-height :compute :display-function `(accept-values-pane-displayer :displayer ,#'(lambda (frame stream) (accept-elements frame stream)))) (buttons :accept-values :scroll-bars nil :min-height :compute :height :compute :max-height :compute :display-function `(accept-values-pane-displayer #| :resynchronize-every-pass t |# :displayer ,#'(lambda (frame stream) (accept-buttons frame stream))))) (:layouts (:default (vertically () (horizontally () (vertically () elements options1 options2) (outlining (:thichness 2) label)) (horizontally () buttons display infos) command pointer-documentation-pane)))) #| (defmethod read-frame-command ((frame gened) &key (stream *standard-input*)) (read-command (frame-command-table frame) :use-keystrokes t :stream stream)) |# (defun accept-it (stream type default prompt query-id &key (view 'gadget-dialog-view) (min-width 200) (min-height 20) orientation) (let (object ptype changed) (formatting-cell (stream :align-x (ecase orientation (:horizontal :left) (:vertical :center)) :align-y :center :min-width min-width :min-height min-height) (multiple-value-setq (object ptype changed) (accept type :stream stream :default default :query-identifier query-id :prompt prompt :view view))) (values object changed))) (defmethod accept-options1 ((frame gened) stream &key (orientation :horizontal)) (with-slots (default-line-style default-line-thickness default-ink default-arrow-head) frame (formatting-table (stream) (flet ((do-body (stream) (multiple-value-bind (real) (accept-it stream 'ink default-ink "Ink" 'ink :orientation orientation :min-width 205) (setf default-ink real) (multiple-value-bind (thickness) (accept-it stream 'line-thickness default-line-thickness "Thickness" 'thickness :orientation orientation :min-width 323) (setf default-line-thickness thickness) (multiple-value-bind (line-style) (accept-it stream 'line-style-type default-line-style "Style" 'style :orientation orientation :min-width 270) (setf default-line-style line-style)) (multiple-value-bind (bool) (accept-it stream 'boolean default-arrow-head "Head " 'head :orientation orientation) (setf default-arrow-head bool)))))) (ecase orientation (:horizontal (formatting-row (stream) (do-body stream))) (:vertical (formatting-column (stream) (do-body stream)))))))) (defmethod accept-options2 ((frame gened) stream &key (orientation :horizontal)) (with-slots (default-filled default-filled-ink default-text-family default-text-face default-text-size ) frame (formatting-table (stream) (flet ((do-body (stream) (multiple-value-bind (real) (accept-it stream 'ink default-filled-ink "Ink" 'ink :orientation orientation) (setf default-filled-ink real) (multiple-value-bind (text-style) (accept-it stream 'p-text-style (list default-text-family default-text-face) "Text-Style" 'text-style :orientation orientation) (setf default-text-family (first text-style)) (setf default-text-face (second text-style)) (multiple-value-bind (text-size) (accept-it stream 'p-text-size default-text-size "Text-Size" 'text-size :orientation orientation :min-width 300) (setf default-text-size text-size) (multiple-value-bind (bool) (accept-it stream 'boolean default-filled "Filled" 'filled :orientation orientation) (setf default-filled bool))))))) (ecase orientation (:horizontal (formatting-row (stream) (do-body stream))) (:vertical (formatting-column (stream) (do-body stream)))))))) ;;; ;;; ;;; (defun get-symbol-list () (with-application-frame (gened-frame) (with-slots (calc-int-dim inc-mode) gened-frame (append (when *bounding-boxes* (list 'boxes)) (when *origins* (list 'origins)) (when *info* (list 'infos)) (when *pretty-hl* (list 'pretty)) (when calc-int-dim (list 'dimensions)) (when inc-mode (list 'incremental)) (when *classic-warnings* (list 'warnings)))))) (defun text-cell (stream format-string &key (orientation :center)) (formatting-cell (stream :align-x orientation) (write-string format-string stream) (write-string " " stream))) (defmethod accept-buttons ((frame gened) stream &key (orientation :vertical)) (with-slots (calc-int-dim inc-mode) frame (let ((last-symbol-list (get-symbol-list))) (formatting-table (stream :y-spacing '(1 :character)) (flet ((do-body (stream) (text-cell stream "Global Display Options:") (multiple-value-bind (symbol-list changed0p) (accept-it stream '(subset-completion (VISIBLE HIDDEN PRIMITIVE COMPOSITE)) *global-display-options* nil 'global-display-options :orientation orientation :view 'list-pane-view) (setf *global-display-options* symbol-list) (text-cell stream "Object Display Options:") (multiple-value-bind (symbol-list changed1p) (accept-it stream '(subset-completion (INTERIOR BORDER)) (list (if *global-border* 'BORDER) (if *global-filled* 'INTERIOR)) nil 'object-display-options :orientation orientation :view 'list-pane-view) (setf *global-filled* (and (member 'INTERIOR symbol-list) t) *global-border* (and (member 'BORDER symbol-list) t)) (text-cell stream "Object Handle Options:") (multiple-value-bind (symbol-list changed2p) (accept-it stream `(subset-completion (NORMAL FIXED UNFIXED START END)) *handles-symbol-list* nil 'handles :orientation orientation :view 'list-pane-view) (setf *handles-symbol-list* symbol-list) (text-cell stream "Global Display Scaling:") (multiple-value-bind (number changed3p) (accept-it stream `(completion (1/2 1 2)) *global-scaling* nil 'gs :view 'list-pane-view :orientation orientation) (setf *global-scaling* number) (text-cell stream "Concept Label Options:") (multiple-value-bind (symbol-list changed4p) (accept-it stream '(subset-completion (IDs PARENTS ANCESTORS)) *concept-labels* nil 'labels :view 'list-pane-view :orientation orientation) (setf *concept-labels* symbol-list) (text-cell stream "Others:") (multiple-value-bind (symbol-list changed5p) (accept-it stream '(subset-completion (Boxes Origins Pretty Infos Warnings Dimensions Incremental)) (get-symbol-list) nil 'others :orientation orientation :view 'list-pane-view) (setf *pretty-hl* (member 'pretty symbol-list)) (setf *bounding-boxes* (member 'boxes symbol-list)) (setf *origins* (member 'origins symbol-list)) (setf *info* (member 'infos symbol-list)) (setf *classic-warnings* (member 'warnings symbol-list)) (set-classic-infos *classic-warnings*) (setf calc-int-dim (member 'dimensions symbol-list)) (setf inc-mode (member 'incremental symbol-list)) (when (or changed0p changed1p changed2p changed3p changed4p changed5p) (when changed5p (when (or (and (member 'dimensions symbol-list) (not (member 'dimensions last-symbol-list))) (and (not (member 'dimensions symbol-list)) (member 'dimensions last-symbol-list))) (clear-hashtable) (do-incremental-updates)) (when (or (and (member 'incremental symbol-list) (not (member 'incremental last-symbol-list))) (and (not (member 'incremental symbol-list)) (member 'incremental last-symbol-list))) (when inc-mode (clear-knowledge-base) (do-incremental-updates)))) (if changed3p (progn (tick-all-objects) (do-incremental-updates)) (only-tick-all-objects))))))))))) (ecase orientation (:horizontal (formatting-row (stream) (do-body stream))) (:vertical (formatting-column (stream) (do-body stream))))))))) (defmethod accept-elements ((frame gened) stream &key &allow-other-keys) (with-slots (mode) frame (formatting-table (stream) (formatting-column (stream) (formatting-cell (stream :align-x :center) (let ((element (accept 'elements :stream stream :default mode :prompt "Element"))) (setf mode element))))))) ;;; ;;; ;;; (define-presentation-type line-thickness () :inherit-from `((completion (1 2 3 4)) :name-key identity :printer present-line-thickness :highlighter highlight-line-thickness)) (defun present-line-thickness (object stream &key acceptably) (declare (ignore acceptably)) (let ((y (stream-line-height stream))) (with-room-for-graphics (stream) (draw-rectangle* stream 0 2 26 (- y 2) :filled nil :ink +background-ink+) (draw-line* stream 0 (floor y 2) 26 (floor y 2) :line-thickness object)))) (defun highlight-line-thickness (continuation object stream) (surrounding-output-with-border (stream) (funcall continuation object stream))) ;;; ;;; ;;; (define-presentation-type line-style-type () :inherit-from `((completion (:solid :pattern1 :pattern2 :pattern3)) :name-key identity :printer present-line-style :highlighter highlight-line-style)) (defun decode-line-style (object) (second (assoc object +line-pattern-list+))) (defun encode-line-style (object) (first (rassoc (list object) +line-pattern-list+ :test #'equal))) (defun present-line-style (object stream &key acceptably) (declare (ignore acceptably)) (let ((y (stream-line-height stream))) (with-room-for-graphics (stream) (draw-rectangle* stream 0 2 22 (- y 2) :filled nil :ink +background-ink+) (draw-line* stream 0 (floor y 2) 22 (floor y 2) :line-dashes (decode-line-style object))))) (defun highlight-line-style (continuation object stream) (surrounding-output-with-border (stream) (funcall continuation object stream))) ;;; ;;; ;;; (define-presentation-type ink () :inherit-from '((completion (0.4 0.6 0.8 0.9)) :name-key identity :printer present-ink)) (defun present-ink (object stream &key acceptably) (declare (ignore acceptably)) (let ((y (stream-line-height stream))) (with-room-for-graphics (stream) (draw-rectangle* stream 0 2 16 (- y 2) :filled t :ink (make-gray-color object))))) ;;; ;;; ;;; (define-presentation-type p-text-style () :inherit-from `((completion ((:sans-serif :bold) (:serif :italic) (:sans-serif nil) (:fix :bold)) :test equalp) :name-key identity :printer present-text-style)) (defun present-text-style (object stream &key) (let ((text-style (parse-text-style (append object '(:small))))) (with-text-style (stream text-style) (draw-text* stream "ABC" 0 0 :ink +black+)))) (define-presentation-type p-text-size () :inherit-from '((completion (:tiny :very-small :normal :very-large :huge)) :name-key identity :printer present-text-size)) (defun present-text-size (object stream &key) (case object (:tiny (write-string "T" stream)) (:very-small (write-string "S" stream)) (:normal (write-string "N" stream)) (:very-large (write-string "L" stream)) (:huge (write-string "H" stream)))) ;;; ;;; ;;; (define-presentation-type elements () :inherit-from `((completion (g-concept g-circle g-rectangle g-arrow g-chain g-spline-chain g-polygon g-spline-polygon g-text g-point)) :name-key identity :printer present-elements :highlighter highlight-element)) (defun present-elements (object stream &key) (let ((*concept-labels* nil) (*handles-symbol-list* nil) (*bounding-boxes* nil) (*origins* nil)) (draw (second (assoc object *sample-graphic-objects*)) stream))) (defun highlight-element (continuation object stream) (surrounding-output-with-border (stream) (funcall continuation object stream))) ;;; ;;; ;;; (defmethod run-frame-top-level :before ((frame gened) &key) (initialize-gened frame)) (defmethod frame-standard-input ((frame gened)) (get-frame-pane frame 'command)) (defmethod frame-standard-output ((frame gened)) (get-frame-pane frame 'infos)) (defmethod initialize-gened ((frame gened)) (load-concepts) (load-label-object) (setf *current-file* "NONAME") (setf *global-scaling* 1) (setf *cl-error-msg-stream* (get-frame-pane frame 'infos)) (setf *cl-warn-msg-stream* (get-frame-pane frame 'infos)) (cl-set-classic-error-mode nil) (setf *classic-print-right-margin* 40)) (defun set-classic-infos (bool) (cl-set-classic-warn-mode bool)) (defmethod frame-error-output ((frame gened)) (get-frame-pane frame 'infos)) (defun clear-info-pane () (with-application-frame (gened-frame) (let ((stream (get-frame-pane gened-frame 'infos))) (window-clear stream)))) ;;; ;;; ;;; (defmethod draw-label ((frame gened) stream &key max-width max-height) (declare (ignore max-width max-height)) (updating-output (stream :unique-id *current-file* :cache-value *current-file*) (multiple-value-bind (x y) (window-inside-size stream) (with-translation (stream (+ 4 (/ x 2)) (+ 12 (/ y 2))) (let ((*origins* nil) (*concept-labels* nil) (*bounding-boxes* nil) (*pretty-hl* nil) (*global-border* t) (*global-filled* t) (*global-scaling* 1) (name (let ((num (position #\/ *current-file* :from-end t))) (subseq *current-file* (if num (1+ num) 0) (length *current-file*))))) (draw *label-shadow-object* stream) (draw *label-object* stream) (format stream "File: ~A" name)))))) ;;; ;;; ;;; (define-gesture-name :move :pointer-button (:left)) (define-gesture-name :create :pointer-button (:left :shift)) (define-gesture-name :delete :pointer-button (:middle :shift)) (define-gesture-name :inspect :pointer-button (:left :meta)) (define-gesture-name :classic-inspect :pointer-button (:right :meta)) (define-gesture-name :copy :pointer-button (:middle :control)) (define-gesture-name :scale :pointer-button (:right :shift)) (define-gesture-name :rotate :pointer-button (:left :control)) (define-gesture-name :atomize :pointer-button (:left :control)) (define-gesture-name :fix/free :pointer-button (:middle)) ;;; ----------------------------- (defparameter *gened-text-style* (make-text-style :sans-serif :roman :normal )) (defvar *gened-frame*) (defun gened (&key (force t) (process t) (left nil) top width height &allow-other-keys) (let ((port (find-port))) (setf (clim:text-style-mapping port *gened-text-style*) "-*-lucida-medium-r-normal-*-12-*-*-*-*-*-*-*") (when (or force (null *gened-frame*)) (unless left (multiple-value-bind (screen-width screen-height) (bounding-rectangle-size (sheet-region (find-graft :port port))) (setf left 0 top 0 width screen-width height screen-height))) (setf *gened-frame* (make-application-frame 'gened :left (+ 10 left) :top (+ 10 top) :width (- width 10) :height (- height 10))) #+:Allegro (if process (mp:process-run-function "Model Browser" #'(lambda () (run-frame-top-level *gened-frame*))) (run-frame-top-level *gened-frame*)) #-:Allegro (run-frame-top-level *gened-frame*) *gened-frame*)))
19,438
Common Lisp
.lisp
556
28.311151
88
0.650807
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
1b3f763c3203f2d3678dd6681d689cea0b943fb5b804fa70fe66d2adf2762ace
11,176
[ -1 ]
11,177
interface-to-classic.lisp
lambdamikel_GenEd/src/interface-to-classic.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; Error-Hook-Fn. ;;; (defun inconsistent-classic-object (code args path object) (if (and (cl-instance? object (cl-named-concept 'gened-thing)) (listp (cl-fillers object (cl-named-role 'belongs-to-clos-object)))) (let ((id (first (cl-fillers object (cl-named-role 'belongs-to-clos-object))))) (find-object id)))) ;;; ;;; (defun add-information (object slot delta) #| (print 'add) (print slot) (print delta) |# (when delta (if (listp delta) (insert-fillers-for-slotname object slot delta) (insert-fillers-for-slotname object slot (list delta))))) (defun remove-information (object slot delta) #| (print 'remove) (print slot) (print delta) |# (when delta (if (listp delta) (remove-fillers-for-slotname object slot delta) (remove-fillers-for-slotname object slot (list delta))))) (defmethod name-for ((object thing)) (concatenate 'string (generate-name (first (parent-concepts object))) "-" (write-to-string (id-number object)))) (defun create-classic-ind-for (object) (when *info* (format t "Creating Classic Individual for Object ~A.~%" object)) (let ((symbol (intern (name-for object)))) (cl-create-ind symbol `(and ,@(parent-concepts object))) (cl-ind-add (cl-named-ind symbol) `(fills belongs-to-clos-object ,(id-number object))) (setf (associated-classic-ind object) symbol))) (defmethod create-classic-ind ((object thing)) (create-classic-ind-for object)) (defun create-info-classic-inds (object) (create-classic-ind-for object) (create-classic-ind-for (start-info-point object)) (create-classic-ind-for (end-info-point object))) (defmethod create-classic-ind ((object g-arrow)) (create-info-classic-inds object)) (defmethod create-classic-ind ((object g-chain)) (create-info-classic-inds object)) (defmethod create-classic-ind ((object g-spline-chain)) (create-info-classic-inds object)) (defmethod create-classic-ind ((object composite-thing)) (create-classic-ind-for object) (dolist (part (liste object)) (create-classic-ind part))) ;;; (defmethod fill-all-roles ((object thing)) (dolist (slot (all-slots object)) (let ((cont (funcall slot object))) (if cont (add-information object slot cont)))) (when (typep object 'directed-info-element) (fill-all-roles (start-info-point object)) (fill-all-roles (end-info-point object)))) (defmethod remove-all-roles ((object thing)) (dolist (slot (all-slots object)) (print slot) (let ((cont (funcall slot object))) (if cont (remove-information object slot cont)))) (when (typep object 'directed-info-element) (remove-all-roles (start-info-point object)) (remove-all-roles (end-info-point object)))) ;;; ;;; (defmethod delete-classic-ind ((object thing)) ()) ;;; ;;; ;;; (defun get-accessor-function (role-symbol) (case role-symbol (has-parts 'liste) (has-startpoint 'start-info-point) (has-endpoint 'end-info-point) (filled-bool 'filledp) (radius-real 'radius) (covered-by-object 'covered-by-objects) (otherwise role-symbol))) (defun get-role-from-accessor (accessor-symbol) (case accessor-symbol (liste 'has-parts) (start-info-point 'has-startpoint) (end-info-point 'has-endpoint) (filledp 'filled-bool) (radius 'radius-real) (covered-by-objects 'covered-by-object) (otherwise accessor-symbol))) ;;; ;;; ;;; (defmethod points-related-with ((object directed-info-element)) (append (startpoint-related-with object) (endpoint-related-with object))) (defun insert-filler-from-rolename (object role-symbol) (let ((object-classic-ind (get-classic-ind object))) (dolist (rel-object (let ((objects (funcall (get-accessor-function role-symbol) object))) (unless (null objects) (if (atom objects) (list objects) objects)))) (let ((classic-ind (if (typep rel-object 'thing) (associated-classic-ind rel-object) rel-object))) (cl-ind-add object-classic-ind `(fills ,role-symbol ,classic-ind)))))) (defun insert-fillers-for-slotname (object slot-name fillers-to-add) (let ((object-classic-ind (get-classic-ind object)) (role-symbol (get-role-from-accessor slot-name))) (let ((fillers (mapcar #'(lambda (object) (cl-ind-name (get-classic-ind object))) fillers-to-add))) (dolist (elem fillers) (cl-ind-add object-classic-ind `(fills ,role-symbol ,elem)))))) (defun remove-all-fillers-for-slotname (object slot-name) (let* ((object-classic-ind (get-classic-ind object)) (role-symbol (get-role-from-accessor slot-name)) (role (cl-named-role role-symbol)) (inv-role (cl-role-inverse role)) (inv-role-symbol (cl-role-name inv-role))) (let* ((all-fillers (cl-fillers object-classic-ind role)) (all-filler-names (mapcar #'cl-name all-fillers)) (told-fillers (cl-told-fillers (cl-told-ind object-classic-ind) role)) (told-filler-names (mapcar #'cl-told-ind-name told-fillers)) (derived-filler-names (set-difference all-filler-names told-filler-names))) (when (cl-ind-closed-role? object-classic-ind role) (cl-ind-unclose-role object-classic-ind role)) (if told-filler-names (cl-ind-remove object-classic-ind `(fills ,role-symbol ,@told-filler-names))) (if (and inv-role-symbol derived-filler-names) (let ((object-name (cl-name object-classic-ind))) (dolist (name derived-filler-names) (let ((inverse-ind (cl-named-ind name))) (cl-ind-remove inverse-ind `(fills ,inv-role-symbol ,object-name))))))))) (defun remove-fillers-for-slotname (object slot-name fillers-to-remove) (let* ((object-classic-ind (get-classic-ind object)) (role-symbol (get-role-from-accessor slot-name)) (role (cl-named-role role-symbol)) (inv-role (cl-role-inverse role)) (inv-role-symbol (cl-role-name inv-role))) (let* ((all-fillers (cl-fillers object-classic-ind role)) (all-filler-names (mapcar #'cl-name all-fillers)) (fillers-to-remove-names (mapcar #'(lambda (x) (cl-name (associated-classic-ind x))) fillers-to-remove)) (told-fillers (cl-told-fillers (cl-told-ind object-classic-ind) role)) (told-filler-names (mapcar #'cl-told-ind-name told-fillers)) (derived-filler-names (set-difference all-filler-names told-filler-names)) (remove-told-filler-names (intersection fillers-to-remove-names told-filler-names)) (remove-derived-filler-names (intersection fillers-to-remove-names derived-filler-names))) (when (cl-ind-closed-role? object-classic-ind role) (cl-ind-unclose-role object-classic-ind role)) (if remove-told-filler-names (cl-ind-remove object-classic-ind `(fills ,role-symbol ,@remove-told-filler-names))) (if (and inv-role-symbol remove-derived-filler-names) (let ((object-name (cl-name object-classic-ind))) (dolist (name remove-derived-filler-names) (let ((inverse-ind (cl-named-ind name))) (cl-ind-remove inverse-ind `(fills ,inv-role-symbol ,object-name))))))))) (defmethod get-classic-ind ((object thing)) (cl-named-ind (associated-classic-ind object))) (defun insert-all-fillers (object) (dolist (role (set-difference (first +known-roles+) '(linked-over-with start-linked-over-with end-linked-over-with points-related-with startpoint-related-with endpoint-related-with linker-objects start-linker-objects end-linker-objects ))) (let ((fn (get-accessor-function role))) (when (slot-exists-p object fn) (insert-filler-from-rolename object role))))) (defun insert-spatial-fillers () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (object liste) (when *info* (format t "Inserting Fillers for Object ~A.~%" object)) (let ((classic-ind (get-classic-ind object))) (insert-all-fillers object) (dolist (elem (start-linked-over-with object)) (let* ((linker (second elem)) (linker-ind (associated-classic-ind linker)) (rel-object (first elem)) (rel-classic-ind (associated-classic-ind rel-object))) (if (head linker) (progn (cl-ind-add classic-ind `(fills start-linked-over-with ,rel-classic-ind)) (cl-ind-add classic-ind `(fills end-linker-objects ,linker-ind))) (progn (cl-ind-add classic-ind `(fills linked-over-with ,rel-classic-ind)) (cl-ind-add classic-ind `(fills linker-objects ,linker-ind)))))) (dolist (elem (end-linked-over-with object)) (let* ((linker (second elem)) (linker-ind (associated-classic-ind linker)) (rel-object (first elem)) (rel-classic-ind (associated-classic-ind rel-object))) (if (head linker) (progn (cl-ind-add classic-ind `(fills end-linked-over-with ,rel-classic-ind)) (cl-ind-add classic-ind `(fills start-linker-objects ,linker-ind))) (progn (cl-ind-add classic-ind `(fills linked-over-with ,rel-classic-ind)) (cl-ind-add classic-ind `(fills linker-objects ,linker-ind)))))) (when (typep object 'directed-info-element) (if (head object) (progn (insert-filler-from-rolename object 'startpoint-related-with) (insert-filler-from-rolename object 'endpoint-related-with)) (insert-filler-from-rolename object 'points-related-with)))))))) (defmethod get-associated-classic-ind ((object thing)) (cl-named-ind (associated-classic-ind object))) ;;; ;;; ;;; (define-gened-command (com-gened-create-classic-inds) () (with-application-frame (gened-frame) (let ((stream (get-frame-pane gened-frame 'infos))) (window-clear stream) (with-slots (liste) gened-frame (dolist (elem liste) (create-classic-ind elem)) (dolist (elem liste) (fill-all-roles elem)))))) (define-gened-command (com-print-ind) ((object '(or thing object-handle) :gesture :classic-inspect)) (terpri) (terpri) (if (typep object 'thing) (cl-print-object (get-associated-classic-ind object)) (if (and (or (typep object 'start-handle) (typep object 'end-handle)) (typep (parent-object object) 'directed-info-element)) (cl-print-object (get-associated-classic-ind (if (typep object 'start-handle) (start-info-point (parent-object object)) (end-info-point (parent-object object)))))))) ;;; ;;; ;;; (defun close-role (object role-symbol) (let ((classic-ind (get-associated-classic-ind object)) (role (cl-named-role role-symbol))) (cl-ind-close-role classic-ind role))) (defun close-all-roles-for-object (object role-set) (dolist (role-sym role-set) (close-role object role-sym))) (defun close-all-roles () (when *info* (format t "Closing Roles for Objects...~%")) (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (role-set +known-roles+) (dolist (object liste) (close-all-roles-for-object object role-set)))))) ;;; ;;; ;;; (defun unclose-role-if-neccessary (object role-symbol) (let ((classic-ind (get-associated-classic-ind object)) (role (cl-named-role role-symbol))) (when (cl-ind-closed-role? classic-ind role) (cl-ind-unclose-role classic-ind role)))) (defun unclose-all-roles-if-neccessary () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (object liste) (mapc #'(lambda (role-set) (mapc #'(lambda (rol-sym) (unclose-role-if-neccessary object rol-sym)) role-set)) +known-roles+))))) ;;; ;;; ;;; (define-gened-command (com-gened-classify) () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (let ((stream (get-frame-pane gened-frame 'infos))) (window-clear stream) (setf liste (install-points liste)) (atomize-all-clusters) (unclose-all-roles-if-neccessary) (reinstall-all-clusters) (unclose-all-roles-if-neccessary) (insert-spatial-fillers) (close-all-roles) (update-parent-concepts) (setf liste (remove-points liste)) (redraw))))) #| (defun update-parent-concepts () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (object liste) (remove-all-but-basic-concept object) (let ((classic-ind (get-associated-classic-ind object))) (dolist (concept +known-concepts+) (when (cl-instance? classic-ind (cl-named-concept concept)) (push-concept object concept)))))))) |# (defun update-parent-concepts () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (object liste) (remove-all-but-basic-concept object) (let* ((classic-ind (get-associated-classic-ind object)) (parents (mapcar #'cl-name (cl-ind-parents classic-ind))) (ancestors (mapcar #'cl-name (cl-ind-ancestors classic-ind))) (p-concepts (reverse (intersection +known-concepts+ parents))) (a-concepts (reverse (intersection +known-concepts+ ancestors)))) (mapc #'(lambda (parent ancestor) (push-concept object parent) (push-concept object ancestor :ancestor t)) p-concepts a-concepts)))))) (define-gened-command (com-gened-clear-kb) () (cl-clear-kb)) (define-gened-command (com-gened-revert-all-to-bottom :name "Revert All To Bottom Concept") () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (setf liste (install-points liste)) (dolist (object liste) (remove-all-but-basic-concept object)) (setf liste (remove-points liste)))) (redraw))
14,275
Common Lisp
.lisp
440
27.125
91
0.668809
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
1e0ee32fe17b0088b91d3f06773d948adc9bed9a5ea2b674c38bb7dc58560d8c
11,177
[ -1 ]
11,178
kb-display.lisp
lambdamikel_GenEd/src/kb-display.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: KNOWLEDGE; Base: 10 -*- (cl:in-package knowledge) (defparameter *browser-text-style* (make-text-style :sans-serif :roman :normal)) (defparameter *list-pane-text-style* (make-text-style :serif :roman :small)) (defparameter *relation-text-style* (make-text-style :serif :roman :small)) (defparameter *command-listener-text-style* (make-text-style :sans-serif :roman :normal)) (define-application-frame browser () ((described-concept :initform nil :accessor browser-described-concept) (current-concepts :initform nil :initarg :roots :accessor browser-current-concepts) (show-super-concepts-p :initform nil :accessor browser-show-super-concepts-p)) (:command-definer t) (:command-table (browser)) (:panes (concept-hierarchy-display-pane :application :incremental-redisplay t :display-function 'draw-concept-hierarchy :label "Concept Hierarchy" :scroll-bars ':both :end-of-page-action ':allow :end-of-line-action ':allow) (concept-info-pane :application :incremental-redisplay t #+allegro :excl-recording-p #+allegro t :display-function 'draw-concept-description :label "Concept Info" :text-style *command-listener-text-style* :scroll-bars ':both :end-of-page-action ':allow :end-of-line-action ':allow) (listener-pane :interactor :label nil :text-style *command-listener-text-style* :scroll-bars ':both :min-height '(4 :line) :max-height '(4 :line) :height '(4 :line)) (pointer-documentation-pane (make-clim-stream-pane :type 'pointer-documentation-pane :foreground +white+ :background +black+ :text-style (make-text-style :sans-serif :bold :small) :scroll-bars nil :min-height '(1 :line) :max-height '(1 :line) :height '(1 :line)))) (:layouts (default (vertically () (horizontally () (2/3 concept-hierarchy-display-pane) (1/3 concept-info-pane)) listener-pane pointer-documentation-pane)))) (defmethod frame-standard-output ((frame browser)) (get-frame-pane frame 'listener-pane)) (defmethod frame-standard-input ((frame browser)) (get-frame-pane frame 'listener-pane)) (define-border-type :ellipse (stream record left top right bottom) (let ((width/2 (floor (- right left) 2)) (height/2 (floor (- bottom top) 2))) (draw-ellipse* stream (+ left width/2) (+ top height/2) (+ width/2 3) 10 10 (+ height/2 7) :filled nil))) ;;; ---------------------------------------------------------------------- (define-presentation-type concept ()) (define-presentation-method presentation-typep ((object t) (type concept)) (classic:cl-named-concept (classic:cl-name object))) (define-presentation-method present (object (type concept) stream (view textual-view) &key) (format stream "~S" (classic:cl-name object))) (define-presentation-method accept ((type concept) stream (view textual-view) &key) (completing-from-suggestions (stream) (dolist (concept (classic:cl-concept-descendants (classic:cl-named-concept 'classic:thing))) (suggest (format nil "~S" (classic:cl-name concept)) concept)))) (defun print-concept-node (concept-node stream) (with-output-as-presentation (stream concept-node 'concept :single-box t) (surrounding-output-with-border (stream :shape :ellipse) (format stream "~S" (classic:cl-name concept-node))))) (defun draw-concept-graph-arc-superconcept (stream from-node to-node x1 y1 x2 y2 &rest drawing-options &key path) (declare (ignore from-node to-node drawing-options)) (if (null path) (draw-arrow* stream x2 y2 x1 y1) (let ((x3 (first path)) (y3 (second path))) (draw-arrow* stream x3 y3 x1 y1) (draw-polygon* stream (append path (list x2 y2)) :filled nil :closed nil)))) (defun draw-concept-graph-arc-subconcept (stream from-node to-node x1 y1 x2 y2 &rest drawing-options &key path) (declare (ignore from-node to-node drawing-options)) (if (null path) (draw-arrow* stream x1 y1 x2 y2) (let ((x3 (first path)) (y3 (second path))) (draw-arrow* stream x1 y1 x3 y3) (draw-polygon* stream (append path (list x2 y2)) :filled nil :closed nil)))) (defun filter-concept-parents (concept) (classic:cl-concept-parents concept)) (defun filter-concept-children (concept) (classic:cl-concept-children concept)) (defmethod draw-concept-hierarchy ((frame browser) stream &key) (let ((current-concepts (browser-current-concepts frame))) (when current-concepts (updating-output (stream :unique-id 'concept-hierarchy :cache-test #'equal :cache-value current-concepts) (stream-set-cursor-position stream 10 10) (if (browser-show-super-concepts-p frame) (format-graph-from-roots current-concepts 'print-concept-node 'filter-concept-parents :graph-type :dag :generation-separation 30 :arc-drawer 'draw-concept-graph-arc-superconcept :stream stream :orientation ':vertical :merge-duplicates t) (format-graph-from-roots current-concepts 'print-concept-node 'filter-concept-children :graph-type :dag :generation-separation 30 :arc-drawer 'draw-concept-graph-arc-subconcept :stream stream :orientation ':horizontal :merge-duplicates t)))))) (defmethod draw-concept-description ((frame browser) stream &key) (let ((concept (browser-described-concept frame))) (updating-output (stream :unique-id 'concept-info :cache-value concept) (when concept (let ((*standard-output* stream)) (classic:cl-print-object concept)))))) ;;; ---------------------------------------------------------------------- (define-browser-command (com-quit-browser :name t :menu "Quit") () (with-application-frame (browser-frame) (frame-exit browser-frame))) (define-browser-command (com-clear-output-history :name t :menu nil) () (with-application-frame (browser-frame) (window-clear (get-frame-pane browser-frame 'listener-pane)))) (define-browser-command (com-show-concept-descendants :name t :menu nil) ((concept '(or concept expression))) (with-application-frame (browser-frame) (window-set-viewport-position (get-frame-pane browser-frame 'concept-hierarchy-display-pane) 0 0) (setf (browser-show-super-concepts-p browser-frame) nil) (setf (browser-current-concepts browser-frame) (list concept)))) (define-presentation-to-command-translator show-concept-descendants-translator (concept com-show-concept-descendants browser) (object) (list object)) (define-browser-command (com-show-concept-ancestors :name t :menu nil) ((concept '(or concept expression))) (with-application-frame (browser-frame) (window-set-viewport-position (get-frame-pane browser-frame 'concept-hierarchy-display-pane) 0 0) (setf (browser-show-super-concepts-p browser-frame) t) (setf (browser-current-concepts browser-frame) (list concept)))) (define-gesture-name :select-super :pointer-button (:left :shift)) (define-presentation-to-command-translator show-concept-ancestors-translator (concept com-show-concept-ancestors browser :gesture :select-super) (object) (list object)) (define-browser-command (com-show-concept-info :name t :menu nil) ((concept '(or concept expression))) (with-application-frame (browser-frame) (setf (browser-described-concept browser-frame) concept))) (define-presentation-to-command-translator show-concept-info-translator ((or concept expression) com-show-concept-info browser :gesture :describe :tester ((object) (setf *x* object) (classic:cl-concept? object))) (object) (list object)) ;;; ---------------------------------------------------------------------- (defvar *browser-frame*) (defun browser (&key (force t) (process t) (left nil) top width height (roots (list (cl-named-concept 'classic:classic-thing))) &allow-other-keys) (let ((port (find-port))) (setf (clim:text-style-mapping port *browser-text-style*) "-*-lucida-medium-r-normal-*-12-*-*-*-*-*-*-*") (when (or force (null *browser-frame*)) (unless left (multiple-value-bind (screen-width screen-height) (bounding-rectangle-size (sheet-region (find-graft :port port))) (setf left 0 top 0 width screen-width height screen-height))) (setf *browser-frame* (make-application-frame 'browser :roots roots :left (+ 10 left) :top (+ 10 top) :width (- width 50) :height (- height 50))) #+:Allegro (if process (mp:process-run-function "Model Browser" #'(lambda () (run-frame-top-level *browser-frame*))) (run-frame-top-level *browser-frame*)) #-:Allegro (run-frame-top-level *browser-frame*) *browser-frame*)))
9,301
Common Lisp
.lisp
267
29.273408
86
0.660686
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
d250901b7d1754dabd5a310c5da7cd1e9550875d4f7ad177390a8451e100468e
11,178
[ -1 ]
11,179
classes.lisp
lambdamikel_GenEd/src/classes.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; Klassendefinitionen ;;; (defclass undo-object () ((object-copy :initarg :object-copy :accessor object-copy) (original-object :initarg :original-object :accessor original-object) (operation :initarg :operation :accessor operation))) ;;; (defclass object-handle () ((x :accessor x :initarg :x) (y :accessor y :initarg :y) (parent-object :accessor parent-object :initarg :parent-object))) (defclass start-handle (object-handle) ()) (defclass end-handle (object-handle) ()) (defclass unfixed-object-handle (object-handle) ()) (defclass fixed-object-handle (object-handle) ((fixed-at-object :accessor fixed-at-object :initform nil))) (defclass unfixed-start-handle (unfixed-object-handle start-handle) ()) (defclass unfixed-end-handle (unfixed-object-handle end-handle) ()) (defclass fixed-start-handle (fixed-object-handle start-handle) ()) (defclass fixed-end-handle (fixed-object-handle end-handle) ()) ;;; ;;; ;;; (defclass linestyle-mixin () ((linestyle :initform nil :initarg :linestyle :accessor linestyle))) (defclass ink-mixin () ((ink :initform 0.0 :initarg :ink :accessor ink))) (defclass linethickness-mixin () ((linethickness :initform 1 :initarg :linethickness :accessor linethickness))) (defclass filled-mixin () ((filledp :initform nil :initarg :filledp :accessor filledp) (filled-ink :initform 0.0 :initarg :filled-ink :accessor filled-ink))) (defclass sit-mixin (linestyle-mixin ink-mixin linethickness-mixin) ()) ;;; ;;; ;;; (defclass thing () ( (attached-handles :initform nil :accessor attached-handles) (tickval :initform 0 :accessor tickval) (associated-classic-ind :initform nil :accessor associated-classic-ind) (initialize :initform nil :initarg :initialize :accessor initialize) ; t, wenn initialize-instance taetig werden darf (xtrans :initform 0 :accessor xtrans :initarg :xtrans) ; rel. zum Screen-Origin (ytrans :initform 0 :accessor ytrans :initarg :ytrans) ; xytrans ist immer Mittelpunkt der bounding-box (parent-concepts :initform nil :accessor parent-concepts :initarg :parent-concepts) (ancestor-concepts :initform nil :accessor ancestor-concepts) (part-of-cluster :initarg :part-of-cluster :initform nil :accessor part-of-cluster) (disjoint-with :initform nil :accessor disjoint-with) (start-linked-over-with :initform nil :accessor start-linked-over-with) ; Listen : (elem linker) (end-linked-over-with :initform nil :accessor end-linked-over-with) (in-relation-with-objects :initform nil :accessor in-relation-with-objects) (intersects-objects :initform nil :accessor intersects-objects) (intersects-0-objects :initform nil :accessor intersects-0-objects) (intersects-1-objects :initform nil :accessor intersects-1-objects) (intersects-2-objects :initform nil :accessor intersects-2-objects) (touching-objects :initform nil :accessor touching-objects) (contained-in-objects :initform nil :accessor contained-in-objects) (covered-by-objects :initform nil :accessor covered-by-objects) (directly-contained-by-object :initform nil :accessor directly-contained-by-object) (hidden :initform nil :accessor hiddenp :initarg :hiddenp) (output-record :accessor output-record) (id-number :accessor id-number :initform 0) (highlighted :initform nil :accessor highlightedp) (br-left :accessor br-left) (br-right :accessor br-right) (br-top :accessor br-top) (br-bottom :accessor br-bottom) )) (defclass basic-thing (thing) ( (polygonized-representation :initform nil :accessor polygonized-representation))) ;;; ;;; ;;; (defclass rotateable-thing () ; es gibt 2D-Objekte, die nicht rotierbar sind (g-circle) ((rotangle :initform 0 :accessor rotangle))) (defclass scaleable-thing () ; auch 1D-Objekte koennen scalierbar sein, wenn sie nicht flach sind ((xscale :initform 1.0 :accessor xscale :initarg :xscale) (yscale :initform 1.0 :accessor yscale :initarg :yscale) (init-x-extend :accessor init-x-extend) (init-y-extend :accessor init-y-extend))) (defclass scale-and-rotateable-thing (scaleable-thing rotateable-thing) ()) ;;; ;;; ;;; (defclass object-with-handles () ((handles :accessor handles :initarg :handles :initform nil) (initialize-handles :accessor initialize-handles :initform nil :initarg :initialize-handles))) (defclass pointlist-object () ((pointlist :initform nil :initarg :pointlist :accessor pointlist))) (defclass spline-object () ((spline-points :initform nil :accessor spline-points))) (defclass object-with-head () ((head :initform t :initarg :head :accessor head))) (defclass linesegment () ((startpoint :initform '(-10 -10) :initarg :startpoint :accessor startpoint) (endpoint :initform '(10 10) :initarg :endpoint :accessor endpoint))) (defclass directed-info-element () ( (startpoint-related-with :initform nil :initarg :startpoint-related-with :accessor startpoint-related-with) (endpoint-related-with :initform nil :initarg :endpoint-related-with :accessor endpoint-related-with) (start-info-point :initform nil :initarg :start-info-point :accessor start-info-point) (end-info-point :initform nil :initarg :end-info-point :accessor end-info-point))) ;;; ;;; ;;; (defclass 2d () ( (contains-objects :initform nil :accessor contains-objects) (directly-contains-objects :initform nil :accessor directly-contains-objects) (covers-objects :initform nil :accessor covers-objects))) (defclass 1d () ()) (defclass 0d () ()) ;;; ;;; ;;; (defclass composite-thing (thing 2d) ( (liste :initform nil :accessor liste :initarg :liste))) ;;; ;;; ;;; (defclass g-point (basic-thing 0d linethickness-mixin ink-mixin) ()) (defclass info-point (basic-thing 0d) ((part-of :initform nil :initarg :part-of :accessor part-of))) (defclass g-circle (basic-thing 2d scaleable-thing sit-mixin filled-mixin) ((radius :initform 0 :accessor radius :initarg :radius))) (defclass g-rectangle (basic-thing 2d scale-and-rotateable-thing sit-mixin filled-mixin) ((xextend :initform 10 :accessor xextend :initarg :xextend) (yextend :initform 10 :accessor yextend :initarg :yextend))) (defclass g-text (basic-thing 2d ink-mixin) ((text-string :initform "Text" :accessor text-string :initarg :text-string) (face :initform :bold :initarg :face :accessor face) (size :initform :large :initarg :size :accessor size) (family :initform :sans-serif :initarg :family :accessor family))) (defclass g-polygon (basic-thing 2d scale-and-rotateable-thing object-with-handles pointlist-object sit-mixin filled-mixin) ()) (defclass g-arrow (basic-thing 1d scale-and-rotateable-thing object-with-handles linesegment object-with-head sit-mixin directed-info-element) ()) (defclass g-chain (basic-thing 1d scale-and-rotateable-thing pointlist-object object-with-handles object-with-head sit-mixin directed-info-element) ()) (defclass g-spline-chain (basic-thing spline-object 1d scale-and-rotateable-thing pointlist-object object-with-handles object-with-head sit-mixin directed-info-element) ()) (defclass g-spline-polygon (basic-thing spline-object 2d scale-and-rotateable-thing pointlist-object object-with-handles sit-mixin filled-mixin) ()) ;;; ;;; ;;; (defmethod startpoint ((object pointlist-object)) (list (first (pointlist object)) (second (pointlist object)))) (defmethod endpoint ((object pointlist-object)) (last (pointlist object) 2)) ;;; ;;; ;;; (defmethod print-object ((object thing) stream) (format stream "~A = ~D" (first (parent-concepts object)) (id-number object))) (define-presentation-method present (object (type thing) stream (view textual-view) &key) (print-object object stream)) (define-presentation-method accept ((type thing) stream (view textual-view) &key) (with-application-frame (gened-frame) (with-slots (liste) gened-frame (completing-from-suggestions (stream) (dolist (elem liste) (suggest (print-object elem) elem)))))) ;;; ;;; ;;; (defun strange-polygon (object) (let ((pointlist (generate-brackets (pointlist object)))) (some #'(lambda (co1 co2 co3) (let* ((x1 (first co1)) (y1 (second co1)) (x2 (first co2)) (y2 (second co2)) (x3 (first co3)) (y3 (second co3))) (multiple-value-bind (d1 phi1) (distance-and-orientation x1 y1 x2 y2) (multiple-value-bind (d2 phi2) (distance-and-orientation x2 y2 x3 y3) (zerop (- (+ phi1 phi2) pi)))))) pointlist (cdr pointlist) (cddr pointlist)))) (defmethod strange-polygon-p ((object thing)) nil) (defmethod strange-polygon-p ((object g-polygon)) (strange-polygon object)) (defmethod strange-polygon-p ((object g-spline-polygon)) (strange-polygon object)) ;;; ;;; ;;; (defmethod self-intersecting-p ((object t)) nil) (defmethod self-intersecting-p ((object pointlist-object)) (let* ((pointlist (let ((brackets (generate-brackets (pointlist object)))) (cons (first (last brackets)) brackets))) (lines (mapcar #'(lambda (point1 point2) (let* ((p1 (make-geom-point (first point1) (second point1))) (p2 (make-geom-point (first point2) (second point2)))) (make-geom-line p1 p2))) pointlist (cdr pointlist)))) (some #'(lambda (succ l1 pred) (let* ((lines (remove l1 lines :test #'equal)) (lines (remove succ lines :test #'equal)) (lines (remove pred lines :test #'equal))) (some #'(lambda (l2) (intersects l1 l2)) lines))) lines (cdr lines) (cddr lines) ))) ;;; ;;; ;;; (defmethod init-object-properties ((object t)) ()) (defmethod init-object-properties ((object basic-thing)) (get-bounding-rect object) (make-poly-representation object) (call-next-method)) (defmethod init-object-properties ((object composite-thing)) (multiple-value-bind (x y) (get-bounding-rect-center object) (multiple-value-bind (x y) (scale-mouse-position x y :inverse t) (setf (xtrans object) x (ytrans object) y))) (call-next-method)) (defmethod init-object-properties ((object scaleable-thing)) (let ((*global-scaling* 1)) (multiple-value-bind (xf yf xt yt) (get-bounding-rect object) (setf (init-x-extend object) (- xt xf) (init-y-extend object) (- yt yf)))) (call-next-method)) (defmethod init-object-properties ((object linesegment)) (make-object-handles object (list (startpoint object) (endpoint object))) (call-next-method)) (defmethod init-object-properties ((object pointlist-object)) (unless (handles object) (make-object-handles object (generate-brackets (pointlist object) ))) (call-next-method)) (defmethod init-object-properties ((object g-spline-chain)) (setf (spline-points object) (mapcan #'identity (filter-to-close-together-out (reverse (make-spline (make-spline-chain-list (generate-brackets (pointlist object) )) 4)) 3.0))) (call-next-method)) (defmethod init-object-properties ((object g-spline-polygon)) (setf (spline-points object) (mapcan #'identity (filter-to-close-together-out (reverse (make-spline (make-spline-polygon-list (generate-brackets (pointlist object))) 4)) 3.0))) (call-next-method)) ;;; ;;; ;;; (defmethod initialize-instance :after ((object thing) &key) (when (initialize object) (with-application-frame (gened-frame) (unless (parent-concepts object) (setf (parent-concepts object) (list (type-of object)))) (setf (id-number object) (get-id-number))))) (defmethod initialize-instance :after ((object object-with-head) &key) (when (initialize object) (with-application-frame (gened-frame) (with-slots (default-arrow-head) gened-frame (setf (head object) default-arrow-head) (setf (parent-concepts object) (case (type-of object) (g-arrow (if (head object) '(g-arrow) '(g-line))) (g-chain (if (head object) '(g-directed-chain) '(g-chain))) (g-spline-chain (if (head object) '(g-directed-spline-chain) '(g-spline-chain))))))))) ;;; ;;; (defmethod initialize-instance :after ((object ink-mixin) &key) (when (initialize object) (with-application-frame (gened-frame) (with-slots (default-ink) gened-frame (setf (ink object) default-ink))))) (defmethod initialize-instance :after ((object filled-mixin) &key) (when (initialize object) (with-application-frame (gened-frame) (with-slots (default-filled default-filled-ink) gened-frame (setf (filledp object) default-filled) (setf (filled-ink object) default-filled-ink))))) (defmethod initialize-instance :after ((object linestyle-mixin) &key) (when (initialize object) (with-application-frame (gened-frame) (with-slots (default-line-style) gened-frame (setf (linestyle object) (decode-line-style object)))))) (defmethod initialize-instance :after ((object linethickness-mixin) &key) (when (initialize object) (with-application-frame (gened-frame) (with-slots (default-line-thickness) gened-frame (setf (linethickness object) default-line-thickness))))) ;;; ;;; (defmethod initialize-instance :after ((object g-text) &key) (if (initialize object) (with-application-frame (gened-frame) (with-slots (default-text-family default-text-face default-text-size) gened-frame (setf (family object) default-text-family) (setf (face object) default-text-face) (setf (size object) default-text-size))))) (defmethod initialize-instance :after ((object linesegment) &key) (if (initialize-handles object) (make-object-handles object (list (startpoint object) (endpoint object))))) (defmethod initialize-instance :after ((object pointlist-object) &key) (if (initialize-handles object) (make-object-handles object (generate-brackets (pointlist object)))))
14,414
Common Lisp
.lisp
386
32.880829
109
0.705422
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
dffc0943286e3a3edfbebd6c51311e1eecea7603c86e42966c064c3b5aaf101d
11,179
[ -1 ]
11,180
undo.lisp
lambdamikel_GenEd/src/undo.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defclass undo-object () ((object-copy :initarg :object-copy :accessor object-copy) (original-object :initarg :original-object :accessor original-object) (operation :initarg :operation :accessor operation))) ;;; ;;; ;;; (defun init-undo-buffer () (with-application-frame (gened-frame) (with-slots (object-copy-buffer buffer-counter) gened-frame (setf buffer-counter 0) (setf object-copy-buffer (make-array +buffer-size+))))) (defun make-undo-object (object operation) (menu-name-for-undo-command object operation) (with-application-frame (gened-frame) (with-slots (object-copy-buffer buffer-counter) gened-frame (setf buffer-counter (mod (1+ buffer-counter) +buffer-size+)) (case operation ((create cluster load-object copy) (setf (aref object-copy-buffer buffer-counter) (make-instance 'undo-object :object-copy nil :original-object object :operation operation))) (load-scene (setf (aref object-copy-buffer buffer-counter) (make-instance 'undo-object :object-copy nil :original-object nil :operation operation))) (otherwise (let ((copy (make-instance (type-of object) :initialize nil))) (copy-values object copy) (setf (aref object-copy-buffer buffer-counter) (make-instance 'undo-object :object-copy copy :original-object object :operation operation)) (setf (id-number copy) (id-number object)) (if (typep object 'composite-thing) (mapc #'(lambda (part copy-part) (setf (id-number copy-part) (id-number part))) (liste object) (liste copy))))))))) (defun unstack-undo-object () (with-application-frame (gened-frame) (with-slots (object-copy-buffer buffer-counter liste) gened-frame (let ((object (aref object-copy-buffer buffer-counter))) (setf (aref object-copy-buffer buffer-counter) nil) (setf buffer-counter (mod (1- buffer-counter) +buffer-size+)) (let ((next-object (get-undo-object))) (if next-object (menu-name-for-undo-command (original-object next-object) (operation next-object)) (menu-name-for-undo-command nil nil))) object)))) (defun menu-name-for-undo-command (object operation) (remove-command-from-command-table 'com-gened-undo 'manipulate-table) (if (and object operation) (add-command-to-command-table 'com-gened-undo 'manipulate-table :menu (list (concatenate 'string "UNDO " (command-name-from-symbol operation) " " (write-to-string object)) ':after ':start)) (add-command-to-command-table 'com-gened-undo 'manipulate-table :menu (list "UNDO NOTHING" ':after ':start)))) (defun get-undo-object () (with-application-frame (gened-frame) (with-slots (object-copy-buffer buffer-counter) gened-frame (aref object-copy-buffer buffer-counter)))) (defun undo () (with-application-frame (gened-frame) (with-slots (object-copy-buffer buffer-counter liste) gened-frame (let* ((undo-object (unstack-undo-object))) (if undo-object (let ((operation (operation undo-object)) (original-object (original-object undo-object)) (object-copy (object-copy undo-object))) (format *standard-output* "~%---> UNDOING ~a : ~a~%" operation original-object) (case operation (delete (make-poly-representation object-copy) (push object-copy liste)) ((create load-object copy) (let ((object (get-object (id-number original-object)))) (delete-object object :undo-object nil))) (cluster (let ((object (get-object (id-number original-object)))) (atomize-cluster object))) (load-scene (com-gened-new)) (otherwise (delete-polyrep-from-cache (get-object (id-number original-object))) (setf liste (mapcar #'(lambda (elem) (if (= (id-number elem) (id-number object-copy)) object-copy elem)) liste)) (make-poly-representation object-copy))) (redraw) (do-incremental-updates :backward t))) undo-object)))) (define-gened-command (com-gened-undo :name "Undo Last Operation") () (unless (undo) (beep)))
4,543
Common Lisp
.lisp
140
26.114286
74
0.652438
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
52e4170028f4db39cb301cc6a1dd8181060c6f5768bbba8dbb1434db384a2217
11,180
[ -1 ]
11,181
inout.lisp
lambdamikel_GenEd/src/inout.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; Writer-Methods ;;; (defmethod write-object ((object t) stream &key &allow-other-keys) (declare (ignore stream)) ()) (defun write-it (object stream) (write object :stream stream) (terpri stream)) (defmethod write-object ((object filled-mixin) stream &key &allow-other-keys) (with-slots (filledp filled-ink) object (write-it 'filled-mixin stream) (write-it filledp stream) (write-it filled-ink stream) (call-next-method))) (defmethod write-object ((object thing) stream &key &allow-other-keys) (with-slots (hidden xtrans ytrans parent-concepts ancestor-concepts) object (write-it 'thing stream) (write-it parent-concepts stream) (write-it ancestor-concepts stream) (write-it xtrans stream) (write-it ytrans stream) (write-it hidden stream) (call-next-method))) (defmethod write-object ((object ink-mixin) stream &key &allow-other-keys) (with-slots (ink) object (write-it 'ink-mixin stream) (write-it ink stream)) (call-next-method)) (defmethod write-object ((object linestyle-mixin) stream &key &allow-other-keys) (with-slots (linestyle) object (write-it 'linestyle-mixin stream) (write-it linestyle stream) (call-next-method))) (defmethod write-object ((object linethickness-mixin) stream &key &allow-other-keys) (with-slots (linethickness) object (write-it 'linethickness-mixin stream) (write-it linethickness stream)) (call-next-method)) (defmethod write-object ((object basic-thing) stream &key &allow-other-keys) (write-it 'basic-thing stream) (call-next-method)) (defmethod write-object ((object composite-thing) stream &key &allow-other-keys) (with-slots (liste) object (write-it 'composite-thing stream) (write-it (length liste) stream) (dolist (elem liste) (write-it (type-of elem) stream) (write-object elem stream)) (call-next-method))) (defmethod write-object ((object g-rectangle) stream &key &allow-other-keys) (with-slots (xextend yextend) object (write-it 'g-rectangle stream) (write-it xextend stream) (write-it yextend stream) (call-next-method))) (defmethod write-object ((object g-arrow) stream &key &allow-other-keys) (write-it 'g-arrow stream) (call-next-method)) (defmethod write-object ((object linesegment) stream &key &allow-other-keys) (with-slots (startpoint endpoint) object (write-it 'linesegment stream) (write-it startpoint stream) (write-it endpoint stream) (call-next-method))) (defmethod write-object ((object object-with-head) stream &key &allow-other-keys) (write-it 'object-with-head stream) (write-it (head object) stream) (call-next-method)) (defmethod write-object ((object pointlist-object) stream &key &allow-other-keys) (write-it 'pointlist-object stream) (with-slots (pointlist) object (write-it (/ (length pointlist) 2) stream) (dolist (point (reverse (generate-brackets pointlist))) (write-it (first point) stream) (write-it (second point) stream)) (call-next-method))) (defmethod write-object ((object g-polygon) stream &key &allow-other-keys) (write-it 'g-polygon stream) (call-next-method)) (defmethod write-object ((object g-chain) stream &key &allow-other-keys) (write-it 'g-chain stream) (call-next-method)) (defmethod write-object ((object spline-object) stream &key &allow-other-keys) (write-it 'spline-object stream) (write-it (spline-points object) stream) (call-next-method)) (defmethod write-object ((object g-spline-chain) stream &key &allow-other-keys) (write-it 'g-spline-chain stream) (call-next-method)) (defmethod write-object ((object g-spline-polygon) stream &key &allow-other-keys) (write-it 'g-spline-polygon stream) (call-next-method)) (defmethod write-object ((object g-circle) stream &key &allow-other-keys) (with-slots (radius) object (write-it 'g-circle stream) (write-it radius stream) (call-next-method))) (defmethod write-object ((object g-text) stream &key &allow-other-keys) (with-slots (text-string face size family) object (write-it 'g-text stream) (write-it text-string stream) (write-it face stream) (write-it family stream) (write-it size stream) (call-next-method))) (defmethod write-object ((object g-point) stream &key &allow-other-keys) (write-it 'g-point stream) (call-next-method)) (defmethod write-object ((object object-with-handles) stream &key &allow-other-keys) (with-slots (handles) object (write-it 'object-with-handles stream) (write-it (length handles) stream) (dolist (handle (reverse handles)) (write-it (type-of handle) stream) (write-it (x handle) stream) (write-it (y handle) stream) ) (call-next-method))) (defmethod write-object ((object scaleable-thing) stream &key &allow-other-keys) (with-slots (xscale yscale init-x-extend init-y-extend) object (write-it 'scaleable-thing stream) (write-it xscale stream) (write-it yscale stream) (write-it init-x-extend stream) (write-it init-y-extend stream) (call-next-method))) (defmethod write-object ((object rotateable-thing) stream &key &allow-other-keys) (with-slots (rotangle) object (write-it 'rotateable-thing stream) (write-it rotangle stream) (call-next-method))) ;;; ;;; Reader Methods ;;; (defmethod read-object ((object t) stream &key ) (declare (ignore stream)) (get-bounding-rect object)) (defmethod read-object ((object thing) stream &key ) (with-slots (xtrans ytrans hidden parent-concepts ancestor-concepts id-number) object (read stream) (setf parent-concepts (read stream)) (setf ancestor-concepts (read stream)) (setf xtrans (read stream)) (setf ytrans (read stream)) (setf hidden (read stream)) (setf id-number (get-id-number))) (call-next-method )) (defmethod read-object ((object filled-mixin) stream &key ) (with-slots (filledp filled-ink) object (read stream) (setf filledp (read stream)) (setf filled-ink (read stream))) (call-next-method )) (defmethod read-object ((object ink-mixin) stream &key ) (with-slots (ink) object (read stream) (setf ink (read stream))) (call-next-method )) (defmethod read-object ((object linestyle-mixin) stream &key ) (with-slots (linestyle) object (read stream) (setf linestyle (read stream))) (call-next-method )) (defmethod read-object ((object linethickness-mixin) stream &key ) (with-slots (linethickness) object (read stream) (setf linethickness (read stream))) (call-next-method )) (defmethod read-object ((object basic-thing) stream &key ) (read stream) (call-next-method )) (defmethod read-object ((object composite-thing) stream &key ) (with-slots (liste) object (read stream) (dotimes (n (read stream)) (let ((object (make-instance (read stream)))) (read-object object stream) (push object liste))) (call-next-method ))) (defmethod read-object ((object g-rectangle) stream &key ) (with-slots (xextend yextend) object (read stream) (setf xextend (read stream)) (setf yextend (read stream)) (call-next-method ))) (defmethod read-object ((object g-circle) stream &key ) (with-slots (radius) object (read stream) (setf radius (read stream)) (call-next-method ))) (defmethod read-object ((object linesegment) stream &key ) (with-slots (startpoint endpoint) object (read stream) (setf startpoint (read stream)) (setf endpoint (read stream)) (call-next-method ))) (defmethod read-object ((object g-arrow) stream &key ) (read stream) (call-next-method )) (defmethod read-object ((object object-with-head) stream &key ) (read stream) (setf (head object) (read stream)) (call-next-method )) (defmethod read-object ((object g-polygon) stream &key ) (read stream) (call-next-method )) (defmethod read-object ((object g-chain) stream &key ) (read stream) (call-next-method )) (defmethod read-object ((object spline-object) stream &key ) (read stream) (with-slots (spline-points) object (setf spline-points (read stream))) (call-next-method )) (defmethod read-object ((object g-spline-chain) stream &key ) (read stream) (call-next-method )) (defmethod read-object ((object g-spline-polygon) stream &key ) (read stream) (call-next-method )) (defmethod read-object ((object pointlist-object) stream &key ) (read stream) (with-slots (pointlist) object (let ((counter (read stream)) (x) (y)) (dotimes (i counter) (setf x (read stream)) (setf y (read stream)) (push y pointlist) (push x pointlist)) (call-next-method )))) (defmethod read-object ((object g-point) stream &key ) (read stream) (call-next-method )) (defmethod read-object ((object g-text) stream &key ) (read stream) (with-slots (text-string face size family) object (setf text-string (read stream)) (setf face (read stream)) (setf family (read stream)) (setf size (read stream)) (call-next-method ))) (defmethod read-object ((object object-with-handles) stream &key ) (read stream) (let ((counter (read stream)) (handle)) (dotimes (i counter) (setf handle (make-instance (read stream))) (setf (x handle) (read stream)) (setf (y handle) (read stream)) (setf (parent-object handle) object) (push handle (handles object))) (call-next-method ))) (defmethod read-object ((object scaleable-thing) stream &key ) (read stream) (with-slots (xscale yscale init-x-extend init-y-extend) object (setf xscale (read stream)) (setf yscale (read stream)) (setf init-x-extend (read stream)) (setf init-y-extend (read stream)) (call-next-method ))) (defmethod read-object ((object rotateable-thing) stream &key ) (read stream) (with-slots (rotangle) object (setf rotangle (read stream)) (call-next-method))) ;;; ;;; Save & Load ;;; (defun file-selector (title directory) (with-application-frame (gened-frame) (let* ((file (select-file gened-frame :title title :directory directory)) (file (and file (namestring file)))) (if (and file (not (string= "" file))) (if (char= (elt file (1- (length file))) #\/) (progn (notify-user gened-frame "You must select a file, not a directory!" :style :error) nil) file) (progn (notify-user gened-frame (format nil "No file selected!") :style :error) nil))))) (define-gened-command (com-gened-save-scene :name "Save Scene") () (with-application-frame (gened-frame) (let ((file (file-selector "Save Scene" +scenes-dir+))) (when file (when (and (probe-file file) (not (notify-user gened-frame (format nil "Overwrite ~A" file) :style :warning))) (return-from com-gened-save-scene)) (with-open-file (output-stream file :direction :output :if-exists :supersede :if-does-not-exist :create) (with-standard-io-syntax (write 'scene-data :stream output-stream) (terpri output-stream) (with-slots (liste) gened-frame (write (length liste) :stream output-stream) (terpri output-stream) (dolist (object (reverse liste)) (write-it (type-of object) output-stream) (write-object object output-stream))))) (setf *current-file* file))))) (define-gened-command (com-gened-load-scene :name "Load Scene") () (with-application-frame (gened-frame) (let ((file (file-selector "Load Scene" +scenes-dir+)) (objects 0) (nowobject)) (when file (unless (probe-file file) (notify-user gened-frame (format nil "File ~A does not exist" file) :style :error) (return-from com-gened-load-scene)) (new) (with-slots (liste) gened-frame (with-open-file (s file :direction :input) (with-standard-io-syntax (unless (eq (read s) 'scene-data) (notify-user gened-frame (format nil "File ~A is not a scene-file!" file) :style :error) (return-from com-gened-load-scene)) (setf objects (read s)) (dotimes (num objects) (setf nowobject (make-instance (read s) :initialize nil)) (push nowobject liste) (read-object nowobject s) (make-poly-representation nowobject)))) (dolist (elem liste) (if (typep elem 'object-with-handles) (dolist (handle (handles elem)) (if (typep handle 'fixed-object-handle) (fix-handle handle))))) (setf *current-file* file) (make-undo-object nil 'load-scene) (do-incremental-updates)))))) ;;; ;;; ;;; (define-gened-command (com-gened-save-library :name "Save Library") () (with-application-frame (gened-frame) (let ((file (file-selector "Save Library" +libraries-dir+))) (when file (when (and (probe-file file) (not (notify-user gened-frame (format nil "Overwrite ~A" file) :style :warning))) (return-from com-gened-save-library)) (with-open-file (output-stream file :direction :output :if-exists :supersede :if-does-not-exist :create) (with-standard-io-syntax (write 'library-data :stream output-stream) (terpri output-stream) (write (length *library*) :stream output-stream) (terpri output-stream) (dolist (lib-item (reverse *library*)) (write (first lib-item) :stream output-stream) (terpri output-stream) (write-it (type-of (second lib-item)) output-stream) (write-object (second lib-item) output-stream)))))))) (define-gened-command (com-gened-load-library :name "Load Library") () (with-application-frame (gened-frame) (let ((file (file-selector "Load Library" +libraries-dir+))) (when file (unless (probe-file file) (notify-user gened-frame (format nil "File ~A does not exist" file) :style :error) (return-from com-gened-load-library)) (with-open-file (s file :direction :input) (with-standard-io-syntax (unless (eq (read s) 'library-data) (notify-user gened-frame (format nil "File ~A is not a library-file!" file) :style :error) (return-from com-gened-load-library)) (let ((length (read s))) (dotimes (i length) (let ((label (read s)) (now-object (make-instance (read s) :initialize nil))) (push (list label now-object) *library*) (read-object now-object s) (make-poly-representation now-object)))))))))) ;;; ;;; ;;; (defmethod save-object ((object thing)) (with-application-frame (gened-frame) (let ((file (file-selector "Save Object" +objects-dir+))) (when file (when (and (probe-file file) (not (notify-user gened-frame (format nil "Overwrite ~A" file) :style :warning))) (return-from save-object)) (with-open-file (output-stream file :direction :output :if-exists :supersede :if-does-not-exist :create) (with-standard-io-syntax (write 'object-data :stream output-stream) (terpri output-stream) (write-it (type-of object) output-stream) (write-object object output-stream))))))) (define-gened-command (com-save-object) ((object 'thing :gesture nil)) (save-object object)) (define-gened-command (com-gened-save-object :name "Save Object") () (if (any-visible-objects) (let ((source-object (accept 'thing))) (terpri) (save-object source-object)))) ;;; ;;; ;;; (defun load-object (file) (when file (unless (probe-file file) (return-from load-object 'error-does-not-exists)) (with-open-file (s file :direction :input) (with-standard-io-syntax (unless (eq (read s) 'object-data) (return-from load-object 'error-not-an-object-file)) (let ((now-object (make-instance (read s) :initialize nil))) (read-object now-object s) now-object))))) (defun load-query-object () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (let* ((file (file-selector "Load Data" +objects-dir+))) (when file (let ((object (load-object file))) (case object (error-does-not-exists (notify-user gened-frame (format nil "File ~A does not exist" file) :style :error)) (error-not-an-object-file (notify-user gened-frame (format nil "File ~A is not an object-file!" file) :style :error)) (otherwise (make-poly-representation object) (push object liste) (make-undo-object object 'load-object) (do-incremental-updates))))))))) (define-gened-command (com-gened-load-object :name "Load Object") () (load-query-object)) ;;; ;;; ;;; #+:allegro (define-gened-command (com-gened-print-scene :name "Print Scene") () (with-application-frame (gened-frame) (with-open-stream (pipe (excl:run-shell-command (format nil "lpr -P~A" '|r131_hp|) :input :stream :wait nil)) (with-output-to-postscript-stream (stream pipe :orientation :landscape :scale-to-fit t) (with-slots (liste) gened-frame (dolist (object (reverse liste)) (draw object stream :printing-active t))))))) (define-gened-command (com-gened-save-postscript :name "Save Scene As Postscript") () (with-application-frame (gened-frame) (let ((file (file-selector "Save Postscript-File" +prints-dir+)) (*global-scaling* 1)) (when file (when (and (probe-file file) (not (notify-user gened-frame (format nil "Overwrite ~A" file) :style :warning))) (return-from com-gened-save-postscript)) (with-open-file (output-stream file :direction :output :if-exists :supersede :if-does-not-exist :create) (with-standard-io-syntax (with-output-to-postscript-stream (stream output-stream :orientation :portrait :scale-to-fit t) (with-translation (stream 0 150) (with-slots (liste) gened-frame (dolist (object (reverse liste)) (draw object stream :printing-active t)))))))))))
18,453
Common Lisp
.lisp
508
31.122047
87
0.666573
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
d73f676a0f12aa91592ce35ca2e74ad060be1e0ca9fc601ed91c7129f8e35ea5
11,181
[ -1 ]
11,182
draw.lisp
lambdamikel_GenEd/src/draw.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defmethod transform-and-draw ((object basic-thing) stream drawer-function) (let* ((comptrans (get-transformation object)) (gstrans (make-scaling-transformation *global-scaling* *global-scaling*)) (trans (compose-transformations gstrans comptrans))) (with-drawing-options (stream :transformation trans) (funcall drawer-function)))) (defmethod transform-and-draw ((object composite-thing) stream drawer-function) (declare (ignore stream)) (funcall drawer-function)) (defmethod transform-point ((object basic-thing) x y &key (inverse nil)) (let ((comptrans (get-transformation object))) (multiple-value-bind (x y) (if inverse (untransform-position comptrans x y) (transform-position comptrans x y)) (values x y)))) (defun scale-mouse-position (x y &key (inverse nil)) (if inverse (values (round (/ x *global-scaling*)) (round (/ y *global-scaling*))) (values (round (* x *global-scaling*)) (round (* y *global-scaling*))))) (defmethod get-transformation ((object basic-thing)) (let* ((scaletrans (if (typep object 'scaleable-thing) (make-scaling-transformation (xscale object) (yscale object)) +identity-transformation+)) (transtrans (make-translation-transformation (xtrans object) (ytrans object))) (rottrans (if (typep object 'rotateable-thing) (make-rotation-transformation (rotangle object)) +identity-transformation+)) (comptrans (compose-transformations transtrans (compose-transformations rottrans scaletrans)))) comptrans)) (defmethod get-transformation ((object composite-thing)) +identity-transformation+) ;;; ;;; ;;; (defmethod output-draw-object-handles ((object object-with-handles) stream &key &allow-other-keys) (transform-and-draw object stream #'(lambda () (let ((handles (handles object))) (dolist (elem handles) (with-output-as-presentation (stream elem (type-of elem) :single-box :position) (draw elem stream))))))) (defmethod draw-object-handles ((object object-with-handles) stream &key (handling-active nil) (printing-active nil) &allow-other-keys) (transform-and-draw object stream #'(lambda () (let ((handles (handles object))) (dolist (elem handles) (draw elem stream :handling-active handling-active :printing-active printing-active)))))) (defmethod draw ((object object-handle) stream &key (handling-active nil) (printing-active nil) &allow-other-keys) (if (or (member 'normal *handles-symbol-list*) (and (member 'unfixed *handles-symbol-list*) (typep object 'unfixed-object-handle)) (and (member 'fixed *handles-symbol-list*) (typep object 'fixed-object-handle))) (let ((x (x object)) (y (y object))) (multiple-value-bind (ink1 ink2 pattern) (get-right-inks object :handling-active handling-active :printing-active printing-active) (declare (ignore ink2)) (draw-rectangle* stream (- x *handle-space*) (- y *handle-space*) (+ x *handle-space*) (+ y *handle-space*) :ink ink1 :filled (typep object 'fixed-object-handle) :line-dashes pattern))))) (defmethod draw ((object start-handle) stream &key (handling-active nil) (printing-active nil) &allow-other-keys) (if (or (member 'start *handles-symbol-list*) (and (member 'fixed *handles-symbol-list*) (typep object 'fixed-object-handle)) (and (member 'unfixed *handles-symbol-list*) (typep object 'unfixed-object-handle))) (let ((x (x object)) (y (y object))) (multiple-value-bind (ink1 ink2 pattern) (get-right-inks object :handling-active handling-active :printing-active printing-active) (draw-circle* stream x y (+ 2 *handle-space*) :ink ink1 :filled (typep object 'fixed-object-handle) :line-dashes pattern) (draw-marker* stream (list x y) *handle-space* :ink ink2 :line-dashes pattern))))) (defmethod draw ((object end-handle) stream &key (handling-active nil) (printing-active nil) &allow-other-keys) (if (or (member 'end *handles-symbol-list*) (and (member 'fixed *handles-symbol-list*) (typep object 'fixed-object-handle)) (and (member 'unfixed *handles-symbol-list*) (typep object 'unfixed-object-handle))) (let ((x (x object)) (y (y object))) (multiple-value-bind (ink1 ink2 pattern) (get-right-inks object :handling-active handling-active :printing-active printing-active) (draw-rectangle* stream (- x *handle-space* 1) (- y *handle-space* 1) (+ x *handle-space* 1) (+ y *handle-space* 1) :ink ink1 :filled (typep object 'fixed-object-handle) :line-dashes pattern) (draw-marker* stream (list x y) *handle-space* :ink ink2 :line-dashes pattern))))) ;;; ;;; ;;; (defmethod output-draw ((object composite-thing) stream &key &allow-other-keys) (with-output-as-presentation (stream object 'composite-thing :single-box t) (draw object stream))) (defmethod output-draw ((object basic-thing) stream &key &allow-other-keys) (let ((*handles-symbol-list* nil)) (with-output-as-presentation (stream object (type-of object) :single-box :position) (draw object stream)))) (defmethod output-draw :after ((object object-with-handles) stream &key &allow-other-keys) (output-draw-object-handles object stream)) ;;; ;;; ;;; (defmethod draw :after ((object object-with-handles) stream &key (handling-active nil) (printing-active nil) &allow-other-keys) (if (not (null *handles-symbol-list*)) (draw-object-handles object stream :handling-active handling-active :printing-active printing-active))) (defmethod draw :after ((object thing) stream &key (handling-active nil) (printing-active nil) &allow-other-keys) (let ((xtrans (xtrans object)) (ytrans (ytrans object))) (multiple-value-bind (ink1) (get-right-inks object :handling-active handling-active :printing-active printing-active) (if (or *bounding-boxes* (highlightedp object)) (multiple-value-bind (left top right bottom) (get-bounding-rect object :handling-active handling-active) (draw-rectangle* stream (- left +br-space+) (- top +br-space+) (+ right +br-space+) (+ bottom +br-space+) :filled nil :line-dashes (if (highlightedp object) nil (if handling-active +br-line-dashes2+ +br-line-dashes+)) :line-thickness (if (highlightedp object) +br-highlight-thickness+ +br-line-thickness+) :ink ink1))) (if *concept-labels* (with-scaling (stream *global-scaling* *global-scaling*) (let ((count 0) (ancestor-concepts (cons '* (ancestor-concepts object))) (parent-concepts (cons '** (parent-concepts object)))) (dolist (concepts (append (when (and (not (null parent-concepts)) (or (member 'parents *concept-labels*) (equal '(ids) *concept-labels*))) (list parent-concepts)) (when (and (member 'ancestors *concept-labels*) (not (null ancestor-concepts))) (list ancestor-concepts)))) (with-text-style (stream (if (eq (first concepts) '*) +labels-text-style2+ +labels-text-style+)) (let ((concepts (if (equal *concept-labels* '(ids)) '(ID) (rest concepts)))) (dolist (concept concepts) (draw-text* stream (if (and (zerop count) (member 'ids *concept-labels*)) (concatenate 'string (generate-name concept) " " (write-to-string (id-number object))) (generate-name concept)) (- xtrans *org-space* 3) (- (- ytrans *org-space* 3) (/ (* (incf count) +labels-text-height+) *global-scaling*)) :ink ink1)))))))) (if *origins* (with-scaling (stream *global-scaling* *global-scaling*) (draw-rectangle* stream (- xtrans *org-space*) (- ytrans *org-space*) (+ xtrans *org-space*) (+ ytrans *org-space*) :ink ink1 :filled nil :line-dashes (if handling-active +origin-dashes+)) (draw-marker* stream (list xtrans ytrans) *org-space* :ink ink1 :line-dashes (if handling-active +origin-dashes+))))))) ;;; ;;; ;;; (defmacro draw-good-arrow* (xs ys xe ye) `(draw-arrow* stream ,xs ,ys ,xe ,ye :ink (if handling-active +flipping-ink+ (make-gray-color (ink object))) :line-thickness (if handling-active 1 (+ (linethickness object) (if printing-active +printing-inc+ 0))) :line-dashes (if handling-active +dash-pattern+ (linestyle object)) :head-width (if (head object) (nth (1- (linethickness object)) '(6 9 13 18)) 0) :head-length (if (head object) (nth (1- (linethickness object)) '(6 9 15 22)) 0))) (defmacro draw-good-line* (xs ys xe ye) `(draw-line* stream ,xs ,ys ,xe ,ye :ink (if handling-active +flipping-ink+ (make-gray-color (ink object))) :line-thickness (if handling-active 1 (+ (linethickness object) (if printing-active +printing-inc+ 0))) :line-dashes (if handling-active +dash-pattern+ (linestyle object)))) ;;; ;;; ;;; (defun draw-pointlist (object pointlist stream &key (printing-active nil) (handling-active nil)) (if *pretty-hl* (transform-and-draw object stream #'(lambda () (when *global-border* (let* ((points (butlast pointlist 2)) (end (last pointlist 2)) (lastx) (lasty)) (loop for x in points by #'cddr for y in (cdr points) by #'cddr do (if (and lastx lasty) (draw-line* stream lastx lasty x y :ink (if handling-active +flipping-ink+ (make-gray-color (ink object))) :line-thickness (if handling-active 1 (+ (linethickness object) (if printing-active +printing-inc+ 0))) :line-dashes (if handling-active +dash-pattern+ (linestyle object)))) (setf lastx x lasty y) finally (if (head object) (draw-good-arrow* (or lastx (first pointlist)) (or lasty (second pointlist)) (first end) (second end)) (draw-good-line* (or lastx (first pointlist)) (or lasty (second pointlist)) (first end) (second end))) ))))) (transform-and-draw object stream #'(lambda () (when *global-border* (let* ((points (butlast pointlist 2)) (end (last pointlist 4))) (if points (draw-polygon* stream points :ink (if handling-active +flipping-ink+ (make-gray-color (ink object))) :line-thickness (if handling-active 1 (+ (linethickness object) (if printing-active +printing-inc+ 0))) :line-dashes (if handling-active +dash-pattern+ (linestyle object)) :filled nil :closed nil)) (when (= (length end) 4) (if (head object) (draw-good-arrow* (first end) (second end) (third end) (fourth end)) (draw-good-line* (first end) (second end) (third end) (fourth end)))))))))) ;;; ;;; ;;; (defmethod draw ((object composite-thing) stream &key (handling-active nil) (printing-active nil) &allow-other-keys) (transform-and-draw object stream #'(lambda () (with-slots (liste) object (let ((*bounding-boxes* nil) (*concept-labels* nil) (*origins* nil) (*handles-symbol-list* nil)) (dolist (elem liste) (draw elem stream :handling-active handling-active :printing-active printing-active))))))) ;;; ;;; ;;; (defmethod draw ((object g-circle) stream &key (handling-active nil) (printing-active nil) &allow-other-keys) (if (and (not handling-active) (polygonized-representation object)) (let ((points (get-points (polygonized-representation object)))) (if (and (filledp object) *global-filled*) (draw-polygon* stream points :ink (make-gray-color (filled-ink object)) :filled t)) (if *global-border* (draw-polygon* stream points :ink (make-gray-color (ink object)) :filled nil :line-thickness (+ (linethickness object) (if printing-active +printing-inc+ 0)) :line-dashes (linestyle object)))) (transform-and-draw object stream #'(lambda () (if (and (not handling-active) (filledp object) *global-filled*) (draw-circle* stream 0 0 (radius object) :ink (make-gray-color (filled-ink object)) :filled t)) (if *global-border* (draw-circle* stream 0 0 (radius object) :ink (if handling-active +flipping-ink+ (make-gray-color (ink object))) :filled nil :line-thickness (if handling-active 1 (+ (linethickness object) (if printing-active +printing-inc+ 0))) :line-dashes (if handling-active +dash-pattern+ (linestyle object)))))))) (defmethod draw ((object g-rectangle) stream &key (handling-active nil) (printing-active nil) &allow-other-keys) (if (and (not handling-active) (polygonized-representation object)) (let ((points (get-points (polygonized-representation object)))) (if (and (filledp object) *global-filled*) (draw-polygon* stream points :ink (make-gray-color (filled-ink object)) :filled t)) (if *global-border* (draw-polygon* stream points :ink (make-gray-color (ink object)) :filled nil :line-thickness (+ (linethickness object) (if printing-active +printing-inc+ 0)) :line-dashes (linestyle object)))) (transform-and-draw object stream #'(lambda () (if *global-border* (draw-polygon* stream (append (list (- (xextend object)) (yextend object)) (list (xextend object) (yextend object)) (list (xextend object) (- (yextend object))) (list (- (xextend object)) (- (yextend object)))) :ink (if handling-active +flipping-ink+ (make-gray-color (ink object))) :filled nil :closed t :line-thickness (if handling-active 1 (+ (linethickness object) (if printing-active +printing-inc+ 0))) :line-dashes (if handling-active +dash-pattern+ (linestyle object)))))))) (defmethod draw ((object g-text) stream &key (handling-active nil) &allow-other-keys) (let ((text-style (parse-text-style (list (family object) (face object) (size object))))) (transform-and-draw object stream #'(lambda () (with-text-style (stream text-style) (draw-text* stream (text-string object) 0 0 :ink (if handling-active +flipping-ink+ (make-gray-color (ink object))))))))) (defmethod draw ((object g-point) stream &key (handling-active nil) (printing-active nil) &allow-other-keys) (transform-and-draw object stream #'(lambda () (draw-circle* stream 0 0 (* 2 (linethickness object)) :ink (if handling-active +flipping-ink+ (make-gray-color (ink object))) :filled t :line-thickness (if handling-active 1 (+ (linethickness object) (if printing-active +printing-inc+ 0))))))) (defmethod draw ((object g-arrow) stream &key (handling-active nil) (printing-active nil) &allow-other-keys) (let ((startpoint (startpoint object)) (endpoint (endpoint object))) (transform-and-draw object stream #'(lambda () (when *global-border* (if (head object) (draw-good-arrow* (first startpoint) (second startpoint) (first endpoint) (second endpoint)) (draw-line* stream (first startpoint) (second startpoint) (first endpoint) (second endpoint) :ink (if handling-active +flipping-ink+ (make-gray-color (ink object))) :line-thickness (if handling-active 1 (+ (linethickness object) (if printing-active +printing-inc+ 0))) :line-dashes (if handling-active +dash-pattern+ (linestyle object))))))))) (defmethod draw ((object g-chain) stream &key (handling-active nil) (printing-active nil) &allow-other-keys) (draw-pointlist object (pointlist object) stream :printing-active printing-active :handling-active handling-active)) (defmethod draw ((object g-spline-chain) stream &key (handling-active nil) (handle-handling-active nil) (printing-active nil) &allow-other-keys) (draw-pointlist object (if (or handle-handling-active (null (spline-points object))) (pointlist object) (spline-points object)) stream :printing-active printing-active :handling-active handling-active)) (defmethod draw ((object g-spline-polygon) stream &key (handling-active nil) (printing-active nil) (handle-handling-active nil) &allow-other-keys) (transform-and-draw object stream #'(lambda () (if (and (not handling-active) (filledp object) *global-filled*) (draw-polygon* stream (if (null (spline-points object)) (pointlist object) (spline-points object)) :ink (make-gray-color (filled-ink object)) :closed t :filled t)) (if *global-border* (draw-polygon* stream (if (or handle-handling-active (null (spline-points object))) (pointlist object) (spline-points object)) :ink (if handling-active +flipping-ink+ (make-gray-color (ink object))) :line-thickness (if handling-active 1 (+ (linethickness object) (if printing-active +printing-inc+ 0))) :line-dashes (if handling-active +dash-pattern+ (linestyle object)) :closed t :filled nil))))) (defmethod draw ((object g-polygon) stream &key (handling-active nil) (printing-active nil) &allow-other-keys) (let ((pointlist (pointlist object))) (transform-and-draw object stream #'(lambda () (if (and (not handling-active) (filledp object) *global-filled*) (draw-polygon* stream pointlist :ink (make-gray-color (filled-ink object)) :filled t)) (if *global-border* (draw-polygon* stream pointlist :ink (if handling-active +flipping-ink+ (make-gray-color (ink object))) :line-thickness (if handling-active 1 (+ (linethickness object) (if printing-active +printing-inc+ 0))) :line-dashes (if handling-active +dash-pattern+ (linestyle object)) :filled nil)))))) ;;; ;;; ;;; (defmethod draw-gened ((frame gened) stream &key max-width max-height) (declare (ignore max-width max-height)) (with-slots (liste) frame (dolist (object (reverse liste)) (let ((visible (and (not (hiddenp object))))) (when (and (or (and visible (member 'visible *global-display-options*)) (and (not visible) (member 'hidden *global-display-options*))) (or (and (typep object 'basic-thing) (not (typep object 'composite-thing)) (member 'primitive *global-display-options*)) (and (typep object 'composite-thing) (member 'composite *global-display-options*)))) (updating-output (stream :unique-id object :cache-value (tickval object)) (output-draw object stream)))))))
21,314
Common Lisp
.lisp
644
24.891304
79
0.600736
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
a0a9bc27b663421499d931c192c109d2a7c49f84b19b5e816f38122054d47e0d
11,182
[ -1 ]
11,183
mac-gened-sysdcl.lisp
lambdamikel_GenEd/src/mac-gened-sysdcl.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: CL-User; Base: 10 -*- (cl:in-package cl-user) (define-system geometry (:default-pathname "gened:geometry;" :subsystem t) (:serial "newgeo13")) (define-system splines (:default-pathname "gened:splines;" :subsystem t) (:serial "spline3")) (define-system knowledge (:default-pathname "gened:knowledge;" :subsystem t) (:serial "knowledge7")) (define-system mac-gened (:default-pathname "gened:sources;") (:serial "gened-packages" "values" "classesxx" "comtable" "mac-frame" (:parallel splines geometry) "helpaux" "polyrep" "transfor" "draw" "creator" "cluster" "handles" "inout" "copy" "spatial5" "inspect" "delete" "undo" "main" "rel-copy2" "interface-to-classic3" knowledge "concepts" "delta2" "mac-init"))
931
Common Lisp
.lisp
42
17.095238
76
0.620571
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
6756e69f6957506d9f47bb5dc9af94c60c47e4b5e39847d29101f88dbde80bf1
11,183
[ -1 ]
11,184
transfor.lisp
lambdamikel_GenEd/src/transfor.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defmethod translate-object ((object thing) newx newy) (let ((dx (- newx (xtrans object))) (dy (- newy (ytrans object)))) (translate-relative-object object dx dy))) (defmethod translate-object ((object basic-thing) newx newy) (declare (ignore newx newy)) (call-next-method)) (defmethod translate-relative-object ((object basic-thing) deltax deltay) (incf (xtrans object) deltax) (incf (ytrans object) deltay) (translate-fixed-handles-relative object deltax deltay)) (defmethod translate-relative-object ((object composite-thing) deltax deltay) (with-slots (liste) object (dolist (elem liste) (translate-relative-object elem deltax deltay)) ; weil beliebige Cluster moeglich! (incf (xtrans object) deltax) (incf (ytrans object) deltay) (translate-fixed-handles-relative object deltax deltay))) (defmethod set-object-scaling ((object scaleable-thing) newleft newtop newright newbottom) (let* ((xext (init-x-extend object)) (yext (init-y-extend object))) (setf (xscale object) (/ (- newright newleft) xext)) (setf (yscale object) (/ (- newbottom newtop) yext)))) ;;; ;;; ;;; (defmethod rotate-object ((object rotateable-thing) newangle) (setf (rotangle object) newangle)) (defmethod move-object ((object thing)) (save-object-list) (make-undo-object object 'move) (when *info* (format t "~%Press Left Mouse-Button To Release!~%")) (interactive-master-creator object #'(lambda (x y) (translate-object object x y)) :drawer-function #'(lambda (object stream) (draw object stream :handling-active t))) (free-my-handles object) (adjust-object-origin object) (adjust-all-attached-objects object) (tick-object object) (do-incremental-updates)) (define-gened-command (com-move-object) ((object 'thing :gesture :move)) (move-object object)) (define-gened-command (com-gened-move-object :name "Move Object") () (if (any-visible-objects) (let ((source-object (accept 'thing))) (terpri) (move-object source-object)))) ;;; ;;; ;;; (defmethod change-object-scaling ((object scaleable-thing)) (when *info* (format t "~%Press Left Mouse-Button To Release!~%")) (make-undo-object object 'change-object-scaling) (let ((*concept-labels* nil) (xorg (xtrans object)) (yorg (ytrans object))) (interactive-master-creator object #'(lambda (x y) (set-object-scaling object (- (* 2 xorg) x) (- (* 2 yorg) y) x y))) (adjust-object-origin object) (free-my-handles object) (tick-object object) (set-init-extend object) (do-incremental-updates))) (define-gened-command (com-scale-object) ((object 'scaleable-thing :gesture :scale)) (change-object-scaling object)) (define-gened-command (com-gened-scale-object :name "Scale Object") () (if (any-scaleable-objects) (let* ((source-object (accept 'scaleable-thing))) (terpri) (change-object-scaling source-object)))) ;;; ;;; ;;; (defmethod rotate-int-object ((object rotateable-thing)) (make-undo-object object 'rotate-object) (when *info* (format t "~%Press Left Mouse-Button To Release!~%")) (let* ((organgle (rotangle object)) (orgx (xtrans object)) (*concept-labels* nil)) (interactive-master-creator object #'(lambda (nowx nowy) (declare (ignore nowy)) (with-slots (rotangle) object (setf rotangle (+ organgle (* (/ pi 150) (round (- nowx orgx))))))))) (adjust-object-origin object) (free-my-handles object) (tick-object object) (set-init-extend object) (do-incremental-updates)) (define-gened-command (com-rotate-object) ((object 'rotateable-thing :gesture :rotate)) (rotate-int-object object)) (define-gened-command (com-gened-rotate-object :name "Rotate Object") () (if (any-rotateable-objects) (let* ((source-object (accept 'rotateable-thing))) (terpri) (rotate-int-object source-object))))
4,147
Common Lisp
.lisp
123
29.227642
91
0.678103
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
34d5bdfcef5ce2be561af48c88e4e73d27042c0ab90045a4e1d7a81f7b2b820f
11,184
[ -1 ]
11,185
classesx.lisp
lambdamikel_GenEd/src/classesx.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; Klassendefinitionen ;;; (defclass undo-object () ((object-copy :initarg :object-copy :accessor object-copy) (original-object :initarg :original-object :accessor original-object) (operation :initarg :operation :accessor operation))) ;;; (defclass object-handle () ((x :accessor x :initarg :x) (y :accessor y :initarg :y) (parent-object :accessor parent-object :initarg :parent-object))) (defclass start-handle (object-handle) ()) (defclass end-handle (object-handle) ()) (defclass unfixed-object-handle (object-handle) ()) (defclass fixed-object-handle (object-handle) ((fixed-at-object :accessor fixed-at-object :initform nil))) (defclass unfixed-start-handle (unfixed-object-handle start-handle) ()) (defclass unfixed-end-handle (unfixed-object-handle end-handle) ()) (defclass fixed-start-handle (fixed-object-handle start-handle) ()) (defclass fixed-end-handle (fixed-object-handle end-handle) ()) ;;; ;;; ;;; (defclass linestyle-mixin () ((linestyle :initform nil :initarg :linestyle :accessor linestyle))) (defclass ink-mixin () ((ink :initform 0.0 :initarg :ink :accessor ink))) (defclass linethickness-mixin () ((linethickness :initform 1 :initarg :linethickness :accessor linethickness))) (defclass filled-mixin () ((filledp :initform nil :initarg :filledp :accessor filledp) (filled-ink :initform 0.0 :initarg :filled-ink :accessor filled-ink))) (defclass sit-mixin (linestyle-mixin ink-mixin linethickness-mixin) ()) ;;; ;;; ;;; (defclass thing () ((attached-handles :initform nil :accessor attached-handles) (tickval :initform 0 :accessor tickval) (associated-classic-ind :initform nil :accessor associated-classic-ind) (initialize :initform nil :initarg :initialize :accessor initialize) ; t, wenn initialize-instance taetig werden darf (xtrans :initform 0 :accessor xtrans :initarg :xtrans) ; rel. zum Screen-Origin (ytrans :initform 0 :accessor ytrans :initarg :ytrans) ; xytrans ist immer Mittelpunkt der bounding-box (parent-concepts :initform nil :accessor parent-concepts :initarg :parent-concepts) (ancestor-concepts :initform nil :accessor ancestor-concepts) (hidden :initform nil :accessor hiddenp :initarg :hiddenp) (output-record :accessor output-record) (id-number :accessor id-number :initform 0) (highlighted :initform nil :accessor highlightedp) (br-left :accessor br-left) (br-right :accessor br-right) (br-top :accessor br-top) (br-bottom :accessor br-bottom) )) (defclass basic-thing (thing) ((polygonized-representation :initform nil :accessor polygonized-representation))) ;;; ;;; ;;; (defclass rotateable-thing () ; es gibt 2D-Objekte, die nicht rotierbar sind (g-circle) ((rotangle :initform 0 :accessor rotangle))) (defclass scaleable-thing () ; auch 1D-Objekte koennen scalierbar sein, wenn sie nicht flach sind ((xscale :initform 1.0 :accessor xscale :initarg :xscale) (yscale :initform 1.0 :accessor yscale :initarg :yscale) (init-x-extend :accessor init-x-extend) (init-y-extend :accessor init-y-extend))) (defclass scale-and-rotateable-thing (scaleable-thing rotateable-thing) ()) ;;; ;;; ;;; (defclass object-with-handles () ((handles :accessor handles :initarg :handles :initform nil) (initialize-handles :accessor initialize-handles :initform nil :initarg :initialize-handles))) (defclass pointlist-object () ((pointlist :initform nil :initarg :pointlist :accessor pointlist))) (defclass spline-object () ((spline-points :initform nil :accessor spline-points))) (defclass object-with-head () ((head :initform t :initarg :head :accessor head))) (defclass linesegment () ((startpoint :initform '(-10 -10) :initarg :startpoint :accessor startpoint) (endpoint :initform '(10 10) :initarg :endpoint :accessor endpoint))) (defclass directed-info-element () ((startpoint-related-with :initform nil :initarg :startpoint-related-with :accessor startpoint-related-with) (endpoint-related-with :initform nil :initarg :endpoint-related-with :accessor endpoint-related-with) (start-info-point :initform nil :initarg :start-info-point :accessor start-info-point) (end-info-point :initform nil :initarg :end-info-point :accessor end-info-point))) ;;; ;;; ;;; (defclass 0d () ((part-of-cluster :initarg :part-of-cluster :initform nil :accessor part-of-cluster) (disjoint-with :initform nil :accessor disjoint-with) (start-linked-over-with :initform nil :accessor start-linked-over-with) (end-linked-over-with :initform nil :accessor end-linked-over-with) (start-linker-objects :initform nil :accessor start-linker-objects) (end-linker-objects :initform nil :accessor end-linker-objects) (in-relation-with-objects :initform nil :accessor in-relation-with-objects) (intersects-objects :initform nil :accessor intersects-objects) (intersects-0-objects :initform nil :accessor intersects-0-objects) (touching-objects :initform nil :accessor touching-objects) (contained-in-objects :initform nil :accessor contained-in-objects) (covered-by-objects :initform nil :accessor covered-by-objects) (directly-contained-by-object :initform nil :accessor directly-contained-by-object))) (defclass 1d (0d) ((intersects-1-objects :initform nil :accessor intersects-1-objects))) (defclass 2d (1d) ((intersects-2-objects :initform nil :accessor intersects-2-objects) (contains-objects :initform nil :accessor contains-objects) (directly-contains-objects :initform nil :accessor directly-contains-objects) (covers-objects :initform nil :accessor covers-objects))) ;;; ;;; ;;; (defclass composite-thing (thing 2d) ( (liste :initform nil :accessor liste :initarg :liste))) ;;; ;;; ;;; (defclass g-point (basic-thing 0d linethickness-mixin ink-mixin) ()) (defclass info-point (basic-thing 0d) ((part-of :initform nil :initarg :part-of :accessor part-of))) (defclass g-circle (basic-thing 2d scaleable-thing sit-mixin filled-mixin) ((radius :initform 0 :accessor radius :initarg :radius))) (defclass g-rectangle (basic-thing 2d scale-and-rotateable-thing sit-mixin filled-mixin) ((xextend :initform 10 :accessor xextend :initarg :xextend) (yextend :initform 10 :accessor yextend :initarg :yextend))) (defclass g-text (basic-thing 2d ink-mixin) ((text-string :initform "Text" :accessor text-string :initarg :text-string) (face :initform :bold :initarg :face :accessor face) (size :initform :large :initarg :size :accessor size) (family :initform :sans-serif :initarg :family :accessor family))) (defclass g-polygon (basic-thing 2d scale-and-rotateable-thing object-with-handles pointlist-object sit-mixin filled-mixin) ()) (defclass g-arrow (basic-thing 1d rotateable-thing object-with-handles linesegment object-with-head sit-mixin directed-info-element) ()) (defclass g-chain (basic-thing 1d rotateable-thing pointlist-object object-with-handles object-with-head sit-mixin directed-info-element) ()) (defclass g-spline-chain (basic-thing spline-object 1d rotateable-thing pointlist-object object-with-handles object-with-head sit-mixin directed-info-element) ()) (defclass g-spline-polygon (basic-thing spline-object 2d scale-and-rotateable-thing pointlist-object object-with-handles sit-mixin filled-mixin) ()) ;;; ;;; ;;; (defmethod startpoint ((object pointlist-object)) (list (first (pointlist object)) (second (pointlist object)))) (defmethod endpoint ((object pointlist-object)) (last (pointlist object) 2)) ;;; ;;; ;;; (defmethod print-object ((object thing) stream) (format stream "~A = ~D" (first (parent-concepts object)) (id-number object))) (define-presentation-method present (object (type thing) stream (view textual-view) &key) (print-object object stream)) (define-presentation-method accept ((type thing) stream (view textual-view) &key) (with-application-frame (gened-frame) (with-slots (liste) gened-frame (completing-from-suggestions (stream) (dolist (elem liste) (suggest (print-object elem) elem)))))) ;;; ;;; ;;; (defun strange-polygon (object) (let ((pointlist (generate-brackets (pointlist object)))) (some #'(lambda (co1 co2 co3) (let* ((x1 (first co1)) (y1 (second co1)) (x2 (first co2)) (y2 (second co2)) (x3 (first co3)) (y3 (second co3))) (multiple-value-bind (d1 phi1) (distance-and-orientation x1 y1 x2 y2) (multiple-value-bind (d2 phi2) (distance-and-orientation x2 y2 x3 y3) (zerop (- (+ phi1 phi2) pi)))))) pointlist (cdr pointlist) (cddr pointlist)))) (defmethod strange-polygon-p ((object g-polygon)) (strange-polygon object)) (defmethod strange-polygon-p ((object g-spline-polygon)) (strange-polygon object)) ;;; ;;; ;;; (defmethod self-intersecting-p ((object pointlist-object)) (unless (<= (length (pointlist object)) 6) (let* ((pointlist (let ((brackets (generate-brackets (pointlist object)))) (if (or (typep object 'g-spline-polygon) (typep object 'g-polygon)) (append brackets (list (first brackets))) brackets))) (lines (mapcar #'(lambda (point1 point2) (let* ((p1 (make-geom-point (first point1) (second point1))) (p2 (make-geom-point (first point2) (second point2)))) (make-geom-line p1 p2))) pointlist (cdr pointlist)))) (some #'(lambda (l1) (let ((count (count-if #'(lambda (l2) (intersects l1 l2)) (remove l1 lines :test #'equal)))) (cond ((or (typep object 'g-polygon) (typep object 'g-spline-polygon)) (> count 2)) (t (or (and (eq l1 (first lines)) (> count 1)) (and (eq l1 (first (last lines))) (> count 1)) (> count 2)))))) lines)))) ;;; ;;; ;;; (defmethod object-ok-p ((object g-polygon)) (and (not (strange-polygon-p object)) (not (self-intersecting-p object)))) (defmethod object-ok-p ((object g-spline-polygon)) (and (not (strange-polygon-p object)) (not (self-intersecting-p object)))) (defmethod object-ok-p ((object pointlist-object)) (not (self-intersecting-p object))) (defmethod object-ok-p ((object linesegment)) (not (equal (startpoint object) (endpoint object)))) (defmethod object-ok-p ((object g-text)) (not (string= "" (text-string object)))) (defmethod object-ok-p ((object g-rectangle)) (not (or (zerop (xextend object)) (zerop (yextend object))))) (defmethod object-ok-p ((object g-circle)) (not (zerop (radius object)))) ;;; ;;; ;;; (defmethod set-init-extend ((object t)) ()) (defmethod set-init-extend ((object scaleable-thing)) (let ((*global-scaling* 1)) (multiple-value-bind (xf yf xt yt) (get-bounding-rect object) (setf (init-x-extend object) (- xt xf) (init-y-extend object) (- yt yf))))) ;;; ;;; ;;; (defmethod init-object-properties ((object t)) ()) (defmethod init-object-properties ((object basic-thing)) (get-bounding-rect object) (make-poly-representation object) (call-next-method)) (defmethod init-object-properties ((object composite-thing)) (multiple-value-bind (x y) (get-bounding-rect-center object) (multiple-value-bind (x y) (scale-mouse-position x y :inverse t) (setf (xtrans object) x (ytrans object) y))) (call-next-method)) (defmethod init-object-properties ((object scaleable-thing)) (set-init-extend object) (call-next-method)) (defmethod init-object-properties ((object linesegment)) (make-object-handles object (list (startpoint object) (endpoint object))) (call-next-method)) (defmethod init-object-properties ((object pointlist-object)) (unless (handles object) (make-object-handles object (generate-brackets (pointlist object) ))) (call-next-method)) (defmethod init-object-properties ((object g-spline-chain)) (setf (spline-points object) (mapcan #'identity (filter-to-close-together-out (reverse (make-spline (make-spline-chain-list (generate-brackets (pointlist object) )) 4)) 3.0))) (call-next-method)) (defmethod init-object-properties ((object g-spline-polygon)) (setf (spline-points object) (mapcan #'identity (filter-to-close-together-out (reverse (make-spline (make-spline-polygon-list (generate-brackets (pointlist object))) 4)) 3.0))) (call-next-method)) ;;; ;;; ;;; (defmethod initialize-instance :after ((object thing) &key) (when (initialize object) (with-application-frame (gened-frame) (unless (parent-concepts object) (setf (parent-concepts object) (list (type-of object)))) (setf (id-number object) (get-id-number))))) (defmethod initialize-instance :after ((object object-with-head) &key) (when (initialize object) (with-application-frame (gened-frame) (with-slots (default-arrow-head) gened-frame (setf (head object) default-arrow-head) (setf (parent-concepts object) (case (type-of object) (g-arrow (if (head object) '(g-arrow) '(g-line))) (g-chain (if (head object) '(g-directed-chain) '(g-chain))) (g-spline-chain (if (head object) '(g-directed-spline-chain) '(g-spline-chain))))))))) ;;; ;;; (defmethod initialize-instance :after ((object ink-mixin) &key) (when (initialize object) (with-application-frame (gened-frame) (with-slots (default-ink) gened-frame (setf (ink object) default-ink))))) (defmethod initialize-instance :after ((object filled-mixin) &key) (when (initialize object) (with-application-frame (gened-frame) (with-slots (default-filled default-filled-ink) gened-frame (setf (filledp object) default-filled) (setf (filled-ink object) default-filled-ink))))) (defmethod initialize-instance :after ((object linestyle-mixin) &key) (when (initialize object) (with-application-frame (gened-frame) (with-slots (default-line-style) gened-frame (setf (linestyle object) (decode-line-style object)))))) (defmethod initialize-instance :after ((object linethickness-mixin) &key) (when (initialize object) (with-application-frame (gened-frame) (with-slots (default-line-thickness) gened-frame (setf (linethickness object) default-line-thickness))))) ;;; ;;; (defmethod initialize-instance :after ((object g-text) &key) (if (initialize object) (with-application-frame (gened-frame) (with-slots (default-text-family default-text-face default-text-size) gened-frame (setf (family object) default-text-family) (setf (face object) default-text-face) (setf (size object) default-text-size))))) (defmethod initialize-instance :after ((object linesegment) &key) (if (initialize-handles object) (make-object-handles object (list (startpoint object) (endpoint object))))) (defmethod initialize-instance :after ((object pointlist-object) &key) (if (initialize-handles object) (make-object-handles object (generate-brackets (pointlist object)))))
15,561
Common Lisp
.lisp
420
32.545238
106
0.700806
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
5c2d0ef8571f24ad502fab3e9a458068ef62b11e9ef928d795246727eeefc333
11,185
[ -1 ]
11,186
copy.lisp
lambdamikel_GenEd/src/copy.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defmethod copy-values ((source-object t) (destination-object t)) ()) (defmethod copy-values ((source-object thing) (destination-object thing)) (with-slots (xtrans ytrans hidden parent-concepts id-number associated-classic-ind) destination-object (setf parent-concepts (parent-concepts source-object)) (setf xtrans (xtrans source-object)) (setf ytrans (ytrans source-object)) (setf hidden (hiddenp source-object)) (setf associated-classic-ind (associated-classic-ind source-object)) (setf id-number (get-id-number))) (call-next-method)) (defmethod copy-values ((source-object composite-thing) (destination-object composite-thing)) (with-slots (liste xtrans ytrans parent-concepts) source-object (dolist (elem (reverse liste)) (let ((object (make-instance (type-of elem) :initialize nil))) (copy-values elem object) (push object (liste destination-object)))) (call-next-method))) (defmethod copy-values ((source-object directed-info-element) (destination-object directed-info-element)) (with-slots (start-info-point end-info-point) source-object (let ((ps (make-instance 'info-point :initialize nil)) (pe (make-instance 'info-point :initialize nil))) (copy-values start-info-point ps) (copy-values end-info-point pe) (setf (id-number ps) (id-number start-info-point)) (setf (id-number pe) (id-number end-info-point)) (setf (start-info-point destination-object) ps) (setf (end-info-point destination-object) pe))) (call-next-method)) (defmethod copy-values ((source-object ink-mixin) (destination-object ink-mixin)) (with-slots (ink) destination-object (setf ink (ink source-object))) (call-next-method)) (defmethod copy-values ((source-object linestyle-mixin) (destination-object linestyle-mixin)) (with-slots (linestyle) destination-object (setf linestyle (linestyle source-object))) (call-next-method)) (defmethod copy-values ((source-object linethickness-mixin) (destination-object linethickness-mixin)) (with-slots (linethickness) destination-object (setf linethickness (linethickness source-object))) (call-next-method)) (defmethod copy-values ((source-object filled-mixin) (destination-object filled-mixin)) (with-slots (filledp filled-ink) destination-object (setf filledp (filledp source-object)) (setf filled-ink (filled-ink source-object)) (call-next-method))) (defmethod copy-values ((source-object g-rectangle) (destination-object g-rectangle)) (with-slots (xextend yextend) destination-object (setf xextend (xextend source-object)) (setf yextend (yextend source-object)) (call-next-method))) (defmethod copy-values ((source-object g-arrow) (destination-object g-arrow)) (call-next-method) (with-slots (startpoint endpoint) destination-object (make-object-handles destination-object (list startpoint endpoint)))) ;unschoen !!! (defmethod copy-values ((source-object linesegment) (destination-object linesegment)) (with-slots (startpoint endpoint) destination-object (setf startpoint (copy-list (startpoint source-object))) (setf endpoint (copy-list (endpoint source-object))) (call-next-method))) (defmethod copy-values ((source-object object-with-head) (destination-object object-with-head)) (setf (head destination-object) (head source-object)) (call-next-method)) (defmethod copy-values ((source-object pointlist-object) (destination-object pointlist-object)) (with-slots (pointlist) destination-object (setf pointlist (copy-list (pointlist source-object))) (make-object-handles destination-object (generate-brackets pointlist)) (call-next-method))) (defmethod copy-values ((source-object g-polygon) (destination-object g-polygon)) (call-next-method)) (defmethod copy-values ((source-object g-chain) (destination-object g-chain)) (call-next-method)) (defmethod copy-values ((source-object spline-object) (destination-object spline-object)) (with-slots (spline-points) destination-object (setf spline-points (copy-list (spline-points source-object)))) (call-next-method)) (defmethod copy-values ((source-object g-spline-chain) (destination-object g-spline-chain)) (call-next-method)) (defmethod copy-values ((source-object g-spline-polygon) (destination-object g-spline-polygon)) (call-next-method)) (defmethod copy-values ((source-object g-circle) (destination-object g-circle)) (with-slots (radius) destination-object (setf radius (radius source-object)) (call-next-method))) (defmethod copy-values ((source-object point) (destination-object point)) (call-next-method)) (defmethod copy-values ((source-object info-point) (destination-object info-point)) (setf (startpoint-of destination-object) (startpoint-of source-object)) (setf (endpoint-of destination-object) (endpoint-of source-object)) (call-next-method)) (defmethod copy-values ((source-object object-with-handles) (destination-object object-with-handles)) (call-next-method)) (defmethod copy-values ((source-object g-text) (destination-object g-text)) (with-slots (text-string face size family) destination-object (setf text-string (text-string source-object)) (setf face (face source-object)) (setf family (family source-object)) (setf size (size source-object)) (call-next-method))) (defmethod copy-values ((source-object scaleable-thing) (destination-object scaleable-thing)) (with-slots (xscale yscale init-x-extend init-y-extend) destination-object (setf xscale (xscale source-object)) (setf yscale (yscale source-object)) (setf init-x-extend (init-x-extend source-object)) (setf init-y-extend (init-y-extend source-object)) (call-next-method))) (defmethod copy-values ((source-object rotateable-thing) (destination-object rotateable-thing)) (with-slots (rotangle) destination-object (setf rotangle (rotangle source-object)) (call-next-method))) ;;; ;;; ;;; (defmethod copy-object ((source-object thing)) (with-application-frame (gened-frame) (with-slots (liste mode) gened-frame (let ((destination-object (make-instance (type-of source-object) :initialize nil))) (copy-values source-object destination-object) (translate-relative-object destination-object 10 10) (push destination-object liste) (make-undo-object destination-object 'copy) (tick-object destination-object) (do-incremental-updates))))) (define-gened-command (com-copy-object) ((source-object 'thing :gesture :copy)) (copy-object source-object)) (define-gened-command (com-gened-copy-object :name "Copy Object") () (if (any-visible-objects) (let ((source-object (accept 'thing))) (terpri) (copy-object source-object))))
6,923
Common Lisp
.lisp
149
42.442953
105
0.739604
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
5cdfe12aea5fe6c0753dfdaa185474d5d38e5a51adc877438b8c9e608bae4e29
11,186
[ -1 ]
11,187
cluster.lisp
lambdamikel_GenEd/src/cluster.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (define-gened-command (com-gened-build-cluster :name "Build Composite Object") () (when *info* (format t "~%Hold Shift & Left Mouse-Button~% And Drag A Rectangle Over Objects To Compose!~%Release Mouse-Button To Finish!~%")) (with-application-frame (gened-frame) (if (any-visible-objects) (with-slots (liste) gened-frame (let ((stream (get-frame-pane gened-frame 'display))) (multiple-value-bind (xf yf xt yt) (pointer-input-rectangle* :stream stream :finish-on-release t) (multiple-value-bind (xf yf) (scale-mouse-position xf yf :inverse t) (multiple-value-bind (xt yt) (scale-mouse-position xt yt :inverse t) (let ((rect (make-rectangle* xf yf xt yt)) (collect ())) (dolist (elem liste) (let ((xtrans (xtrans elem)) (ytrans (ytrans elem))) (when (region-contains-position-p rect xtrans ytrans) (push elem collect) (free-my-handles elem) (free-all-handles elem) (setf liste (delete elem liste :test #'equal))))) (if (not (null collect)) (let ((object (make-instance 'composite-thing :liste collect :initialize t))) (init-object-properties object) (push object liste) (make-undo-object object 'cluster) (do-incremental-updates)) (notify-user gened-frame "Nothing composed! OK?" :style :inform))))))))))) (defmethod atomize-cluster ((object composite-thing)) (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (elem (liste object)) (push elem liste)) (setf liste (delete object liste)) (when (attached-handles object) (dolist (handle (attached-handles object)) (free-handle handle)))))) ;;; ;;; ;;; (defun atomize-all-clusters () (with-application-frame (gened-frame) (with-slots (liste saved-liste) gened-frame (setf saved-liste (copy-list liste)) (dolist (elem liste) (setf (part-of-cluster elem) nil)) (loop (if (some #'(lambda (elem) (typep elem 'composite-thing)) liste) (dolist (cluster liste) (when (typep cluster 'composite-thing) (setf liste (delete cluster liste)) (dolist (cluster-part (liste cluster)) (push cluster-part liste) (setf (part-of-cluster cluster-part) cluster)))) (return)))))) (defun reinstall-all-clusters () (with-application-frame (gened-frame) (with-slots (liste saved-liste) gened-frame (if saved-liste (setf liste saved-liste))))) ;;; ;;; ;;; (define-gened-command (com-gened-atomize-cluster :name "Decompose Composite Object") () (if (any-visible-clusters) (let ((source-object (accept 'composite-thing))) (terpri) (atomize-cluster source-object) (do-incremental-updates)))) (define-gened-command (com-decompose-composite-object) ((object 'composite-thing :gesture :atomize)) (atomize-cluster object) (do-incremental-updates))
3,059
Common Lisp
.lisp
87
29.942529
133
0.666781
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
4971e224c72b450d40f12ca249cab9ba120a66973ec63ca1efacaad3332ed46c
11,187
[ -1 ]
11,188
gened-sysdcl.lisp
lambdamikel_GenEd/src/gened-sysdcl.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: CL-User; Base: 10 -*- (cl:in-package cl-user) (require "clim") (load "~/define-system.lisp") (setf (logical-pathname-translations "base") '(("**;*.*" "~/**/*.*"))) (setf (logical-pathname-translations "gened") (list '("sources;**;*.*" "base:gened;**;*.*") '("**;*.*" "base:gened;**;*.*"))) (define-system geometry (:default-pathname "gened:geometry;" :subsystem t) (:serial "newgeo13")) (define-system splines (:default-pathname "gened:splines;" :subsystem t) (:serial "spline3")) (define-system knowledge (:default-pathname "gened:knowledge;" :subsystem t) (:serial "knowledge7")) (define-system gened (:default-pathname "gened:sources;") (:serial "gened-packages" "values" "classesxx" "comtable" "frame2" (:parallel splines geometry) "helpaux" "polyrep" "transfor" "draw" "creator" "cluster" "handles" "inout" "copy" "spatial5" "inspect" "delete" "undo" "main" "rel-copy2" #+:classic "interface-to-classic3" #+:classic knowledge "concepts" "delta2" "init2")) (load-system 'gened :force-p t) (princ "(gened::gened)")
1,330
Common Lisp
.lisp
54
18.888889
76
0.5795
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
5ef9a0a53445322c62e73a5aafec77973bd5e8dd2ab812d18150a4553c722e9a
11,188
[ -1 ]
11,189
helpaux.lisp
lambdamikel_GenEd/src/helpaux.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defun calc-right-tres () (/ +tres-touch+ *global-scaling*)) ;;; ;;; ;;; (defun get-id-number () (incf *id-number*)) (defun min-max (liste) (values (apply #'min liste) (apply #'max liste))) (defun find-it (liste fn) (mapcan #'(lambda (x) (if (funcall fn x) (list x))) liste)) ;;; ;;; ;;; (defun interactive-master-creator (object updater-function &key (drawer-function #'(lambda (object stream) (draw object stream :handling-active t)))) (with-application-frame (gened-frame) (let ((stream (get-frame-pane gened-frame 'display))) (with-output-recording-options (stream :draw t :record nil) (funcall drawer-function object stream) (block track-pointer (tracking-pointer (stream) (:pointer-motion (x y) (multiple-value-bind (x y) (scale-mouse-position x y :inverse t) (funcall drawer-function object stream) (funcall updater-function x y) (funcall drawer-function object stream))) (:pointer-button-press (event) (funcall drawer-function object stream) (return-from track-pointer event)))))))) ;;; ;;; ;;; (defun generate-brackets (liste &optional (akku '())) (cond ((null liste) (reverse akku)) (t (generate-brackets (cddr liste) (cons (list (first liste) (second liste)) akku))))) (defun normalize-pointlist (pointlist) (let ((xlist) (ylist)) (dolist (elem pointlist) (push (first elem) xlist) (push (second elem) ylist)) (multiple-value-bind (xf xt) (min-max xlist) (multiple-value-bind (yf yt) (min-max ylist) (let* ((xtrans (/ (+ xf xt) 2)) (ytrans (/ (+ yf yt) 2)) (translist (mapcan #'(lambda (x y) (list (- x xtrans) (- y ytrans))) xlist ylist))) (values translist xtrans ytrans)))))) (defun draw-marker* (stream pointlist size &key (ink +foreground-ink+) (line-thickness 1) (line-dashes nil)) (loop (let ((x (first pointlist)) (y (second pointlist))) (draw-line* stream (- x size) (- y size) (+ x size) (+ y size) :ink ink :line-dashes line-dashes :line-thickness line-thickness) (draw-line* stream (- x size) (+ y size) (+ x size) (- y size) :ink ink :line-dashes line-dashes :line-thickness line-thickness) (setf pointlist (cddr pointlist)) (if (null pointlist) (return))))) ;;; ;;; ;;; (defun any-?-objects (function text-string) (with-application-frame (gened-frame) (with-slots (liste) gened-frame (let ((test (some function liste))) (if (not test) (notify-user gened-frame text-string :style :warning)) test)))) (defun any-fixed-handles () (any-?-objects #'attached-handles "No fixed handles at all!")) (defun any-unfixed-handles () (any-?-objects #'(lambda (elem) (if (typep elem 'object-with-handles) (not (every #'(lambda (handle) (typep handle 'fixed-object-handle)) (handles elem))))) "No unfixed handles at all!")) (defun any-visible-objects () (any-?-objects #'(lambda (x) (not (hiddenp x))) "No visible objects at all!")) (defun any-visible-directed-objects () (any-?-objects #'(lambda (x) (and (not (hiddenp x)) (typep x 'directed-info-element) (head x))) "No visible directed objects at all!")) (defun any-invisible-objects () (any-?-objects #'hiddenp "No invisible objects at all!")) (defun any-visible-clusters () (any-?-objects #'(lambda (x) (and (typep x 'composite-thing) (not (hiddenp x)))) "No visible clusters at all!")) (defun any-invisible-clusters () (any-?-objects #'(lambda (x) (and (typep x 'composite-thing) (hiddenp x))) "No invisible clusters at all!")) (defun any-scaleable-objects () (any-?-objects #'(lambda (x) (and (typep x 'scaleable-thing) (or (and (hiddenp x) (member 'hidden *global-display-options*)) (and (not (hiddenp x)) (member 'visible *global-display-options*))))) "No scaleable objects at all!")) (defun any-rotateable-objects () (any-?-objects #'(lambda (x) (and (typep x 'rotateable-thing) (or (and (hiddenp x) (member 'hidden *global-display-options*)) (and (not (hiddenp x)) (member 'visible *global-display-options*))))) "No rotateable objects at all!")) (defun any-visible-2d-objects () (any-?-objects #'(lambda (x) (and (typep x '2d) (not (hiddenp x)))) "No visible 2d-objects at all!"))
4,745
Common Lisp
.lisp
153
25.529412
89
0.618654
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
a91fafcf5d999acced11a3efb860666304901aebf18c0dd76df1de1f5eac4b85
11,189
[ -1 ]
11,190
spatial4.lisp
lambdamikel_GenEd/src/spatial4.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) (defparameter *accessor-table* (make-hash-table)) (defmacro define-relation-accessors (&rest names) `(progn (defparameter +relation-accessor-symbols+ ',names) (clrhash *accessor-table*) (dolist (name +relation-accessor-symbols+) (setf (gethash name *accessor-table*) (fdefinition `(setf ,name)))))) (defun find-accessor (name) (gethash name *accessor-table*)) ;;; ---------------------------------------------------------------------- (define-relation-accessors touching-objects intersects-objects intersects-0-objects intersects-1-objects intersects-2-objects contains-objects contained-in-objects directly-contains-objects directly-contained-by-object covers-objects covered-by-objects start-linked-over-with end-linked-over-with startpoint-related-with endpoint-related-with disjoint-with in-relation-with-objects) (defconstant +info-relation-accessor-symbols+ '( touching-objects intersects-objects intersects-0-objects intersects-1-objects intersects-2-objects contained-in-objects directly-contained-by-object covered-by-objects start-linked-over-with end-linked-over-with disjoint-with)) (defconstant +map-accessors-to-pretty-names+ '((touching-objects . (touches touches)) (intersects-objects . (intersects intersects)) (intersects-0-objects . (intersects>dim=0 intersects>dim=0)) (intersects-1-objects . (intersects>dim=1 intersects>dim=1)) (intersects-2-objects . (intersects>dim=2 intersects>dim=2)) (contained-in-objects . (is-inside contains)) (directly-contained-by-object . (directly-inside directly-contains)) (covered-by-objects . (covers is-covered-by)) (start-linked-over-with . (is-end-linked-over-with is-start-linked-over-with)) (end-linked-over-with . (is-start-linked-over-with is-end-linked-over-with)) (disjoint-with . (is-disjoint-with is-disjoint-with)))) (defconstant +map-relations-to-accessors+ '((touches . (touching-objects)) (intersects . (intersects-objects)) (intersects-0 . (intersects-0-objects intersects-objects)) (intersects-1 . (intersects-1-objects intersects-objects)) (intersects-2 . (intersects-2-objects intersects-objects)) (contains . (contained-in-objects)) (is-inside . (contains-objects)) (covers . (contained-in-objects covered-by-objects directly-contained-by-object)) (is-covered-by . (contains-objects covers-objects directly-contains-objects)) (is-disjoint-with . (disjoint-with)))) (defconstant +map-accessors-to-roles+ '((start-info-point . has-startpoint) (end-info-point . has-endpoint) (disjoint-with . disjoint-with) (start-linked-over-with . start-linked-over-with) (end-linked-over-with . end-linked-over-with) (in-relation-with-objects . in-relation-with-objects) (intersects-objects . intersects-objects) (intersects-0-objects . intersects-0-objects) (touching-objects . touching-objects) (contained-in-objects . contained-in-objects) (covered-by-objects . covered-by-object) ; richtig geschr.! (mal m. s, mal ohne!) (directly-contained-by-object . directly-contained-by-object) (intersects-1-objects . intersects-1-objects) (intersects-2-objects . intersects-2-objects) (contains-objects . contains) (directly-contains-objects . directly-contains-objects) (covers-objects . covers-objects))) (defun store-output-regions () (with-application-frame (gened-frame) (let ((stream (get-frame-pane gened-frame 'display)) (*bounding-boxes* t) (*handles-symbol-list* nil)) (with-slots (liste) gened-frame (dolist (object liste) (unless (typep object 'info-point) (let ((record (with-output-recording-options (stream :draw nil :record t) (with-output-to-output-record (stream) (draw object stream))))) (setf (output-record object) record)))))))) (defun get-accessor-function-from-name (symbol) (fdefinition `(setf ,symbol))) ;;; ;;; ;;; ;;; (defun clear-stored-relations (liste) (dolist (elem liste) (dolist (accessor +relation-accessor-symbols+) (when (slot-exists-p elem accessor) (funcall (find-accessor accessor) nil elem))))) (defun show-topo-info (elem1 elem2 relation stream) (multiple-value-bind (dist orient) (distance-and-orientation (xtrans elem1) (ytrans elem1) (xtrans elem2) (ytrans elem2)) (format stream "~% Relation:~% ~A~% ~A~% ~A.~%" elem1 relation elem2) (format stream "Polar-Distance: (~D | ~D)~%" (round dist) (round (* 180 (/ orient pi)))))) (defun find-all-cluster-elements (cluster) (if (typep cluster 'composite-thing) (let ((liste (liste cluster))) (mapcan #'find-all-cluster-elements liste)) (list cluster))) (defun make-all-disjoint (liste) (dolist (elem1 liste) (dolist (elem2 liste) (unless (eq elem1 elem2) (pushnew elem1 (disjoint-with elem2)))))) (defun remove-wrong-disjoints (liste) (dolist (elem1 liste) (dolist (elem2 liste) (if (and (not (eq elem1 elem2)) (member elem1 (in-relation-with-objects elem2))) (setf (disjoint-with elem2) (delete elem1 (disjoint-with elem2))))))) (defun remove-not-in-list (liste) (dolist (elem liste) (dolist (slot (set-difference +relation-accessor-symbols+ '(start-linked-over-with end-linked-over-with))) (when (slot-exists-p elem slot) (let ((content (funcall slot elem))) (dolist (rel-elem content) (unless (member rel-elem liste) (funcall (find-accessor slot) (delete rel-elem content) elem)))))) (dolist (slot '(start-linked-over-with end-linked-over-with)) (when (slot-exists-p elem slot) (let ((content (funcall slot elem))) (dolist (rel-elem content) ; Listen der Form : (object linker) (let ((object (first rel-elem)) (linker (second rel-elem))) (unless (and (member object liste) (member linker liste)) (funcall (find-accessor slot) (delete rel-elem content :test #'equalp) elem))))))))) (defun install-relations-for-clusters () (with-application-frame (gened-frame) (let ((stream (get-frame-pane gened-frame 'infos))) (with-slots (liste) gened-frame (dolist (cluster1 liste) (let ((elems-of-cluster1 (find-all-cluster-elements cluster1))) (dolist (cluster2 liste) (if (and (not (eq cluster1 cluster2)) (or (typep cluster1 'composite-thing) (typep cluster2 'composite-thing))) (let* ((elems-of-cluster2 (find-all-cluster-elements cluster2))) (cond ( (some #'(lambda (x) (some #'(lambda (y) (member y (intersects-objects x))) elems-of-cluster2)) elems-of-cluster1) (memoize-relation cluster1 cluster2 'intersects)) ( (and (some #'(lambda (x) (and (typep x '2d) (some #'(lambda (y) (member y (covers-objects x))) elems-of-cluster2))) elems-of-cluster1) (some #'(lambda (x) (and (typep x '2d) (every #'(lambda (y) (or (member y (contains-objects x)) (member y (covers-objects x)))) elems-of-cluster2))) elems-of-cluster1)) (memoize-relation cluster1 cluster2 'covers) (memoize-relation cluster2 cluster1 'is-covered-by)) ( (some #'(lambda (x) (and (typep x '2d) (every #'(lambda (y) (member y (contains-objects x))) elems-of-cluster2))) elems-of-cluster1) (memoize-relation cluster1 cluster2 'contains) (memoize-relation cluster2 cluster1 'is-inside)) ( (and (some #'(lambda (x) (some #'(lambda (y) (member y (touching-objects x))) elems-of-cluster2)) elems-of-cluster1) (not (some #'(lambda (x) (some #'(lambda (y) (and (member y (in-relation-with-objects x)) (not (member y (touching-objects x))) ; !!! nachdenken! )) elems-of-cluster2)) elems-of-cluster1))) (memoize-relation cluster1 cluster2 'touches)))))))))))) (defun memoize-relation (elem1 elem2 relation) (multiple-value-bind (dist orient) (distance-and-orientation (xtrans elem1) (ytrans elem1) (xtrans elem2) (ytrans elem2)) (unless (eq relation 'is-disjoint-with) (push elem1 (in-relation-with-objects elem2))) (dolist (accessor (rest (assoc relation +map-relations-to-accessors+))) (when (slot-exists-p elem2 accessor) (funcall (find-accessor accessor) (cons elem1 (funcall accessor elem2)) elem2))))) ;;; ;;; ;;; (defun store-infos-for-arrows-and-so () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (elem liste) (when (and (typep elem 'directed-info-element) (> (length (in-relation-with-objects elem)) 1)) (let ((startpoint (start-info-point elem)) (endpoint (end-info-point elem)) (related-start-object) (related-end-object)) (dolist (inter-elem (intersects-objects elem)) (when (typep inter-elem 'basic-thing) (when (member inter-elem (contained-in-objects startpoint)) (setf related-start-object inter-elem)) (when (member inter-elem (contained-in-objects endpoint)) (setf related-end-object inter-elem)))) (dolist (touch-elem (touching-objects elem)) (when (typep touch-elem 'basic-thing) (when (member startpoint (touching-objects touch-elem)) (setf related-start-object touch-elem)) (when (member endpoint (touching-objects touch-elem)) (setf related-end-object touch-elem)))) (dolist (cov-elem (covered-by-objects elem)) (when (typep cov-elem 'basic-thing) (when (member cov-elem (covered-by-objects startpoint)) (setf related-start-object cov-elem)) (when (member cov-elem (covered-by-objects endpoint)) (setf related-end-object cov-elem)))) (when (and related-start-object related-end-object) (push related-start-object (startpoint-related-with elem)) (push related-start-object (in-relation-with-objects related-end-object)) (push (list related-end-object elem) (end-linked-over-with related-start-object)) (push related-end-object (endpoint-related-with elem)) (when related-start-object (push related-end-object (in-relation-with-objects related-start-object)) (push (list related-start-object elem) (start-linked-over-with related-end-object)))))))))) (defun find-topmost-cluster (elem) (let ((cluster elem)) (loop (if (null (part-of-cluster cluster)) (return cluster) (setf cluster (part-of-cluster cluster)))))) #| (defun propagate-for-arrows-and-so (liste) (dolist (elem liste) (when (and (typep elem 'directed-info-element) (startpoint-related-with elem) (endpoint-related-with elem)) (let ((srw (startpoint-related-with elem)) (erw (endpoint-related-with elem))) (if (and srw erw) (let ((cluster srw)) (loop (setf cluster (mapcan #'(lambda (x) (if x (let ((part-of (part-of-cluster x))) (when part-of (list part-of))))) cluster)) (if cluster (dolist (elem2 cluster) (push elem2 (startpoint-related-with elem))) (return))) (let ((cluster erw)) (loop (setf cluster (mapcan #'(lambda (x) (if x (let ((part-of (part-of-cluster x))) (when part-of (list part-of))))) cluster)) (if cluster (dolist (elem2 cluster) (push elem2 (endpoint-related-with elem))) (return)))))))))) |# (defun propagate-for-arrows-and-so (liste) (dolist (elem liste) (when (and (typep elem 'directed-info-element) (startpoint-related-with elem) (endpoint-related-with elem)) (let ((srw (first (startpoint-related-with elem))) (erw (first (endpoint-related-with elem)))) (when (and srw erw) (let ((cluster1 (find-topmost-cluster srw)) (cluster2 (find-topmost-cluster erw))) (when (not (and (eq cluster1 srw) (eq cluster2 erw))) (push cluster1 (startpoint-related-with elem)) (push cluster2 (endpoint-related-with elem)) (push (list cluster1 elem) (start-linked-over-with cluster2)) (push cluster1 (in-relation-with-objects cluster2)) (push (list cluster2 elem) (end-linked-over-with cluster1)) (push cluster2 (in-relation-with-objects cluster1)) ))))))) (defun resolve-covering-conflicts (liste) (dolist (elem liste) (when (and (typep elem '2d)) (let ((cov-elems (covers-objects elem))) (when (> (length cov-elems) 1) (dolist (cov-elem cov-elems) (when (typep cov-elem '2d) (let* ((cov-cov-elems (covers-objects cov-elem)) (conflict-elem (find-if #'(lambda (X) (member x cov-elems)) cov-cov-elems))) (when conflict-elem (setf (covers-objects elem) (delete conflict-elem cov-elems)) (setf (covered-by-objects conflict-elem) (delete elem (covered-by-objects conflict-elem))) (setf (directly-contains-objects elem) (delete conflict-elem (directly-contains-objects elem))) (if (eq (first (directly-contained-by-object conflict-elem)) elem) (setf (directly-contained-by-object conflict-elem) nil)) (push conflict-elem (contains-objects elem)) (push elem (contained-in-objects conflict-elem)) ))))))))) (defun remove-cluster-parts (liste) (let ((liste2 liste)) (dolist (elem liste) (if (typep elem 'composite-thing) (setf liste2 (set-difference liste2 (liste elem))))) liste2)) (defun calculate-directly-containing (liste) (flet ((memoize (elem1 elem2) (pushnew elem2 (directly-contains-objects elem1)) (setf (directly-contained-by-object elem2) (list elem1)))) (dolist (elem liste) (let* ((contained-in-objects (remove-cluster-parts (remove-duplicates (contained-in-objects elem)))) (l (length contained-in-objects))) (dolist (elem2 contained-in-objects) #| (format t "~A in ~A ~A~%" elem contained-in-objects (contained-in-objects elem2) ) |# (when (or (and (typep elem2 'thing) (= (length (remove-cluster-parts (remove-duplicates (contained-in-objects elem2)))) (1- l))) nil) #| (format t "~A directly-contains ~A ~%" elem2 elem) |# (memoize elem2 elem))))))) (defun only-dublicates (liste &optional (akku nil)) (cond ((null liste) akku) (t (let* ((elem (first liste)) (relem (list (second elem) (first elem)))) (if (member relem liste :test #'equal) (only-dublicates (cdr (delete relem liste :test #'equal)) (cons elem akku)) (only-dublicates (cdr liste) akku)))))) (defun install-points (liste) (mapcan #'(lambda (elem) (if (typep elem 'directed-info-element) (list (start-info-point elem) (end-info-point elem) elem) (list elem))) liste)) (defun remove-points (liste) (remove-if #'(lambda (x) (typep x 'info-point)) liste)) (defun calc-relations () (with-application-frame (gened-frame) (with-slots (liste saved-liste calc-int-dim) gened-frame (clear-stored-relations liste) (setf liste (install-points liste)) (atomize-all-clusters) (store-output-regions) (clear-stored-relations liste) (dolist (elem1 liste) (dolist (elem2 liste) (unless (eq elem1 elem2) (if (or (typep elem1 'info-point) (typep elem2 'info-point) (not (eql +nowhere+ (region-intersection (output-record elem1) (output-record elem2))))) (let ((relation (relate-poly-to-poly-unary-tres (polygonized-representation elem1) (polygonized-representation elem2) (calc-right-tres) :dim calc-int-dim))) (progn #| (print relation) |# (memoize-relation elem1 elem2 relation))) (memoize-relation elem1 elem2 'is-disjoint-with)) ))) (resolve-covering-conflicts liste) (reinstall-all-clusters) (make-all-disjoint liste) (store-infos-for-arrows-and-so) (propagate-for-arrows-and-so liste) (calculate-directly-containing liste) (install-relations-for-clusters) (calculate-directly-containing liste) (remove-wrong-disjoints liste) (remove-not-in-list liste) (setf liste (remove-points liste)) (when *info* (show-infos))))) (define-gened-command (com-gened-show-relations :name "Show Relations") () (let ((*info* t)) (calc-relations))) (defun show-infos () (with-application-frame (gened-frame) (let ((stream (get-frame-pane gened-frame 'infos)) (mem-list nil)) (window-clear stream) (format stream "Hash-Table-Size: ~D~%" (hash-table-count geometry::*hash-table*)) (with-slots (liste) gened-frame (dolist (elem liste) (mapc #'(lambda (relation-accessor-symbol) (when (slot-exists-p elem relation-accessor-symbol) (let ((relation-symbols (rest (assoc relation-accessor-symbol +map-accessors-to-pretty-names+)))) (dolist (rel-elem (funcall (symbol-function relation-accessor-symbol) elem)) (let ((rel-elem (if (listp rel-elem) (first rel-elem) rel-elem))) (when (and (member rel-elem liste) (not (member (list (first relation-symbols) elem rel-elem) mem-list :test #'equal)) (not (member (list (second relation-symbols) elem rel-elem) mem-list :test #'equal))) (push (list (first relation-symbols) elem rel-elem) mem-list) (push (list (second relation-symbols) rel-elem elem) mem-list) (show-topo-info elem rel-elem (first relation-symbols) stream) (show-topo-info rel-elem elem (second relation-symbols) stream))))))) +info-relation-accessor-symbols+)))))) ;;; ;;; ;;; (defmethod show-map-over ((object thing) accessor) (with-application-frame (gened-frame) (with-slots (liste) gened-frame (unhighlight-all-objects) (dolist (elem (funcall accessor object)) (if (member elem liste) (highlight-object elem)))))) (define-gened-command (com-gened-show-touching :name "Show Touching Objects") () (if (any-visible-objects) (let ((object (accept '0d))) (show-map-over object #'touching-objects)))) (define-gened-command (com-show-touching :name "Show Touching Objects") ((object '0d :gesture nil)) (show-map-over object #'touching-objects)) ;;; ;;; (define-gened-command (com-gened-show-intersecting :name "Show Intersecting Objects") () (if (any-visible-objects) (let ((object (accept '0d))) (show-map-over object #'intersects-objects)))) (define-gened-command (com-show-intersecting :name "Show Intersecting Objects") ((object '0d :gesture nil)) (show-map-over object #'intersects-objects)) ;;; ;;; (define-gened-command (com-gened-show-contained :name "Show Contained In Objects") () (if (any-visible-objects) (let ((object (accept '0d))) (show-map-over object #'contained-in-objects)))) (define-gened-command (com-show-contained :name "Show Contained In Objects") ((object '0d :gesture nil)) (show-map-over object #'contained-in-objects)) ;;; ;;; (define-gened-command (com-gened-show-containing :name "Show Containing Objects") () (if (any-visible-2d-objects) (let ((object (accept '2d))) (show-map-over object #'contains-objects)))) (define-gened-command (com-show-containing :name "Show Containing Objects") ((object '2d :gesture nil)) (show-map-over object #'contains-objects)) ;;; ;;; (define-gened-command (com-gened-show-directly-contained :name "Show Directly Contained In Object") () (if (any-visible-objects) (let ((object (accept '0d))) (show-map-over object #'directly-contained-by-object)))) (define-gened-command (com-show-directly-contained :name "Show Directly Contained In Object") ((object '0d :gesture nil)) (show-map-over object #'directly-contained-by-object)) ;;; ;;; (define-gened-command (com-gened-show-directly-containing :name "Show Directly Containing Objects") () (if (any-visible-2d-objects) (let ((object (accept '2d))) (show-map-over object #'directly-contains-objects)))) (define-gened-command (com-show-directly-containing :name "Show Directly Containing Objects") ((object '2d :gesture nil)) (show-map-over object #'directly-contains-objects)) ;;; ;;; (define-gened-command (com-gened-show-covered :name "Show Covered By Objects") () (if (any-visible-objects) (let ((object (accept '0d))) (show-map-over object #'covered-by-objects)))) (define-gened-command (com-show-covered :name "Show Coverd By Objects") ((object '0d :gesture nil)) (show-map-over object #'covered-by-objects)) ;;; ;;; (define-gened-command (com-gened-show-covering :name "Show Covering Objects") () (if (any-visible-2d-objects) (let ((object (accept '2d))) (show-map-over object #'covers-objects)))) (define-gened-command (com-show-covering :name "Show Covering Objects") ((object '2d :gesture nil)) (show-map-over object #'covers-objects)) ;;; ;;; (define-gened-command (com-gened-show-disjoint :name "Show Disjoint Objects") () (if (any-visible-objects) (let ((object (accept '0d))) (show-map-over object #'disjoint-with)))) (define-gened-command (com-show-disjoint :name "Show Disjoint Objects") ((object '0d :gesture nil)) (show-map-over object #'disjoint-with)) ;;; ;;; (define-gened-command (com-gened-show-related :name "Show Related Objects") () (if (any-visible-objects) (let ((object (accept '0d))) (show-map-over object #'in-relation-with-objects)))) (define-gened-command (com-show-related :name "Show Related Objects") ((object '0d :gesture nil)) (show-map-over object #'in-relation-with-objects)) ;;; ;;; (define-gened-command (com-gened-show-linked :name "Show Linked Objects") () (when (any-visible-objects) (let* ((object (accept 'directed-info-element))) (unhighlight-all-objects) (highlight-object (first (endpoint-related-with object))) (highlight-object (first (startpoint-related-with object)))))) (define-gened-command (com-gened-show-start-linked :name "Show Start-Linked Objects") () (when (any-visible-directed-objects) (let ((object (accept 'directed-info-element))) (unhighlight-all-objects) (highlight-object (first (startpoint-related-with object)))))) (define-gened-command (com-gened-show-end-linked :name "Show End-Linked Objects") () (when (any-visible-directed-objects) (let ((object (accept 'directed-info-element))) (unhighlight-all-objects) (highlight-object (first (endpoint-related-with object)))))) ;;; ;;; ...-linked-over-with : (object linker) ;;; (define-gened-command (com-gened-show-opposite :name "Show Opposite Objects") () (when (any-visible-objects) (let ((object (accept '0d))) (unhighlight-all-objects) (mapc #'(lambda (x) (highlight-object (first x))) (append (start-linked-over-with object) (end-linked-over-with object)))))) ;;;; (define-gened-command (com-gened-show-linker :name "Show Linker Objects") () (when (any-visible-objects) (let ((object (accept '0d))) (unhighlight-all-objects) (mapc #'(lambda (x) (highlight-object (second x))) (append (start-linked-over-with object) (end-linked-over-with object))))))
24,712
Common Lisp
.lisp
647
31.384853
99
0.651967
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
84459f30883cba6cd598206a97d1c4e894de7e3b75525f0b6092b2053bd63ab9
11,190
[ -1 ]
11,191
gened-packages.lisp
lambdamikel_GenEd/src/gened-packages.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: CL-User; Base: 10 -*- (cl:in-package cl-user) (defpackage geometry (:use common-lisp) (:export :make-geom-polygon :make-geom-point :make-geom-line :get-points :intersects :intersects-0 :intersects-1 :intersects-2 :distance-between :inside :covers :covers-tres :touching-tres :inverse :distance-and-orientation :clear-hashtable :delete-object-from-cache :relate-poly-to-poly-unary-tres :tickval :is-disjoint-with :touches :is-inside :contains :is-covered-by)) (defpackage splines (:use common-lisp) (:export :make-spline :make-spline-chain-list :make-spline-polygon-list :filter-to-close-together-out)) (defpackage knowledge (:use #+:classic classic #+:classic krss-classic common-lisp) (:export #| Konzepte |# :gened-thing :g-circle :g-rectangle :g-arrow :g-line :g-chain :g-directed-chain :g-spline-chain :g-directed-spline-chain :g-polygon :g-text :g-spline-polygon :g-point :info-point :basic-thing :composite-thing #| Rollen |# :spatial-relation ; keine Inverse :in-relation-with-objects ; keine Inverse :disjoint-with ; selbstinvers :touching-objects ; selbstinvers :intersects-objects ; selbstinvers :intersects-0-objects ; selbstinvers :intersects-1-objects ; selbstinvers :intersects-2-objects ; selbstinvers :contains-objects :contained-in-objects :directly-contains-objects :directly-contained-by-object :covers-objects :covered-by-object :linked-over-with ; selbstinvers :start-linked-over-with :end-linked-over-with :linker-objects :points-related-with :start-linker-objects :startpoint-related-with :end-linker-objects :endpoint-related-with :has-parts :part-of :has-points :point-part-of :has-startpoint :startpoint-part-of-directed-element :has-endpoint :endpoint-part-of-directed-element ;;; Attribute :belongs-to-clos-object :filled-bool :radius-real :text-string :xtrans-integer :ytrans-integer #| Bibliothek |# :+known-concepts+ :+library-concepts+ :+known-roles+)) (defpackage gened (:use clim-lisp clim splines knowledge #+:classic classic #+:classic krss-classic geometry) #+:classic (:shadowing-import-from classic pathname) ;(:shadowing-import-from cl-user ; output-record )
2,683
Common Lisp
.lisp
114
18.017544
76
0.686722
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
6aea5e071a0e30d34c82ad237cb3c3e730e0be1b3a2a3ebab0cfb7f5cb84e9b7
11,191
[ -1 ]
11,192
inspect.lisp
lambdamikel_GenEd/src/inspect.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defmethod get-dialog-closure ((object t) stream) (declare (ignore stream)) #'(lambda ())) (defmethod get-dialog-closure ((object thing) stream) #'(lambda () (with-slots (xtrans ytrans hidden) object (formatting-cell (stream :align-x :center) (setf xtrans (accept 'integer :stream stream :view 'gadget-dialog-view :default xtrans :prompt " X")) (terpri stream) (setf ytrans (accept 'integer :stream stream :view 'gadget-dialog-view :default ytrans :prompt " Y")) (terpri stream)) (formatting-cell (stream :align-x :center) (setf hidden (accept 'boolean :stream stream :view 'gadget-dialog-view :default hidden :prompt "Hidden")) (terpri stream)) (funcall (call-next-method))))) (defmethod get-dialog-closure ((object ink-mixin) stream) #'(lambda () (with-slots (ink) object (formatting-cell (stream :align-x :center) (setf ink (accept 'ink :stream stream :view 'gadget-dialog-view :default ink :prompt "Ink")) (terpri stream))) (funcall (call-next-method)))) (defmethod get-dialog-closure ((object g-text) stream) #'(lambda () (with-slots (text-string face size family) object (formatting-cell (stream :align-x :center) (setf text-string (accept 'string :stream stream :view 'gadget-dialog-view :default text-string :prompt "Text"))) (terpri stream) (formatting-cell (stream :align-x :center) (let ((style (accept 'p-text-style :stream stream :view 'gadget-dialog-view :default (list family face) :prompt "Text-Style"))) (setf family (first style)) (setf face (second style)))) (terpri stream) (formatting-cell (stream :align-x :center) (let ((text-size (accept 'p-text-size :stream stream :view 'gadget-dialog-view :default size :prompt "Text-Size"))) (setf size text-size)))) (funcall (call-next-method)))) (defmethod get-dialog-closure ((object linestyle-mixin) stream) #'(lambda () (with-slots (linestyle) object (formatting-cell (stream :align-x :center) (let ((object (accept 'line-style-type :stream stream :view 'gadget-dialog-view :default (encode-line-style linestyle) :prompt "Style "))) (setf linestyle (decode-line-style object))) (terpri stream)) (funcall (call-next-method))))) (defmethod get-dialog-closure ((object linethickness-mixin) stream) #'(lambda () (with-slots (linethickness) object (formatting-cell (stream :align-x :center) (setf linethickness (accept 'line-thickness :stream stream :view 'gadget-dialog-view :default linethickness :prompt "Thickness")) (terpri stream)) (funcall (call-next-method))))) (defmethod get-dialog-closure ((object filled-mixin) stream) #'(lambda () (with-slots (filledp filled-ink) object (formatting-cell (stream :align-x :center) (setf filled-ink (accept 'ink :stream stream :view 'gadget-dialog-view :default filled-ink :prompt "Filled-Ink")) (terpri stream)) (formatting-cell (stream :align-x :center) (setf filledp (accept 'boolean :stream stream :view 'gadget-dialog-view :default filledp :prompt "Filled")) (terpri stream))) (funcall (call-next-method)))) (defmethod get-dialog-closure ((object rotateable-thing) stream) #'(lambda () (with-slots (rotangle) object (formatting-cell (stream :align-x :center) (let ((object (accept 'real :stream stream :view 'gadget-dialog-view :default (* 180 (/ rotangle pi)) :prompt "Angle"))) (setf rotangle (* pi (/ object 180)))) (terpri stream)) (funcall (call-next-method))))) (defmethod get-dialog-closure ((object scaleable-thing) stream) #'(lambda () (with-slots (xscale yscale) object (formatting-cell (stream :align-x :center) (setf xscale (accept 'real :stream stream :view 'gadget-dialog-view :default xscale :prompt " X-Scale")) (terpri stream) (setf yscale (accept 'real :stream stream :view 'gadget-dialog-view :default yscale :prompt " Y-Scale")) (terpri stream)) (funcall (call-next-method))))) (defmethod get-dialog-closure ((object linesegment) stream) #'(lambda () (with-slots (startpoint endpoint) object (formatting-cell (stream :align-x :center) (setf startpoint (accept '(sequence-enumerated integer integer) :stream stream :view 'gadget-dialog-view :default startpoint :prompt " Start")) (terpri stream) (setf endpoint (accept '(sequence-enumerated integer integer) :stream stream :view 'gadget-dialog-view :default endpoint :prompt " End")) (terpri stream)) (funcall (call-next-method))))) (defmethod get-dialog-closure ((object object-with-head) stream) #'(lambda () (with-slots (head) object (formatting-cell (stream :align-x :center) (setf head (accept 'boolean :stream stream :view 'gadget-dialog-view :default head :prompt " Arrow-Head")) (adjust-parent-concept object) (terpri stream))) (funcall (call-next-method)))) (defmethod get-dialog-closure ((object g-circle) stream) #'(lambda () (with-slots (radius) object (formatting-cell (stream :align-x :center) (setf radius (accept 'integer :stream stream :view 'gadget-dialog-view :default radius :prompt "Radius")) (terpri stream)) (funcall (call-next-method))))) (defmethod get-dialog-closure ((object g-rectangle) stream) #'(lambda () (with-slots (xextend yextend) object (formatting-cell (stream :align-x :center) (setf xextend (accept 'integer :stream stream :view 'gadget-dialog-view :default xextend :prompt " X-Ext")) (terpri stream) (setf yextend (accept 'integer :stream stream :view 'gadget-dialog-view :default yextend :prompt " Y-Ext")) (terpri stream)) (funcall (call-next-method))))) ;;; ;;; ;;; (defmethod inspect-object ((object thing)) (make-undo-object object 'inspect) (with-application-frame (gened-frame) (let ((stream (get-frame-pane gened-frame 'display))) (accepting-values (stream :own-window t :label "Inspector") (terpri stream) (formatting-table (stream :y-spacing '(1 :character) :x-spacing '(2 :character)) (formatting-column (stream) (funcall (get-dialog-closure object stream))))))) (adjust-object-origin object) (tick-object object) (do-incremental-updates)) (define-gened-command (com-inspect-object) ((object 'thing :gesture :inspect)) (inspect-object object)) (define-gened-command (com-gened-inspect-object :name "Inspect Object") () (if (any-visible-objects) (let ((source-object (accept 'thing))) (terpri) (inspect-object source-object))))
6,817
Common Lisp
.lisp
187
31.967914
74
0.683802
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
6871138b8741d98742cc687a4194f929b20876ab4d605bf7a30459f9e7f1db83
11,192
[ -1 ]
11,193
frame2.lisp
lambdamikel_GenEd/src/frame2.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; #+(or mcl lispworks) (defmacro outl (&body body) `(spacing (:thickness 2) (outlining (:thickness 2) (spacing (:thickness 2) ,@body)))) (defmacro with-centering ((stream) &body body) (let ((x (gensym))) `(multiple-value-bind (,x) (window-inside-size ,stream) (formatting-table (stream) (formatting-row (stream) (formatting-cell (stream :align-x :center :align-y :center :min-width ,x) ,@body))) (terpri stream)))) (defmacro with-border ((stream &key (offset 0)) &body body) (let ((or (gensym))) `(let ((,or (with-output-to-output-record (,stream) ,@body))) (draw-rectangle* ,stream (- (bounding-rectangle-min-x ,or) ,offset) (- (bounding-rectangle-min-y ,or) ,offset) (+ (bounding-rectangle-max-x ,or) ,offset) (+ (bounding-rectangle-max-y ,or) ,offset) :line-dashes '(1 1) :filled nil) ,@body))) (define-application-frame gened () ( (liste :initform nil) (stored-relations :initform nil) (saved-liste :initform nil) (prev-op-liste :initform nil) (mode :initform 'g-circle) (concept-type :initform nil) (calc-int-dim :initform nil) (inc-mode :initform nil) (default-arrow-head :initform t) (default-line-thickness :initform 2) (default-line-style :initform :solid) (default-ink :initform 0.4) (default-text-family :initform :sans-serif) (default-text-face :initform :bold) (default-text-size :initform :normal) (default-filled-ink :initform 0.8) (default-filled :initform nil) (buffer-counter :initform 0) (object-copy-buffer :initform (make-array +buffer-size+))) (:command-table (gened :inherit-from (accept-values-pane concept-table file-table tool-table manipulate-table reasoning-table spatial-table) :menu (("File" :menu file-table) ("Tools" :menu tool-table) ("Manipulate" :menu manipulate-table) ("Reasoning" :menu reasoning-table) ("Concepts" :menu concept-table) ("Spatial" :menu spatial-table)))) (:pointer-documentation t) (:panes (display :application :display-function 'draw-gened :textcursor nil :scroll-bars nil :min-width 800 :redisplay-after-commands nil :incremental-redisplay t) (label :application :scroll-bars nil :redisplay-after-commands nil :incremental-redisplay nil :display-function 'draw-label :height 136 :width 250 :foreground +white+ :background +black+) (infos :application :textcursor nil :text-style (parse-text-style '(:sans-serif :roman :very-small)) :end-of-line-action :allow :scroll-bars :both) #+:ignore (command :interactor :Height '(4 :line)) (options :accept-values :scroll-bars nil :height 40 :text-style (parse-text-style '(:sans-serif :roman :small)) :display-function `(accept-values-pane-displayer :displayer ,#'(lambda (frame stream) (accept-options frame stream)))) (elements :accept-values :scroll-bars nil :height 80 :text-style (parse-text-style '(:sans-serif :roman :small)) :display-function `(accept-values-pane-displayer :displayer ,#'(lambda (frame stream) (accept-elements frame stream)))) (buttons :accept-values ;:scroll-bars :vertical :width 80 :scroll-bars nil :text-style (parse-text-style '(:sans-serif :roman :small)) :display-function `(accept-values-pane-displayer :displayer ,#'(lambda (frame stream) (accept-buttons frame stream))))) (:layouts (:default (horizontally () (4/5 (vertically () (outl elements) (outl options) (horizontally () (1/4 buttons) (3/4 (outl display))))) (1/5 (vertically () (outl label) (outl infos))))))) #| (defmethod read-frame-command ((frame gened) &key (stream *standard-input*)) (read-command (frame-command-table frame) :use-keystrokes t :stream stream)) |# (defun accept-it (stream type default prompt query-id &key (min-width 0) (min-height 0) orientation (view +textual-dialog-view+)) (let (object ptype changed) (formatting-cell (stream :align-x (ecase orientation (:horizontal :left) (:vertical :center)) :align-y :center :min-width min-width :min-height min-height) (multiple-value-setq (object ptype changed) (accept type :stream stream :default default :query-identifier query-id :prompt prompt ;; Get the graphical representation instead of gadgets :view view ))) (values object changed))) (defmethod accept-elements ((frame gened) stream &key &allow-other-keys) (with-slots (mode) frame (flet ((accept (stream type default prompt query-id) (let (object ptype changed) (formatting-cell (stream :align-x (ecase :horizontal (:horizontal :center) (:vertical :left))) (multiple-value-setq (object ptype changed) (accept type :stream stream :default default :query-identifier query-id :prompt prompt ;; Get the graphical representation instead of gadgets :view +textual-dialog-view+))) ptype (values object changed)))) (declare (dynamic-extent #'accept)) (terpri stream) (formatting-table (stream) (formatting-row (stream) (formatting-cell (stream :align-x :center) (let ((element (accept stream 'g-elements mode "Element" 'element))) (setf mode element)))))))) (define-presentation-type-abbreviation g-elements () `((member g-concept g-circle g-rectangle g-arrow g-chain g-spline-chain g-polygon g-spline-polygon g-text g-point) :name-key identity :printer present-elements :highlighter highlight-element)) (defun present-elements (object stream &rest args) (let ((*concept-labels* nil) (*handles-symbol-list* nil) (*bounding-boxes* nil) (*origins* nil) (*global-scaling* 0.7)) (draw (second (assoc object *sample-graphic-objects*)) stream))) (defun highlight-element (continuation object stream) (surrounding-output-with-border (stream) (funcall continuation object stream))) (defmethod accept-options ((frame gened) stream) (with-slots (default-line-style default-line-thickness default-ink default-arrow-head default-filled mode default-filled-ink default-text-family default-text-face default-text-size) frame (flet ((do-body1 (stream) (multiple-value-bind (real) (accept-it stream 'ink default-ink "Ink" 'ink1 :orientation :horizontal) (setf default-ink real) (multiple-value-bind (thickness) (accept-it stream 'line-thickness default-line-thickness "Thickness" 'thickness :orientation :horizontal) (setf default-line-thickness thickness) (multiple-value-bind (line-style) (accept-it stream 'line-style-type default-line-style "Style" 'style :orientation :horizontal) (setf default-line-style line-style)) (multiple-value-bind (bool) (accept-it stream 'boolean default-arrow-head "Head " 'head :orientation :horizontal) (setf default-arrow-head bool))))) (do-body2 (stream) (multiple-value-bind (real) (accept-it stream 'ink default-filled-ink "Ink" 'ink2 :orientation :horizontal) (setf default-filled-ink real) (multiple-value-bind (text-style) (accept-it stream 'p-text-style (list default-text-family default-text-face) "Style" 'text-style :orientation :horizontal) (setf default-text-family (first text-style)) (setf default-text-face (second text-style)) (multiple-value-bind (text-size) (accept-it stream 'p-text-size default-text-size "Size" 'text-size :orientation :horizontal) (setf default-text-size text-size) (multiple-value-bind (bool) (accept-it stream 'boolean default-filled "Filled" 'filled :orientation :horizontal) (setf default-filled bool)))))) (accept-element (stream) (let ((element (accept-it stream 'g-elements mode "Element" 'element :orientation :horizontal))) (setf mode element)))) (formatting-table (stream) (formatting-row (stream) (do-body1 stream)) (formatting-row (stream) (do-body2 stream)))))) ;;; ;;; ;;; (defun get-symbol-list () (with-application-frame (gened-frame) (with-slots (calc-int-dim inc-mode) gened-frame (append (when *bounding-boxes* (list 'boxes)) (when *origins* (list 'origins)) (when *info* (list 'infos)) (when *pretty-hl* (list 'pretty)) (when calc-int-dim (list 'dimensions)) (when inc-mode (list 'incremental)) (when *classic-warnings* (list 'warnings)))))) (defun text-cell (stream format-string &key (orientation :center)) (formatting-cell (stream :align-x orientation) (write-string format-string stream) (write-string " " stream))) (defmethod accept-buttons ((frame gened) stream &key (orientation :vertical)) (with-slots (calc-int-dim inc-mode) frame (let ((last-symbol-list (get-symbol-list))) (with-centering (stream) (formatting-table (stream :y-spacing '(1 :character)) (flet ((do-body (stream) (text-cell stream "Global Display Options:") (multiple-value-bind (symbol-list changed0p) (accept-it stream '(subset-completion (VISIBLE HIDDEN PRIMITIVE COMPOSITE)) *global-display-options* nil 'global-display-options :orientation orientation :view 'list-pane-view) (setf *global-display-options* symbol-list) (text-cell stream "Object Display Options:") (multiple-value-bind (symbol-list changed1p) (accept-it stream '(subset-completion (INTERIOR BORDER)) (list (if *global-border* 'BORDER) (if *global-filled* 'INTERIOR)) nil 'object-display-options :orientation orientation :view 'list-pane-view) (setf *global-filled* (and (member 'INTERIOR symbol-list) t) *global-border* (and (member 'BORDER symbol-list) t)) (text-cell stream "Object Handle Options:") (multiple-value-bind (symbol-list changed2p) (accept-it stream `(subset-completion (NORMAL FIXED UNFIXED START END)) *handles-symbol-list* nil 'handles :orientation orientation :view 'list-pane-view) (setf *handles-symbol-list* symbol-list) (text-cell stream "Global Display Scaling:") (multiple-value-bind (number changed3p) (accept-it stream `(completion (1/2 1 2)) *global-scaling* nil 'gs :view 'list-pane-view :orientation orientation) (setf *global-scaling* number) (text-cell stream "Concept Label Options:") (multiple-value-bind (symbol-list changed4p) (accept-it stream '(subset-completion (IDs PARENTS ANCESTORS)) *concept-labels* nil 'labels :view 'list-pane-view :orientation orientation) (setf *concept-labels* symbol-list) (text-cell stream "Others:") (multiple-value-bind (symbol-list changed5p) (accept-it stream '(subset-completion (Boxes Origins Pretty Infos Warnings Dimensions Incremental)) (get-symbol-list) nil 'others :orientation orientation :view 'list-pane-view) (setf *pretty-hl* (member 'pretty symbol-list)) (setf *bounding-boxes* (member 'boxes symbol-list)) (setf *origins* (member 'origins symbol-list)) (setf *info* (member 'infos symbol-list)) #+:classic (setf *classic-warnings* (member 'warnings symbol-list)) #+:classic (set-classic-infos *classic-warnings*) (setf calc-int-dim (member 'dimensions symbol-list)) (setf inc-mode (member 'incremental symbol-list)) (when (or changed0p changed1p changed2p changed3p changed4p changed5p) (when changed5p (when (or (and (member 'dimensions symbol-list) (not (member 'dimensions last-symbol-list))) (and (not (member 'dimensions symbol-list)) (member 'dimensions last-symbol-list))) (clear-hashtable) (do-incremental-updates)) (when (or (and (member 'incremental symbol-list) (not (member 'incremental last-symbol-list))) (and (not (member 'incremental symbol-list)) (member 'incremental last-symbol-list))) (when inc-mode #+:classic (clear-knowledge-base) (do-incremental-updates)))) (if changed3p (progn (tick-all-objects) (do-incremental-updates)) (only-tick-all-objects))))))))))) (ecase orientation (:horizontal (formatting-row (stream) (do-body stream))) (:vertical (formatting-column (stream) (do-body stream)))))))))) ;;; ;;; ;;; (define-presentation-type line-thickness () :inherit-from '((completion (1 2 3 4)) :name-key identity :printer present-line-thickness :highlighter highlight-line-thickness )) (defun present-line-thickness (object stream &rest args) (let ((y (stream-line-height stream))) (with-room-for-graphics (stream) (draw-rectangle* stream 0 2 13 (- y 2) :filled nil :ink +background-ink+) (draw-line* stream 0 (floor y 2) 13 (floor y 2) :line-thickness object)))) (defun highlight-line-thickness (continuation object stream) (surrounding-output-with-border (stream) (funcall continuation object stream))) ;;; ;;; ;;; (define-presentation-type line-style-type () :inherit-from `((completion (:solid :pattern1 :pattern2 :pattern3)) :name-key identity :printer present-line-style :highlighter highlight-line-style)) (defun decode-line-style (object) (second (assoc object +line-pattern-list+))) (defun encode-line-style (object) (first (rassoc (list object) +line-pattern-list+ :test #'equal))) (defun present-line-style (object stream &rest args) (let ((y (stream-line-height stream))) (with-room-for-graphics (stream) (draw-rectangle* stream 0 2 11 (- y 2) :filled nil :ink +background-ink+) (draw-line* stream 0 (floor y 2) 11 (floor y 2) :line-dashes (decode-line-style object))))) (defun highlight-line-style (continuation object stream) (surrounding-output-with-border (stream) (funcall continuation object stream))) ;;; ;;; ;;; (define-presentation-type ink () :inherit-from '((completion (0.4 0.6 0.8 0.9)) :name-key identity :printer present-ink)) (defun present-ink (object stream &rest args) (let ((y (stream-line-height stream))) (with-room-for-graphics (stream) (draw-rectangle* stream 0 2 8 (- y 2) :filled t :ink (make-gray-color object))))) ;;; ;;; ;;; (define-presentation-type p-text-style () :inherit-from `((completion ((:sans-serif :bold) (:serif :italic) (:sans-serif nil) (:fix :bold)) :test equalp) :name-key identity :printer present-text-style)) (defun present-text-style (object stream &rest args) (let ((text-style (parse-text-style (append object '(:very-small))))) (with-text-style (stream text-style) (draw-text* stream "A" 0 0 :ink +black+)))) (define-presentation-type p-text-size () :inherit-from '((completion (:tiny :very-small :normal :very-large :huge)) :name-key identity :printer present-text-size)) (defun present-text-size (object stream &rest args) (case object (:tiny (write-string "T" stream)) (:very-small (write-string "S" stream)) (:normal (write-string "N" stream)) (:very-large (write-string "L" stream)) (:huge (write-string "H" stream)))) ;;; ;;; ;;; (define-presentation-type-abbreviation g-elements () `((member g-concept g-circle g-rectangle g-arrow g-chain g-spline-chain g-polygon g-spline-polygon g-text g-point) :name-key identity :printer present-elements :highlighter highlight-element)) (defun present-elements (object stream &rest args) (let ((*concept-labels* nil) (*handles-symbol-list* nil) (*bounding-boxes* nil) (*origins* nil) (*global-border* t) (*global-scaling* 1.0)) (draw (second (assoc object *sample-graphic-objects*)) stream))) (defun highlight-element (continuation object stream) (surrounding-output-with-border (stream) (funcall continuation object stream))) ;;; ;;; ;;; (defmethod run-frame-top-level :before ((frame gened) &key) (initialize-gened frame)) #| (defmethod frame-standard-input ((frame gened)) (get-frame-pane frame 'command)) |# (defmethod frame-standard-output ((frame gened)) (get-frame-pane frame 'infos)) (defmethod initialize-gened ((frame gened)) (load-concepts) (load-label-object) (setf *current-file* "NONAME") (setf *global-scaling* 1) (setf *cl-error-msg-stream* (get-frame-pane frame 'infos)) (setf *cl-warn-msg-stream* (get-frame-pane frame 'infos)) #+:classic (cl-set-classic-error-mode nil) #+:classic (setf *classic-print-right-margin* 40)) #+:classic (defun set-classic-infos (bool) (cl-set-classic-warn-mode bool)) (defmethod frame-error-output ((frame gened)) (get-frame-pane frame 'infos)) (defun clear-info-pane () (with-application-frame (gened-frame) (let ((stream (get-frame-pane gened-frame 'infos))) (window-clear stream)))) ;;; ;;; ;;; (defmethod draw-label ((frame gened) stream &key max-width max-height) (declare (ignore max-width max-height)) (updating-output (stream :unique-id *current-file* :cache-value *current-file*) (multiple-value-bind (x y) (window-inside-size stream) (with-translation (stream (+ 4 (/ x 2)) (+ 12 (/ y 2))) (let ((*origins* nil) (*concept-labels* nil) (*bounding-boxes* nil) (*pretty-hl* nil) (*global-border* t) (*global-filled* t) (*global-scaling* 1.0) (name (let ((num (position #\/ *current-file* :from-end t))) (subseq *current-file* (if num (1+ num) 0) (length *current-file*))))) (draw *label-shadow-object* stream) (draw *label-object* stream) (format stream "File: ~A" name) ))))) ;;; ;;; ;;; (define-gesture-name :move :pointer-button (:left)) (define-gesture-name :create :pointer-button (:left :shift)) (define-gesture-name :delete :pointer-button (:middle :shift)) (define-gesture-name :inspect :pointer-button (:left :meta)) (define-gesture-name :classic-inspect :pointer-button (:right :meta)) (define-gesture-name :copy :pointer-button (:middle :control)) (define-gesture-name :scale :pointer-button (:right :shift)) (define-gesture-name :rotate :pointer-button (:left :control)) (define-gesture-name :atomize :pointer-button (:left :control)) (define-gesture-name :fix/free :pointer-button (:middle)) ;;; ----------------------------- (defparameter *gened-text-style* (make-text-style :serif :roman :large)) (defvar *gened-frame*) (defun gened (&key (force t) (process t) left top width height &allow-other-keys) (let ((port (find-port))) #+allegro (setf (clim:text-style-mapping port +map-viewer-text-style+) "-*-lucida-medium-r-normal-*-12-*-*-*-*-*-*-*") (when (or force (null *gened-frame*)) (unless left (multiple-value-bind (screen-width screen-height) (bounding-rectangle-size (sheet-region (find-graft :port port))) (setf left 0 top 0 width screen-width height screen-height))) (setf *gened-frame* (make-application-frame 'gened :left left :top top :width 1400 )) #+allegro (if process (mp:process-run-function "Gened" #'(lambda () (run-frame-top-level *gened-frame*))) (run-frame-top-level *gened-frame*)) #+mcl (if process (ccl:process-run-function "Gened" #'(lambda () (run-frame-top-level *gened-frame*))) (run-frame-top-level *gened-frame*)) #+lispworks (if process (mp:process-run-function "Gened" '(:size 200000) ;;; set Stack Size! #'(lambda () (run-frame-top-level *gened-frame*))) (run-frame-top-level *gened-frame*)) *gened-frame*)))
22,959
Common Lisp
.lisp
621
27.663446
88
0.595121
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
cefc957f75eda650e9fb235a7bad7fd122b8676184a91caf5f50ea0d5c301785
11,193
[ -1 ]
11,194
interface-to-classic3.lisp
lambdamikel_GenEd/src/interface-to-classic3.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; Error-Hook-Fn. ;;; (defun inconsistent-classic-object (code args path object) (declare (ignore code args path)) (if (and (cl-instance? object (cl-named-concept 'gened-thing)) (listp (cl-fillers object (cl-named-role 'belongs-to-clos-object)))) (let ((id (first (cl-fillers object (cl-named-role 'belongs-to-clos-object))))) (find-object id)))) ;;; ;;; ;;; (defmethod name-for ((object thing)) (concatenate 'string (generate-name (first (parent-concepts object))) "-" (write-to-string (id-number object)))) ;;; ;;; ;;; (defun add-information (object slot delta) (when delta (when *info* (format t "+ Information: Object ~A, Slot ~A~%" object slot)) (if (or (listp delta) (typep delta 'thing)) (if (listp delta) (insert-fillers-for-slotname object slot delta) (insert-fillers-for-slotname object slot (list delta))) (insert-filler-for-attribute object slot delta)))) (defun remove-information (object slot delta) (when delta (when *info* (format t "- Information: Object ~A, Slot ~A~%" object slot)) (if (or (listp delta) (typep delta 'thing)) (if (listp delta) (remove-fillers-for-slotname object slot delta) (remove-fillers-for-slotname object slot (list delta))) (remove-filler-for-attribute object slot delta)))) ;;; ;;; ;;; (defun create-classic-ind-for (object) (unless (associated-classic-ind object) (when *info* (format t "~%Creating Classic Individual for Object ~A.~%" object)) (let* ((symbol (intern (name-for object))) (classic-ind (cl-create-ind symbol `(and ,@(parent-concepts object))))) (unless (eq classic-ind 'classic-error) (cl-ind-add (cl-named-ind symbol) `(fills belongs-to-clos-object ,(id-number object))) (setf (associated-classic-ind object) symbol))))) (defmethod create-classic-ind ((object thing)) (create-classic-ind-for object)) ;;; Nachdenken! Alle Relationen zwischen Part-Of-Objekten gehen verloren! (Black-Box!) (defmethod create-classic-ind ((object composite-thing)) (dolist (part (liste object)) (create-classic-ind part)) (create-classic-ind-for object)) ;;; ;;; ;;; (defun fill-all-roles-for-object (object) (dolist (slot (all-slots object)) (let ((cont (funcall slot object))) (add-information object slot cont)))) (defmethod fill-all-roles ((object thing)) (fill-all-roles-for-object object) (call-next-method)) (defmethod fill-all-roles ((object stored-relations)) (fill-all-roles-for-object object) (call-next-method)) (defmethod fill-all-roles ((object t)) ()) ;;; ;;; ;;; (defun remove-all-roles-for-object (object) (dolist (slot (all-slots object)) (let ((cont (funcall slot object))) (remove-information object slot cont)))) (defmethod remove-all-roles ((object thing)) (remove-all-roles-for-object object) (call-next-method)) (defmethod remove-all-roles ((object stored-relations)) (remove-all-roles-for-object object) (call-next-method)) (defmethod remove-all-roles ((object t)) ()) ;;; ;;; ;;; (defmethod delete-classic-ind ((object t)) (when *info* (format t "~%Removing All Information for Object ~A.~%" object)) (remove-all-roles object)) (defmethod delete-classic-ind ((object composite-thing)) (when *info* (format t "~%Removing All Information for Object ~A.~%" object)) (remove-all-roles object) (dolist (part (liste object)) (delete-classic-ind part))) ;;; ;;; ;;; (defun get-role-from-accessor (accessor-symbol) (case accessor-symbol (liste 'has-parts) (calc-linked-over-with 'linked-over-with) (calc-start-linked-over-with 'start-linked-over-with) (calc-end-linked-over-with 'end-linked-over-with) (calc-linker-objects 'linker-objects) (calc-start-linker-objects 'start-linker-objects) (calc-end-linker-objects 'end-linker-objects) (calc-startpoint-related-with 'startpoint-related-with) (calc-endpoint-related-with 'endpoint-related-with) (calc-points-related-with 'points-related-with) (part-of-cluster 'part-of) (calc-point-of 'point-part-of) (calc-startpoint-of 'startpoint-part-of-directed-element) (calc-endpoint-of 'endpoint-part-of-directed-element) (filledp 'filled-bool) (xtrans 'xtrans-integer) (ytrans 'ytrans-integer) (radius 'radius-real) (covered-by-objects 'covered-by-object) (otherwise accessor-symbol))) ;;; ;;; ;;; (defun update-classic-ind-concepts (object &key (remove nil) (clos-update t)) (with-application-frame (gened-frame) (with-slots (inc-mode) gened-frame (when inc-mode (let ((object-classic-ind (get-classic-ind object)) (parent-concepts (parent-concepts object)) (ancestor-concepts (ancestor-concepts object))) (when object-classic-ind (if remove (cl-ind-remove object-classic-ind `(and ,@parent-concepts ,@ancestor-concepts)) (cl-ind-add object-classic-ind `(and ,@parent-concepts ,@ancestor-concepts))) (if clos-update (update-parent-concepts)))))))) ;;; ;;; ;;; (defun create-classic-inds () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (elem liste) (create-classic-ind elem)) (dolist (elem liste) (fill-all-roles elem))))) ;;; ;;; ;;; (defmethod calc-points-related-with ((object directed-info-element)) (if (head object) nil (append (startpoint-related-with object) (endpoint-related-with object)))) (defmethod calc-startpoint-related-with ((object directed-info-element)) (if (head object) (startpoint-related-with object) nil)) (defmethod calc-endpoint-related-with ((object directed-info-element)) (if (head object) (endpoint-related-with object) nil)) ;;; ;;; ;;; (defmethod calc-linker-objects ((object 0d)) (remove-if #'head (append (start-linker-objects object) (end-linker-objects object)))) (defmethod calc-start-linker-objects ((object 0d)) (remove-if-not #'head (start-linker-objects object))) (defmethod calc-end-linker-objects ((object 0d)) (remove-if-not #'head (end-linker-objects object))) ;;; ;;; ;;; (defmethod calc-linked-over-with ((object 0d)) (mapcan #'(lambda (goal linker) (unless (head linker) (list goal))) (append (start-linked-over-with object) (end-linked-over-with object)) (append (start-linker-objects object) (end-linker-objects object)))) (defmethod calc-start-linked-over-with ((object 0d)) (mapcan #'(lambda (goal linker) (if (head linker) (list goal))) (start-linked-over-with object) (end-linker-objects object))) (defmethod calc-end-linked-over-with ((object 0d)) (mapcan #'(lambda (goal linker) (if (head linker) (list goal))) (end-linked-over-with object) (start-linker-objects object))) ;;; ;;; ;;; (defun f-point-of (object) (let ((parent (or (startpoint-of object) (endpoint-of object)))) (if (head parent) nil (list (or (startpoint-of object) (endpoint-of object)))))) (defmethod calc-point-of ((object info-point)) (f-point-of object)) (defmethod calc-point-of ((object s-info-point)) (f-point-of object)) (defun f-startpoint-of (object) (let ((parent (startpoint-of object))) (if parent (if (head parent) (list parent) nil) nil))) (defmethod calc-startpoint-of ((object info-point)) (f-startpoint-of object)) (defmethod calc-startpoint-of ((object s-info-point)) (f-startpoint-of object)) (defun f-endpoint-of (object) (let ((parent (endpoint-of object))) (if parent (if (head parent) (list parent) nil) nil))) (defmethod calc-endpoint-of ((object info-point)) (f-endpoint-of object)) (defmethod calc-endpoint-of ((object s-info-point)) (f-endpoint-of object)) ;;; ;;; ;;; (defun insert-filler-for-attribute (object attrib-name filler-to-add) (let ((object-classic-ind (get-classic-ind object)) (filler-to-add (if (numberp filler-to-add) (round filler-to-add) filler-to-add))) (when (and object-classic-ind filler-to-add) (let* ((role-symbol (get-role-from-accessor attrib-name)) (present-fillers (cl-fillers object-classic-ind (cl-named-role role-symbol)))) (unclose-all-roles-for-object-i.n. object) (if present-fillers (cl-ind-remove object-classic-ind `(fills ,role-symbol ,@present-fillers))) (cl-ind-add object-classic-ind `(fills ,role-symbol ,filler-to-add)))))) (defun insert-fillers-for-slotname (object slot-name fillers-to-add) (let ((object-classic-ind (get-classic-ind object))) (when object-classic-ind (let* ((role-symbol (get-role-from-accessor slot-name)) (present-fillers (cl-fillers object-classic-ind (cl-named-role role-symbol)))) (let ((filler-names (mapcar #'(lambda (object) (cl-name (get-classic-ind object))) fillers-to-add)) (present-filler-names (mapcar #'cl-ind-name present-fillers))) (unclose-all-roles-for-object-i.n. object) (dolist (filler-name filler-names) (let ((filler-ind (cl-named-ind filler-name))) (unclose-all-roles-for-classic-ind-i.n. filler-ind) (unless (member filler-name present-filler-names) (cl-ind-add object-classic-ind `(fills ,role-symbol ,filler-name)))))))))) ;;; ;;; ;;; (defun remove-all-fillers-for-slotname (object slot-name) (remove-fillers-for-slotname object slot-name (funcall slot-name object))) (defun remove-filler-for-attribute (object attrib-name filler-to-remove) (let* ((object-classic-ind (get-classic-ind object)) (role-symbol (get-role-from-accessor attrib-name)) (filler-to-remove (if (numberp filler-to-remove) (round filler-to-remove) filler-to-remove))) (when (and object-classic-ind filler-to-remove) (unclose-role-for-classic-ind-i.n. object-classic-ind role-symbol) (cl-ind-remove object-classic-ind `(fills ,role-symbol ,filler-to-remove))))) (defun remove-fillers-for-slotname (object slot-name fillers-to-remove) (let ((object-classic-ind (get-classic-ind object))) (when object-classic-ind (let* ( (role-symbol (get-role-from-accessor slot-name)) (role (cl-named-role role-symbol)) (inv-role (cl-role-inverse role)) (inv-role-symbol (cl-role-name inv-role)) (all-fillers (cl-fillers object-classic-ind role)) (all-filler-names (mapcar #'cl-name all-fillers)) (fillers-to-remove-names (mapcar #'(lambda (x) (cl-name (get-classic-ind x))) fillers-to-remove)) (told-fillers (cl-told-fillers (cl-told-ind object-classic-ind) role)) (told-filler-names (mapcar #'cl-told-ind-name told-fillers)) (derived-filler-names (set-difference all-filler-names told-filler-names)) (remove-told-filler-names (intersection fillers-to-remove-names told-filler-names)) (remove-derived-filler-names (intersection fillers-to-remove-names derived-filler-names))) (unclose-all-roles-for-classic-ind-i.n. object-classic-ind) (dolist (filler-name remove-told-filler-names) (unclose-all-roles-for-classic-ind-i.n. (cl-named-ind filler-name)) (cl-ind-remove object-classic-ind `(fills ,role-symbol ,filler-name))) (if (and inv-role-symbol remove-derived-filler-names) (let ((object-name (cl-name object-classic-ind))) (dolist (name remove-derived-filler-names) (let ((inverse-ind (cl-named-ind name))) (unclose-all-roles-for-classic-ind-i.n. inverse-ind) (cl-ind-remove inverse-ind `(fills ,inv-role-symbol ,object-name)))))))))) ;;; ;;; ;;; (defmethod get-classic-ind ((object thing)) (let ((classic-ind (cl-named-ind (associated-classic-ind object)))) (if classic-ind classic-ind (progn (format t "~%*** ERROR - NO CLASSIC-INDIVIDUAL~% FOR OBJECT ~A EXISTS! ***~%" object) nil)))) ;;; ;;; ;;; (defun print-classic-individual (object) (terpri) (terpri) (if (typep object 'thing) (cl-print-object (get-classic-ind object)) (if (and (or (typep object 'start-handle) (typep object 'end-handle)) (typep (parent-object object) 'directed-info-element)) (cl-print-object (get-classic-ind (if (typep object 'start-handle) (start-info-point (parent-object object)) (end-info-point (parent-object object))))) (format t "~A is not a handle of a Linker-Object!~%" object)))) (define-gened-command (com-print-classic-individual) ((object '(or thing start-handle end-handle) :gesture :classic-inspect)) (print-classic-individual object)) ;;; ;;; ;;; (defun close-role-for-object (object role-symbol) (let ((classic-ind (get-classic-ind object))) (when classic-ind (let* ( (cl-ind (if (cl-told-classic-ind? classic-ind) classic-ind (cl-told-ind classic-ind))) (role (cl-named-role role-symbol))) (unless (cl-told-ind-closed-role? cl-ind role) (cl-ind-close-role classic-ind role)))))) (defun close-roles-for-object (object role-set) (dolist (role-sym role-set) (close-role-for-object object role-sym))) (defun close-all-roles-for-object (object) (dolist (role-set +known-roles+) (close-roles-for-object object role-set))) (defun close-all-roles () (when *info* (format t "~%Closing Roles for Objects...")) (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (role-set +known-roles+) (dolist (object liste) (close-roles-for-object object role-set))))) (when *info* (format t " DONE!~%") (beep)) (update-parent-concepts)) (define-gened-command (com-gened-close-all-roles :name "Close All Roles For All Objects") () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (setf liste (install-points liste)) (close-all-roles) (setf liste (remove-points liste))))) ;;; ;;; ;;; (defun unclose-role-for-object-i.n. (object role-symbol) (let ((classic-ind (get-classic-ind object))) (when classic-ind (unclose-role-for-classic-ind-i.n. classic-ind role-symbol)))) (defun unclose-roles-for-object-i.n. (object role-set) (let ((classic-ind (get-classic-ind object))) (when classic-ind (dolist (role-symbol role-set) (unclose-role-for-classic-ind-i.n. classic-ind role-symbol))))) (defun unclose-role-for-classic-ind-i.n. (classic-ind role-symbol) (let* ((cl-ind (if (cl-told-classic-ind? classic-ind) classic-ind (cl-told-ind classic-ind))) (role (cl-named-role role-symbol))) (when (cl-told-ind-closed-role? cl-ind role) (cl-ind-unclose-role classic-ind role)))) (defun unclose-all-roles-for-object-i.n. (object) (mapc #'(lambda (role-set) (mapc #'(lambda (rol-sym) (unclose-role-for-object-i.n. object rol-sym)) (reverse role-set))) (reverse +known-roles+))) (defun unclose-all-roles-for-classic-ind-i.n. (classic-ind) (mapc #'(lambda (role-set) (mapc #'(lambda (rol-sym) (unclose-role-for-classic-ind-i.n. classic-ind rol-sym)) (reverse role-set))) (reverse +known-roles+))) (defun unclose-all-roles () (when *info* (format t "~%Unclosing Roles for Objects...")) (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (role-set (reverse +known-roles+)) (dolist (object liste) (unclose-roles-for-object-i.n. object (reverse role-set)))))) (when *info* (format t " DONE!~%") (beep))) (define-gened-command (com-gened-open-all-roles :name "Open All Roles For All Objects") () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (setf liste (install-points liste)) (unclose-all-roles) (setf liste (remove-points liste))))) ;;; ;;; ;;; (define-gened-command (com-gened-classify :name "Classic, Classify!") () (with-application-frame (gened-frame) (with-slots (inc-mode liste) gened-frame (when *info* (format t "~%Classic, Classify!~%")) (if inc-mode (progn (setf liste (install-points liste)) (close-all-roles) (setf liste (remove-points liste))) (progn (clear-knowledge-base) (let ((*info* nil)) (calc-relations)) (setf liste (install-points liste)) #| (atomize-all-clusters) |# (create-classic-inds) #| (reinstall-all-clusters) |# (close-all-roles) (setf liste (remove-points liste)))) (update-parent-concepts) (redraw)))) ;;; ;;; ;;; (defun update-parent-concepts-for-object (object) (remove-all-concepts object :classic-ind-update nil) (let ((classic-ind (get-classic-ind object))) (when classic-ind (let* ((parents (mapcar #'cl-name (cl-ind-parents classic-ind))) (ancestors (mapcar #'cl-name (cl-ind-ancestors classic-ind))) (p-concepts (reverse (intersection +known-concepts+ parents))) (a-concepts (reverse (intersection +known-concepts+ ancestors)))) (mapc #'(lambda (parent ancestor) (push-concept object parent :classic-ind-update nil) (push-concept object ancestor :ancestor t :classic-ind-update nil)) p-concepts a-concepts))))) (defun update-parent-concepts () (with-application-frame (gened-frame) (with-slots (liste) gened-frame (dolist (object liste) (update-parent-concepts-for-object object))))) ;;; ;;; ;;; (defmethod clear-classic-ind ((object basic-thing)) (setf (associated-classic-ind object) nil)) (defmethod clear-classic-ind ((object composite-thing)) (dolist (elem (liste object)) (clear-classic-ind elem)) (setf (associated-classic-ind object) nil)) (define-gened-command (com-gened-clear-kb :name "Clear Knowledge-Base") () (with-application-frame (gened-frame) (let ((yes-or-no (notify-user gened-frame "Clear Knowledge-Base selected! Are you sure?" :style :question))) (when yes-or-no (clear-knowledge-base))))) (defun clear-knowledge-base () (with-application-frame (gened-frame) (with-slots (liste stored-relations) gened-frame (cl-clear-kb) (setf liste (install-points liste)) (dolist (elem liste) (clear-classic-ind elem)) (setf liste (remove-points liste)) (setf stored-relations nil))))
18,923
Common Lisp
.lisp
595
26.942857
90
0.66364
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
576c790616029bbeeb052fe9596f04793d6ef4cc9515ad9135dbc593120a084c
11,194
[ -1 ]
11,195
frame-4.3-test.lisp
lambdamikel_GenEd/src/frame-4.3-test.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (define-application-frame gened () ( (liste :initform nil) (stored-relations :initform nil) (saved-liste :initform nil) (prev-op-liste :initform nil) (mode :initform 'g-circle) (concept-type :initform nil) (calc-int-dim :initform nil) (inc-mode :initform nil) (default-arrow-head :initform t) (default-line-thickness :initform 2) (default-line-style :initform :solid) (default-ink :initform 0.4) (default-text-family :initform :sans-serif) (default-text-face :initform :bold) (default-text-size :initform :normal) (default-filled-ink :initform 0.8) (default-filled :initform nil) (buffer-counter :initform 0) (object-copy-buffer :initform (make-array +buffer-size+))) (:command-table (gened :inherit-from (concept-table file-table tool-table manipulate-table reasoning-table spatial-table) :menu (("File" :menu file-table) ("Tools" :menu tool-table) ("Manipulate" :menu manipulate-table) ("Reasoning" :menu reasoning-table) ("Concepts" :menu concept-table) ("Spatial" :menu spatial-table)))) (:panes #| (pointer-documentation-pane (make-clim-stream-pane :type 'pointer-documentation-pane :foreground +white+ :background +black+ :text-style (make-text-style :sans-serif :bold :small) :scroll-bars nil :min-height '(1 :line) :max-height '(1 :line) )) |# (pointer-documentation-pane :pointer-documentation) (display :application :display-function 'draw-gened :textcursor nil :width 600 :height 300 :redisplay-after-commands nil :incremental-redisplay t) (label :application :scroll-bars nil :width 140 :max-width 140 :min-width 140 :redisplay-after-commands nil :incremental-redisplay t :display-function 'draw-label :foreground +white+ :background +black+) (infos :application :textcursor nil :text-style (parse-text-style '(:sans-serif :roman :very-small)) :width 300 :height 300 :end-of-line-action :allow :scroll-bars :both :incremental-redisplay nil) (command :interactor :min-height '(1 :line) :max-height '(1 :line)) (options1 :accept-values :min-height :compute :min-width :compute :width :compute :max-width :compute :scroll-bars nil :display-function `(accept-values-pane-displayer :displayer ,#'(lambda (frame stream) (accept-options1 frame stream)))) (options2 :accept-values :min-height :compute :min-width :compute :width :compute :max-width :compute :scroll-bars nil :display-function `(accept-values-pane-displayer :displayer ,#'(lambda (frame stream) (accept-options2 frame stream)))) (elements :accept-values :scroll-bars nil :min-height :compute :height :compute :max-height :compute :display-function `(accept-values-pane-displayer :displayer ,#'(lambda (frame stream) (accept-elements frame stream)))) (buttons :accept-values :scroll-bars nil :min-height :compute :height :compute :max-height :compute :display-function `(accept-values-pane-displayer #| :resynchronize-every-pass t |# :displayer ,#'(lambda (frame stream) (accept-buttons frame stream))))) (:layouts (:default (vertically () (horizontally () (vertically () elements options1 options2) (outlining (:thichness 2) label)) (horizontally () buttons display infos) command pointer-documentation-pane)))) #| (defmethod read-frame-command ((frame gened) &key (stream *standard-input*)) (read-command (frame-command-table frame) :use-keystrokes t :stream stream)) |# (defun accept-it (stream type default prompt query-id &key (view 'gadget-dialog-view) (min-width 200) (min-height 20) orientation) (let (object ptype changed) (formatting-cell (stream :align-x (ecase orientation (:horizontal :left) (:vertical :center)) :align-y :center :min-width min-width :min-height min-height) (multiple-value-setq (object ptype changed) (accept type :stream stream :default default :query-identifier query-id :prompt prompt :view view))) (values object changed))) (defmethod accept-options1 ((frame gened) stream &key (orientation :horizontal)) (with-slots (default-line-style default-line-thickness default-ink default-arrow-head) frame (formatting-table (stream) (flet ((do-body (stream) (multiple-value-bind (real) (accept-it stream 'ink default-ink "Ink" 'ink :orientation orientation :min-width 205) (setf default-ink real) (multiple-value-bind (thickness) (accept-it stream 'line-thickness default-line-thickness "Thickness" 'thickness :orientation orientation :min-width 323) (setf default-line-thickness thickness) (multiple-value-bind (line-style) (accept-it stream 'line-style-type default-line-style "Style" 'style :orientation orientation :min-width 270) (setf default-line-style line-style)) (multiple-value-bind (bool) (accept-it stream 'boolean default-arrow-head "Head " 'head :orientation orientation) (setf default-arrow-head bool)))))) (ecase orientation (:horizontal (formatting-row (stream) (do-body stream))) (:vertical (formatting-column (stream) (do-body stream)))))))) (defmethod accept-options2 ((frame gened) stream &key (orientation :horizontal)) (with-slots (default-filled default-filled-ink default-text-family default-text-face default-text-size ) frame (formatting-table (stream) (flet ((do-body (stream) (multiple-value-bind (real) (accept-it stream 'ink default-filled-ink "Ink" 'ink :orientation orientation) (setf default-filled-ink real) (multiple-value-bind (text-style) (accept-it stream 'p-text-style (list default-text-family default-text-face) "Text-Style" 'text-style :orientation orientation) (setf default-text-family (first text-style)) (setf default-text-face (second text-style)) (multiple-value-bind (text-size) (accept-it stream 'p-text-size default-text-size "Text-Size" 'text-size :orientation orientation :min-width 300) (setf default-text-size text-size) (multiple-value-bind (bool) (accept-it stream 'boolean default-filled "Filled" 'filled :orientation orientation) (setf default-filled bool))))))) (ecase orientation (:horizontal (formatting-row (stream) (do-body stream))) (:vertical (formatting-column (stream) (do-body stream)))))))) ;;; ;;; ;;; (defun get-symbol-list () (with-application-frame (gened-frame) (with-slots (calc-int-dim inc-mode) gened-frame (append (when *bounding-boxes* (list 'boxes)) (when *origins* (list 'origins)) (when *info* (list 'infos)) (when *pretty-hl* (list 'pretty)) (when calc-int-dim (list 'dimensions)) (when inc-mode (list 'incremental)) (when *classic-warnings* (list 'warnings)))))) (defun text-cell (stream format-string &key (orientation :center)) (formatting-cell (stream :align-x orientation) (write-string format-string stream) (write-string " " stream))) (defmethod accept-buttons ((frame gened) stream &key (orientation :vertical)) (with-slots (calc-int-dim inc-mode) frame (let ((last-symbol-list (get-symbol-list))) (formatting-table (stream :y-spacing '(1 :character)) (flet ((do-body (stream) (text-cell stream "Global Display Options:") (multiple-value-bind (symbol-list changed0p) (accept-it stream '(subset-completion (VISIBLE HIDDEN PRIMITIVE COMPOSITE)) *global-display-options* nil 'global-display-options :orientation orientation :view 'list-pane-view) (setf *global-display-options* symbol-list) (text-cell stream "Object Display Options:") (multiple-value-bind (symbol-list changed1p) (accept-it stream '(subset-completion (INTERIOR BORDER)) (list (if *global-border* 'BORDER) (if *global-filled* 'INTERIOR)) nil 'object-display-options :orientation orientation :view 'list-pane-view) (setf *global-filled* (and (member 'INTERIOR symbol-list) t) *global-border* (and (member 'BORDER symbol-list) t)) (text-cell stream "Object Handle Options:") (multiple-value-bind (symbol-list changed2p) (accept-it stream `(subset-completion (NORMAL FIXED UNFIXED START END)) *handles-symbol-list* nil 'handles :orientation orientation :view 'list-pane-view) (setf *handles-symbol-list* symbol-list) (text-cell stream "Global Display Scaling:") (multiple-value-bind (number changed3p) (accept-it stream `(completion (1/2 1 2)) *global-scaling* nil 'gs :view 'list-pane-view :orientation orientation) (setf *global-scaling* number) (text-cell stream "Concept Label Options:") (multiple-value-bind (symbol-list changed4p) (accept-it stream '(subset-completion (IDs PARENTS ANCESTORS)) *concept-labels* nil 'labels :view 'list-pane-view :orientation orientation) (setf *concept-labels* symbol-list) (text-cell stream "Others:") (multiple-value-bind (symbol-list changed5p) (accept-it stream '(subset-completion (Boxes Origins Pretty Infos Warnings Dimensions Incremental)) (get-symbol-list) nil 'others :orientation orientation :view 'list-pane-view) (setf *pretty-hl* (member 'pretty symbol-list)) (setf *bounding-boxes* (member 'boxes symbol-list)) (setf *origins* (member 'origins symbol-list)) (setf *info* (member 'infos symbol-list)) (setf *classic-warnings* (member 'warnings symbol-list)) (set-classic-infos *classic-warnings*) (setf calc-int-dim (member 'dimensions symbol-list)) (setf inc-mode (member 'incremental symbol-list)) (when (or changed0p changed1p changed2p changed3p changed4p changed5p) (when changed5p (when (or (and (member 'dimensions symbol-list) (not (member 'dimensions last-symbol-list))) (and (not (member 'dimensions symbol-list)) (member 'dimensions last-symbol-list))) (clear-hashtable) (do-incremental-updates)) (when (or (and (member 'incremental symbol-list) (not (member 'incremental last-symbol-list))) (and (not (member 'incremental symbol-list)) (member 'incremental last-symbol-list))) (when inc-mode (clear-knowledge-base) (do-incremental-updates)))) (if changed3p (progn (tick-all-objects) (do-incremental-updates)) (only-tick-all-objects))))))))))) (ecase orientation (:horizontal (formatting-row (stream) (do-body stream))) (:vertical (formatting-column (stream) (do-body stream))))))))) (defmethod accept-elements ((frame gened) stream &key &allow-other-keys) (with-slots (mode) frame (formatting-table (stream) (formatting-column (stream) (formatting-cell (stream :align-x :center) (let ((element (accept 'elements :stream stream :default mode :prompt "Element"))) (setf mode element))))))) ;;; ;;; ;;; (define-presentation-type line-thickness () :inherit-from `((completion (1 2 3 4)) :name-key identity :printer present-line-thickness :highlighter highlight-line-thickness)) (defun present-line-thickness (object stream &key acceptably) (declare (ignore acceptably)) (let ((y (stream-line-height stream))) (with-room-for-graphics (stream) (draw-rectangle* stream 0 2 26 (- y 2) :filled nil :ink +background-ink+) (draw-line* stream 0 (floor y 2) 26 (floor y 2) :line-thickness object)))) (defun highlight-line-thickness (continuation object stream) (surrounding-output-with-border (stream) (funcall continuation object stream))) ;;; ;;; ;;; (define-presentation-type line-style-type () :inherit-from `((completion (:solid :pattern1 :pattern2 :pattern3)) :name-key identity :printer present-line-style :highlighter highlight-line-style)) (defun decode-line-style (object) (second (assoc object +line-pattern-list+))) (defun encode-line-style (object) (first (rassoc (list object) +line-pattern-list+ :test #'equal))) (defun present-line-style (object stream &key acceptably) (declare (ignore acceptably)) (let ((y (stream-line-height stream))) (with-room-for-graphics (stream) (draw-rectangle* stream 0 2 22 (- y 2) :filled nil :ink +background-ink+) (draw-line* stream 0 (floor y 2) 22 (floor y 2) :line-dashes (decode-line-style object))))) (defun highlight-line-style (continuation object stream) (surrounding-output-with-border (stream) (funcall continuation object stream))) ;;; ;;; ;;; (define-presentation-type ink () :inherit-from '((completion (0.4 0.6 0.8 0.9)) :name-key identity :printer present-ink)) (defun present-ink (object stream &key acceptably) (declare (ignore acceptably)) (let ((y (stream-line-height stream))) (with-room-for-graphics (stream) (draw-rectangle* stream 0 2 16 (- y 2) :filled t :ink (make-gray-color object))))) ;;; ;;; ;;; (define-presentation-type p-text-style () :inherit-from `((completion ((:sans-serif :bold) (:serif :italic) (:sans-serif nil) (:fix :bold)) :test equalp) :name-key identity :printer present-text-style)) (defun present-text-style (object stream &key) (let ((text-style (parse-text-style (append object '(:small))))) (with-text-style (stream text-style) (draw-text* stream "ABC" 0 0 :ink +black+)))) (define-presentation-type p-text-size () :inherit-from '((completion (:tiny :very-small :normal :very-large :huge)) :name-key identity :printer present-text-size)) (defun present-text-size (object stream &key) (case object (:tiny (write-string "T" stream)) (:very-small (write-string "S" stream)) (:normal (write-string "N" stream)) (:very-large (write-string "L" stream)) (:huge (write-string "H" stream)))) ;;; ;;; ;;; (define-presentation-type elements () :inherit-from `((completion (g-concept g-circle g-rectangle g-arrow g-chain g-spline-chain g-polygon g-spline-polygon g-text g-point)) :name-key identity :printer present-elements :highlighter highlight-element)) (defun present-elements (object stream &key) (let ((*concept-labels* nil) (*handles-symbol-list* nil) (*bounding-boxes* nil) (*origins* nil)) (draw (second (assoc object *sample-graphic-objects*)) stream))) (defun highlight-element (continuation object stream) (surrounding-output-with-border (stream) (funcall continuation object stream))) ;;; ;;; ;;; (defmethod run-frame-top-level :before ((frame gened) &key) (initialize-gened frame)) (defmethod frame-standard-input ((frame gened)) (get-frame-pane frame 'command)) (defmethod frame-standard-output ((frame gened)) (get-frame-pane frame 'infos)) (defmethod initialize-gened ((frame gened)) (load-concepts) (load-label-object) (setf *current-file* "NONAME") (setf *global-scaling* 1) (setf *cl-error-msg-stream* (get-frame-pane frame 'infos)) (setf *cl-warn-msg-stream* (get-frame-pane frame 'infos)) (cl-set-classic-error-mode nil) (setf *classic-print-right-margin* 40)) (defun set-classic-infos (bool) (cl-set-classic-warn-mode bool)) (defmethod frame-error-output ((frame gened)) (get-frame-pane frame 'infos)) (defun clear-info-pane () (with-application-frame (gened-frame) (let ((stream (get-frame-pane gened-frame 'infos))) (window-clear stream)))) ;;; ;;; ;;; (defmethod draw-label ((frame gened) stream &key max-width max-height) (declare (ignore max-width max-height)) (updating-output (stream :unique-id *current-file* :cache-value *current-file*) (multiple-value-bind (x y) (window-inside-size stream) (with-translation (stream (+ 4 (/ x 2)) (+ 12 (/ y 2))) (let ((*origins* nil) (*concept-labels* nil) (*bounding-boxes* nil) (*pretty-hl* nil) (*global-border* t) (*global-filled* t) (*global-scaling* 1) (name (let ((num (position #\/ *current-file* :from-end t))) (subseq *current-file* (if num (1+ num) 0) (length *current-file*))))) (draw *label-shadow-object* stream) (draw *label-object* stream) (format stream "File: ~A" name)))))) ;;; ;;; ;;; (define-gesture-name :move :pointer-button (:left)) (define-gesture-name :create :pointer-button (:left :shift)) (define-gesture-name :delete :pointer-button (:middle :shift)) (define-gesture-name :inspect :pointer-button (:left :meta)) (define-gesture-name :classic-inspect :pointer-button (:right :meta)) (define-gesture-name :copy :pointer-button (:middle :control)) (define-gesture-name :scale :pointer-button (:right :shift)) (define-gesture-name :rotate :pointer-button (:left :control)) (define-gesture-name :atomize :pointer-button (:left :control)) (define-gesture-name :fix/free :pointer-button (:middle)) ;;; ----------------------------- (defparameter *gened-text-style* (make-text-style :sans-serif :roman :normal )) (defvar *gened-frame*) (defun gened (&key (force t) (process t) (left nil) top width height &allow-other-keys) (let ((port (find-port))) (setf (clim:text-style-mapping port *gened-text-style*) "-*-lucida-medium-r-normal-*-12-*-*-*-*-*-*-*") (when (or force (null *gened-frame*)) (unless left (multiple-value-bind (screen-width screen-height) (bounding-rectangle-size (sheet-region (find-graft :port port))) (setf left 0 top 0 width screen-width height screen-height))) (setf *gened-frame* #| (make-application-frame 'gened :left (+ 10 left) :top (+ 10 top) :width (- width 50) :height (- height 50) ) |# (make-application-frame 'gened) ) #+:Allegro (if process (mp:process-run-function "Model Browser" #'(lambda () (run-frame-top-level *gened-frame*))) (run-frame-top-level *gened-frame*)) #-:Allegro (run-frame-top-level *gened-frame*) *gened-frame*)))
19,662
Common Lisp
.lisp
567
28.059965
88
0.650232
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
ff65bb0930777a0093bd22ef8144fd31dd8081c072804443e4d0c050a0305ad7
11,195
[ -1 ]
11,196
rel-copy.lisp
lambdamikel_GenEd/src/rel-copy.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; Object-Copier-Functions for Spatial Relations! ;;; (defclass stored-relations () ((belongs-to :accessor belongs-to) (id-number :accessor id-number) (xtrans :accessor xtrans) (ytrans :accessor ytrans))) (defclass s-object-with-head () ((head :accessor head))) (defclass s-0d (stored-relations 0d) ()) (defclass s-1d (stored-relations 1d) ()) (defclass s-directed-1d (stored-relations 1d directed-info-element s-object-with-head) ()) (defclass s-2d (stored-relations 2d) ()) (defclass s-filled-mixin () ((filledp :accessor filledp))) (defclass s-composite-thing (stored-relations 2d) ((liste :accessor liste :initform nil))) (defclass s-info-point (stored-relations 0d) ((startpoint-of :initform nil :initarg :startpoint-of :accessor startpoint-of) (endpoint-of :initform nil :initarg :endpoint-of :accessor endpoint-of) (parent-head :accessor parent-head))) (defclass s-g-text (stored-relations 2d) ((text-string :accessor text-string))) (defclass s-g-circle (stored-relations 2d s-filled-mixin) ((radius :accessor radius))) (defclass s-g-rectangle (stored-relations 2d s-filled-mixin) ()) (defclass s-g-polygon (stored-relations 2d s-filled-mixin) ()) (defclass s-g-spline-polygon (stored-relations 2d s-filled-mixin) ()) ;;; ;;; ;;; (defmethod print-object ((object stored-relations) stream) (print "STORED" stream) (print-object (belongs-to object) stream)) (defmethod get-classic-ind ((object stored-relations)) (get-classic-ind (belongs-to object))) ;;; ;;; ;;; (defmethod copy-relations ((source-object t) (destination-object stored-relations)) (setf (id-number destination-object) (id-number source-object)) (setf (belongs-to destination-object) source-object) (setf (xtrans destination-object) (xtrans source-object)) (setf (ytrans destination-object) (ytrans source-object))) (defmethod copy-relations ((source-object composite-thing) (destination-object s-composite-thing)) (dolist (elem (liste source-object)) (push (make-stored-relation elem) (liste destination-object))) (call-next-method)) (defmethod copy-relations ((source-object filled-mixin) (destination-object s-filled-mixin)) (setf (filledp destination-object) (filledp source-object)) (call-next-method)) (defmethod copy-relations ((source-object g-circle) (destination-object s-g-circle)) (setf (radius destination-object) (radius source-object)) (call-next-method)) (defmethod copy-relations ((source-object g-text) (destination-object s-g-text)) (setf (text-string destination-object) (text-string source-object)) (call-next-method)) (defmethod copy-relations ((source-object info-point) (destination-object s-info-point)) (setf (startpoint-of destination-object) (startpoint-of source-object)) (setf (endpoint-of destination-object) (endpoint-of source-object)) (setf (parent-head destination-object) (head (or (startpoint-of source-object) (endpoint-of source-object)))) (call-next-method)) ;;; ;;; ;;; (defmethod copy-relations ((source-object 0d) (destination-object 0d)) (with-slots (part-of-cluster disjoint-with start-linked-over-with end-linked-over-with start-linker-objects end-linker-objects in-relation-with-objects intersects-objects intersects-0-objects touching-objects contained-in-objects covered-by-objects directly-contained-by-object) destination-object (setf part-of-cluster (part-of-cluster source-object)) (setf disjoint-with (disjoint-with source-object)) (setf start-linked-over-with (start-linked-over-with source-object)) (setf end-linked-over-with (end-linked-over-with source-object)) (setf start-linker-objects (start-linker-objects source-object)) (setf end-linker-objects (end-linker-objects source-object)) (setf in-relation-with-objects (in-relation-with-objects source-object)) (setf intersects-objects (intersects-objects source-object)) (setf intersects-0-objects (intersects-0-objects source-object)) (setf touching-objects (touching-objects source-object)) (setf contained-in-objects (contained-in-objects source-object)) (setf covered-by-objects (covered-by-objects source-object)) (setf directly-contained-by-object (directly-contained-by-object source-object))) (call-next-method)) (defmethod copy-relations ((source-object 1d) (destination-object 1d)) (with-slots (intersects-1-objects) destination-object (setf intersects-1-objects (intersects-1-objects source-object))) (call-next-method)) (defmethod copy-relations ((source-object 2d) (destination-object 2d)) (with-slots (intersects-2-objects contains-objects covers-objects directly-contains-objects) destination-object (setf intersects-2-objects (intersects-2-objects source-object)) (setf contains-objects (contains-objects source-object)) (setf covers-objects (covers-objects source-object)) (setf directly-contains-objects (directly-contains-objects source-object))) (call-next-method)) (defmethod copy-relations ((source-object directed-info-element) (destination-object s-directed-1d)) (setf (startpoint-related-with destination-object) (startpoint-related-with source-object)) (setf (endpoint-related-with destination-object) (endpoint-related-with source-object)) (if (head source-object) (setf (head destination-object) t) (setf (head destination-object) nil)) (call-next-method)) ;;; ;;; ;;; (defun remove-stored-object-relations () (with-application-frame (gened-frame) (with-slots (liste stored-relations) gened-frame (setf stored-relations nil)))) (defun store-object-relations () (with-application-frame (gened-frame) (with-slots (liste stored-relations) gened-frame (setf stored-relations nil) (dolist (elem liste) (let ((rel (make-stored-relation elem))) (push rel stored-relations)))))) (defun make-stored-relation (elem) (let ((instance (make-instance (cond ((typep elem 'composite-thing) 's-composite-thing) ((typep elem 'directed-info-element) 's-directed-1d) ((typep elem 'g-circle) 's-g-circle) ((typep elem 'g-text) 's-g-text) ((typep elem 'g-rectangle) 's-g-rectangle) ((typep elem 'g-polygon) 's-g-polygon) ((typep elem 'g-spline-polygon) 's-g-spline-polygon) ((typep elem '2d) 's-2d) ((typep elem '1d) 's-1d) ((typep elem 'info-point) 's-info-point) ((typep elem '0d) 's-0d))))) (copy-relations elem instance) instance)) (defun get-stored-object (object) (with-application-frame (gened-frame) (with-slots (stored-relations) gened-frame (find (id-number object) stored-relations :key #'id-number))))
6,965
Common Lisp
.lisp
173
35.99422
106
0.720868
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
8d326f2ce2bc53b41eb285680bbbd6771ddcadb2545a545be2f48a2c06f7e447
11,196
[ -1 ]
11,197
delta.lisp
lambdamikel_GenEd/src/delta.lisp
;;; -*- Mode: LISP; Syntax: Ansi-Common-Lisp; Package: GENED -*- (in-package gened) (defun do-incremental-updates (&key (backward nil)) (with-application-frame (gened-frame) (with-slots (inc-mode liste prev-op-liste object-copy-buffer) gened-frame (if inc-mode (progn (calc-relations) (let* ((undo-object (if backward (unstack-undo-object) (get-undo-object)))) (if undo-object (let* ((op (operation undo-object)) (copy (if backward (original-object undo-object) (object-copy undo-object))) (orig-object (if backward (object-copy undo-object) (original-object undo-object)))) #| (terpri) (print op) (terpri) (terpri) (if orig-object (dolist (slot (all-slots orig-object)) (format t "ORIG!! Slot ~A: ~A~%" slot (funcall slot orig-object)))) (terpri) (if copy (dolist (slot (all-slots copy)) (format t "COPY! Slot ~A: ~A~%" slot (funcall slot copy)))) |# (print op) (case op (cluster (if backward (progn (remove-all-roles copy) (dolist (elem (liste copy)) (fill-all-roles elem))) (when orig-object (create-classic-ind orig-object) (fill-all-roles orig-object)))) (delete (if backward ; dann UNDO delete = (re)create ! (progn (fill-all-roles copy) (setf (associated-classic-ind orig-object) (associated-classic-ind copy))) (when orig-object (delete-classic-ind orig-object) (remove-all-roles orig-object)))) ((create load-object copy) (if backward ; dann UNDO create = delete ! (remove-all-roles copy) (when orig-object (create-classic-ind orig-object) (fill-all-roles orig-object)))) (load-scene (com-gened-create-classic-inds)) (otherwise (when backward (setf (associated-classic-ind orig-object) (associated-classic-ind copy)) (when (typep orig-object 'composite-thing) (mapc #'(lambda (o-elem c-elem) (setf (associated-classic-ind o-elem) (associated-classic-ind c-elem))) (liste orig-object) (liste copy)))) (loop for i from 0 to (1- +buffer-size+) do (let ((second-undo-object (aref object-copy-buffer i))) (if (and second-undo-object (original-object second-undo-object) orig-object (= (id-number (original-object second-undo-object)) (id-number orig-object))) (setf (original-object second-undo-object) orig-object)))) (when (and orig-object copy) (do-incremental-classic-updates orig-object copy) (when (typep orig-object 'directed-info-element) (do-incremental-classic-updates (start-info-point orig-object) (start-info-point copy)) (do-incremental-classic-updates (end-info-point orig-object) (end-info-point copy)) (let ((delta (object-delta orig-object copy))) (when (member 'startpoint-related-with delta) (if (and (startpoint-related-with copy) (startpoint-related-with orig-object)) (do-incremental-classic-updates (first (startpoint-related-with orig-object)) (first (startpoint-related-with copy)))) (if (and (startpoint-related-with copy) (not (startpoint-related-with orig-object))) (remove-all-roles orig-object)) (if (and (not (startpoint-related-with copy)) (startpoint-related-with orig-object)) (fill-all-roles orig-object))) (when (member 'endpoint-related-with delta) (if (and (endpoint-related-with copy) (endpoint-related-with orig-object)) (do-incremental-classic-updates (first (endpoint-related-with orig-object)) (first (endpoint-related-with copy)))) (if (and (endpoint-related-with copy) (not (endpoint-related-with orig-object))) (remove-all-roles orig-object)) (if (and (not (endpoint-related-with copy)) (endpoint-related-with orig-object)) (fill-all-roles orig-object))) ))))))))) (if backward (unstack-undo-object)))))) (defmethod do-incremental-classic-updates ((orig-object null) (copy 0d)) (fill-all-roles copy)) (defmethod do-incremental-classic-updates ((orig-object 0d) (copy null)) (remove-all-roles orig-object)) (defmethod do-incremental-classic-updates ((orig-object 0d) (copy 0d)) (dolist (slot (object-delta orig-object copy)) (let ((prev-cont (get-unique-slot-output (funcall slot copy))) (cont (get-unique-slot-output (funcall slot orig-object)))) #| (format t "DELTA Slot: ~A ~A ~A~%" slot prev-cont cont) |# (if (or (and (listp cont) (subsetp prev-cont cont :key #'id-number)) (and (numberp cont) (not (equalp prev-cont cont)))) (add-information orig-object slot (set-difference cont prev-cont :key #'id-number))) (if (or (and (listp prev-cont) (subsetp cont prev-cont :key #'id-number)) (and (numberp prev-cont) (not (equalp prev-cont cont)))) (remove-information orig-object slot (set-difference prev-cont cont :key #'id-number)))))) ;;;; (defgeneric all-slots (object) (:method-combination append)) ;;;; (defun get-unique-slot-output (content) (when content (if (atom content) (list content) content))) (defun get-delta (object1 object2 slot-names) (mapcan #'(lambda (rel-sym) (let ((l1 (funcall rel-sym object1)) (l2 (funcall rel-sym object2))) (when (or (and l1 (not l2)) (and l2 (not l1)) (and (listp l1) (listp l2) (not (and (subsetp l1 l2 :key #'id-number) (subsetp l2 l1 :key #'id-number)))) (and (numberp l1) (numberp l2) (not (equalp l1 l2)))) (list rel-sym)))) slot-names)) ;;; Achtung: unbed. die richtige Reihenfolge einhalten! (defmethod all-slots append ((object composite-thing)) '(liste)) (defmethod all-slots append ((object 0d)) '(part-of-cluster disjoint-with start-linked-over-with end-linked-over-with start-linker-objects end-linker-objects intersects-objects intersects-0-objects touching-objects directly-contained-by-object contained-in-objects covered-by-objects)) (defmethod all-slots append ((object 1d)) '(intersects-1-objects)) (defmethod all-slots append ((object 2d)) '(intersects-2-objects directly-contains-objects contains-objects covers-objects)) (defmethod all-slots append ((object directed-info-element)) '(startpoint-related-with endpoint-related-with start-info-point end-info-point)) ;;; ;;; (defmethod object-delta ((object1 0d) (object2 0d)) (get-delta object1 object2 (union (all-slots object1) (all-slots object2)))) (defmethod object-delta ((object1 null) (object2 0d)) (all-slots object2)) (defmethod object-delta ((object1 0d) (object2 null)) (all-slots object1))
7,459
Common Lisp
.lisp
204
28.25
77
0.627392
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
40fee1d592d2bef2a947bd061f380dfe0a59dd3f96d06b33557c97ac07a224d4
11,197
[ -1 ]
11,198
init.lisp
lambdamikel_GenEd/src/init.lisp
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*- (in-package gened) ;;; ;;; ;;; (defparameter *spline-chain* (make-instance 'g-spline-chain :pointlist '(-23 -13 -12 6 -8 -10 0 0 8 -4 16 14) :initialize-handles t :head t :parent-concepts '("directed-spline-chain"))) (defparameter *spline-polygon* (make-instance 'g-spline-polygon :pointlist '(8 16 10 12 16 16 22 18 24 12 22 8 16 0 8 -8 4 -16 0 -20 -8 -16 -10 -8 -12 0 -16 4 -12 12 -4 16) :initialize-handles t :xscale 1.0 :yscale 1.0 :parent-concepts '("spline-polygon"))) (defparameter *label-object* nil) ; wird spaeter gebunden, Frame muss erst existieren! (defparameter *label-shadow-object* nil) (defun load-label-object () (setf *label-object* (load-object (concatenate 'string +objects-dir+ "label-object"))) (setf *label-shadow-object* (load-object (concatenate 'string +objects-dir+ "label-shadow-object"))) (translate-object *label-object* 0 0) (translate-object *label-shadow-object* 3 3)) (let ((liste (make-spline (make-spline-chain-list (generate-brackets (pointlist *spline-chain*))) 3))) (setf (spline-points *spline-chain*) (append (mapcan #'identity liste) '(-28 -20)))) (let ((liste (make-spline (make-spline-polygon-list (generate-brackets (pointlist *spline-polygon*))) 6))) (setf (spline-points *spline-polygon*) (mapcan #'identity liste))) (defparameter *sample-graphic-objects* (list (list 'g-circle (make-instance 'g-circle :radius 10 :xscale 2.0 :yscale 2.0)) (list 'g-rectangle (make-instance 'g-rectangle :xextend 10 :yextend 8 :xscale 2.0 :yscale 2.0)) (list 'g-arrow (make-instance 'g-arrow :startpoint '(-20 20) :endpoint '(20 -20) :initialize-handles t :head t)) (list 'g-chain (make-instance 'g-chain :pointlist '(-20 -10 -12 6 -8 -10 0 0 4 -4 12 8 20 20) :initialize-handles t :head t)) (list 'g-spline-chain *spline-chain*) (list 'g-spline-polygon *spline-polygon*) (list 'g-polygon (make-instance 'g-polygon :pointlist '(-16 12 16 20 12 8 16 -12 8 -20 -20 -12 -16 -8) :initialize-handles t)) (list 'g-text (make-instance 'g-text :text-string "ABC" :size :very-large :face :italic :family :sans-serif)) (list 'g-point (make-instance 'g-point :linethickness 3)) (list 'g-concept (make-instance 'g-text :text-string "*!@?" :size :very-large)))) ;;; ;;; ;;; (defun load-concepts () (mapc #'(lambda (x) (init-object-properties (second x))) *library*)) (defparameter *library* nil) (defun get-visualisations-of-concept (item) (find-it *library* #'(lambda (x) (eql (first x) item)))) (defun get-graphic-object (item) (second item)) (defun get-nth-visualisation-of-concept (item nth) (get-graphic-object (nth nth (get-visualisations-of-concept item)))) ;;; ;;; ;;; #| (cl-add-error-hook #'inconsistent-classic-object) |#
3,151
Common Lisp
.lisp
103
25.466019
104
0.631738
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e82c32c4f44d0dc997d5e6f910f836acd9471a75c55a10cffaf89e8a66a7f8b8
11,198
[ -1 ]
11,199
example.lisp
lambdamikel_GenEd/src/cc/example.lisp
;;; -*- Syntax: ANSI-Common-Lisp; Package: KNOWLEDGE -*- (in-package knowledge) (cl-startup) ;;; ---------------------------------------------------------------------- ;;; ;;; Domain Model ;;; (define-primitive-concept person classic-thing) (define-primitive-concept loadable-object classic-thing) (define-primitive-concept container loadable-object) (define-primitive-concept passenger (and person loadable-object)) (define-primitive-role has-ship nil) (define-primitive-concept captain person) (define-primitive-role has-loadable-object nil) (define-primitive-role has-captain nil) (define-primitive-role has-position nil) (define-primitive-concept pos classic-thing) (define-primitive-role has-x-coordinate nil) (define-primitive-role has-y-coordinate nil) (define-primitive-concept ship (and (all has-loadable-object loadable-object) (at-least 1 has-position) (at-most 1 has-position) (all has-position pos) (at-least 1 has-captain) (at-most 1 has-captain) (all has-captain captain))) (define-concept passenger-ship (and ship (all has-loadable-object passenger))) (define-concept container-ship (and ship (all has-loadable-object container))) ;;; ---------------------------------------------------------------------- ;;; ;;; Functional interface to a knowledge base ;;; (define-accessors captain (has-ship captains-ship :single-value-p t)) (define-accessors ship (has-loadable-object ship-loadable-objects) (has-position ship-position :single-value-p t :error-if-null t) (has-captain ship-captain :single-value-p t :error-if-null t)) (define-method initialize-individual :after ((ind ship) &rest initargs) (let ((captain (ship-captain ind))) (setf (captains-ship captain) ind) (setf (ship-position ind) (create-individual 'pos (gensym "POS") 'has-x-coordinate 0 'has-y-coordinate 0)))) (define-accessors pos (has-x-coordinate position-x :single-value-p t :error-if-null t) (has-y-coordinate position-y :single-value-p t :error-if-null t)) (eval-when (:compile-toplevel :load-toplevel :execute) (define-generic-function ship-position-xy ((ship :classic))) (define-generic-function print-information-about-domain-object ((ind :classic) (stream :clos)) (:documentation "Demonstration function for method dispatch.")) ) (define-method ship-position-xy ((ind ship)) (let ((pos (ship-position ind))) (values (position-x pos) (position-y pos)))) ;;; ---------------------------------------------------------------------- ;;; ;;; Procedural code ;;; (define-method print-information-about-domain-object ((ind ship) stream) (format stream "~%Information about the ship ~S." ind) (cl-print-object ind)) (define-method print-information-about-domain-object ((ind container-ship) stream) (format stream "~%Ah, a ship has been classified to a container ship ~ and the advantages of CLASSIC over CLOS become clear.") (call-next-method)) (define-method print-information-about-domain-object ((ind passenger-ship) stream) (format stream "~%Ah, a ship has been classified to a passenger ship ~ and the advantages of CLASSIC over CLOS become clear.") (call-next-method)) ;;; ---------------------------------------------------------------------- ;;; ;;; Individual creation ;;; #| (create-individual 'captain 'c1) (create-individual 'ship 's1 'has-captain (list @c1)) (print-information-about-domain-object @s1 *standard-output*) (state (instance s1 (all has-loadable-object passenger))) (print-information-about-domain-object @s1 *standard-output*) (ship-position @s1) (ship-position-xy @s1) |# (defun measurement1 () (let ((s @s1) j) (dotimes (i 1000) (setf j (ship-position s))))) (defun measurement2 () (let ((i 0) (s @s1)) (dotimes (i 1000) (incf i (ship-position-xy s))))) (defun measurement3 () (let ((s @s1) (r @has-position) j) (dotimes (i 1000) (setf j (first (cl-fillers s r)))))) (defun pos-xy (s) (let ((pos (first (cl-fillers s @has-position)))) (values (first (cl-fillers pos @has-x-coordinate)) (first (cl-fillers pos @has-y-coordinate))))) (defun measurement4 () (let ((i 0) (s @s1)) (dotimes (i 1000) (incf i (pos-xy s)))))
4,264
Common Lisp
.lisp
118
33.144068
82
0.666099
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
b16512c2d5634e85053e60cab33506c775fab0646e01f95c324b149fa39152b3
11,199
[ -1 ]
11,200
example-clean.lisp
lambdamikel_GenEd/src/cc/example-clean.lisp
;;; -*- Syntax: ANSI-Common-Lisp; Package: krss-classic -*- (in-package krss-classic) (classic:cl-startup) ;;; ---------------------------------------------------------------------- ;;; ;;; Domain Model ;;; (define-primitive-concept person classic-thing) (define-primitive-concept loadable-object classic-thing) (define-primitive-concept container loadable-object) (define-primitive-concept passenger (and person loadable-object)) (define-primitive-role has-ship nil) (define-primitive-concept captain person) (define-primitive-role has-loadable-object nil) (define-primitive-role has-captain nil) (define-primitive-role has-position nil) (define-primitive-concept pos classic-thing) (define-primitive-role has-x-coordinate nil) (define-primitive-role has-y-coordinate nil) (define-primitive-concept ship (and (all has-loadable-object loadable-object) (at-least 1 has-position) (at-most 1 has-position) (all has-position pos) (at-least 1 has-captain) (at-most 1 has-captain) (all has-captain captain))) (define-concept passenger-ship (and ship (all has-loadable-object passenger))) (define-concept container-ship (and ship (all has-loadable-object container))) ;;; ---------------------------------------------------------------------- ;;; ;;; Functional interface to a knowledge base ;;; (define-accessors captain (has-ship captains-ship :single-value-p t)) (define-accessors ship (has-loadable-object ship-loadable-objects) (has-position ship-position :single-value-p t :error-if-null t) (has-captain ship-captain :single-value-p t :error-if-null t)) (define-method initialize-individual :after ((ind ship) &rest initargs) (let ((captain (ship-captain ind))) (setf (captains-ship captain) ind) (setf (ship-position ind) (create-individual 'pos (gensym "POS") 'has-x-coordinate 0 'has-y-coordinate 0)))) (define-accessors pos (has-x-coordinate position-x :single-value-p t :error-if-null t) (has-y-coordinate position-y :single-value-p t :error-if-null t)) (eval-when (:compile-toplevel :load-toplevel :execute) (define-generic-function ship-position-xy ((ship :classic))) (define-generic-function print-information-about-domain-object ((ind :classic) (stream :clos)) (:documentation "Demonstration function for method dispatch.")) ) (define-method ship-position-xy ((ind ship)) (let ((pos (ship-position ind))) (values (position-x pos) (position-y pos)))) ;;; ---------------------------------------------------------------------- ;;; ;;; Procedural code ;;; (define-method print-information-about-domain-object ((ind ship) stream) (format stream "~%Information about the ship ~S." ind) (classic:cl-print-object ind)) (define-method print-information-about-domain-object ((ind container-ship) stream) (format stream "~%Ah, a ship has been classified to a container ship ~ and the advantages of CLASSIC over CLOS become clear.") (call-next-method)) (define-method print-information-about-domain-object ((ind passenger-ship) stream) (format stream "~%Ah, a ship has been classified to a passenger ship ~ and the advantages of CLASSIC over CLOS become clear.") (call-next-method)) ;;; ---------------------------------------------------------------------- ;;; ;;; Individual creation ;;; #| (create-individual 'captain 'c1) (create-individual 'ship 's1 'has-captain (list @c1)) (print-information-about-domain-object @s1 *standard-output*) (state (instance s1 (all has-loadable-object passenger))) (print-information-about-domain-object @s1 *standard-output*) (ship-position @s1) (ship-position-xy @s1) |#
3,672
Common Lisp
.lisp
93
36.688172
82
0.681319
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
3eab9b42508f3aa34350983f65b371eccb2b89844f4feccb1291121c0b6ec4a4
11,200
[ -1 ]
11,201
newgeo6.lisp
lambdamikel_GenEd/src/geometry/newgeo6.lisp
;;; -*- Mode: LISP; Syntax: Ansi-Common-Lisp; Package: GEOMETRY -*- (in-package geometry) (defconstant +big-int+ 10000) (defparameter *tick-counter* 1) (defparameter *hash-table* (make-hash-table :size 200 :rehash-size 50)) ;;; ;;; Topological Relations for Polygons. ;;; ;;; ;;; Konstruktoren ;;; (defclass geom-thing () ((tickval :initform nil :accessor tickval :initarg :tickval))) (defclass geom-line (geom-thing) ((p1 :initform nil :initarg :p1 :accessor p1) (p2 :initform nil :initarg :p2 :accessor p2))) (defclass geom-point (geom-thing) ((x :initform 0 :initarg :x :accessor x) (y :initform 0 :initarg :y :accessor y))) (defclass geom-polygon (geom-thing) ((point-arr :initform nil :initarg :point-arr :accessor point-arr) ; range: 1..n (line-arr :initform nil :initarg :line-arr :accessor line-arr) ; range: 0..n/n-1 (closed :initform t :initarg :closed :accessor closed))) (defmethod get-points ((object geom-polygon)) (mapcan #'(lambda (point) (list (x point) (y point))) (coerce (point-arr object) 'list))) ;;; ;;; Basis-Funktionen ;;; (defmethod ccw ((p0 geom-point) (p1 geom-point) (p2 geom-point)) "Quelle: Sedgewick" (let* ((x0 (x p0)) (x1 (x p1)) (x2 (x p2)) (y0 (y p0)) (y1 (y p1)) (y2 (y p2)) (dx1 (- x1 x0)) (dy1 (- y1 y0)) (dx2 (- x2 x0)) (dy2 (- y2 y0))) (cond ((> (* dx1 dy2) (* dy1 dx2)) 1) ((< (* dx1 dy2) (* dy1 dx2)) -1) ((or (< (* dx1 dx2) 0) (< (* dy1 dy2) 0)) -1) ((< (+ (* dx1 dx1) (* dy1 dy1)) (+ (* dx2 dx2) (* dy2 dy2))) 1) (t 0)))) ;;; ;;; Hilfsfunktionen ;;; (defun make-geom-polygon (point-list &key (is-closed t) (tickval nil)) ; Fehler: wenn &key (closed t) ! (let* ((poly (make-instance 'geom-polygon :closed is-closed :tickval tickval))) (setf (point-arr poly) (make-geom-point-arr point-list) (line-arr poly) (make-geom-line-arr (point-arr poly) :closed is-closed)) poly)) (defun make-geom-point (x y &key (tickval nil)) (make-instance 'geom-point :x x :y y :tickval tickval)) (defun make-geom-point-arr (liste) (let ((arr (make-array (+ 2 (length liste)))) (i 1)) (dolist (elem liste) (setf (aref arr i) (make-geom-point (first elem) (second elem))) (incf i)) (setf (aref arr 0) (aref arr (1- i))) (setf (aref arr i) (aref arr 1)) arr)) (defun make-geom-line (p1 p2 &key (tickval nil)) (make-instance 'geom-line :p1 p1 :p2 p2 :tickval tickval)) (defun make-geom-line-arr (point-arr &key (closed t)) (let* ((dim (if closed (- (first (array-dimensions point-arr)) 2) (- (first (array-dimensions point-arr)) 3))) (arr (make-array (list dim)))) (dotimes (i dim) (setf (aref arr i) (make-geom-line (aref point-arr (+ i 1)) (aref point-arr (+ i 2))))) arr)) ;;;; ;;;; ;;;; (defun high-index (arr) (1- (first (array-dimensions arr)))) (defun calculate-bounding-box (arr) (let* ((minx (x (aref arr 0))) (miny (y (aref arr 0))) (maxx minx) (maxy miny)) (dotimes (i (1- (first (array-dimensions arr)))) (let* ((point (aref arr i)) (y (y point)) (x (x point))) (cond ((< x minx) (setf minx x)) ((> x maxx) (setf maxx x)) ((< y miny) (setf miny y)) ((> y maxy) (setf maxy y))))) (values minx miny maxx maxy))) (defun calculate-center (arr) (multiple-value-bind (xf yf xt yt) (calculate-bounding-box arr) (values (/ (+ xf xt) 2) (/ (+ yf yt) 2)))) ;;; ;;; Abstandsfunktionen ;;; (defmethod parallelp ((thing1 geom-thing) (thing2 geom-thing)) nil) (defmethod parallelp ((line1 geom-line) (line2 geom-line)) (let ((dx1 (- (x (p1 line1)) (x (p2 line1)))) (dx2 (- (x (p1 line2)) (x (p2 line2)))) (dy1 (- (y (p1 line1)) (y (p2 line1)))) (dy2 (- (y (p1 line2)) (y (p2 line2))))) (zerop (- (abs (* dx1 dy2)) (abs (* dx2 dy1)))))) ;;; ;;; ;;; (defmethod distance-between ((point1 geom-point) (point2 geom-point)) (let ((dx (- (x point1) (x point2))) (dy (- (y point1) (y point2)))) (sqrt (+ (* dx dx) (* dy dy))))) (defmethod distance-between ((line geom-line) (point geom-point)) (distance-between point line)) (defmethod distance-between ((point geom-point) (line geom-line)) (flet ((betw-0-and-1 (number) (and (not (minusp number)) (<= number 1.0)))) (let* ((lp1 (p1 line)) (lp2 (p2 line)) (lx1 (x lp1)) (ly1 (y lp1)) (lx2 (x lp2)) (ly2 (y lp2)) (px (x point)) (py (y point)) (ax (- lx2 lx1)) (ay (- ly2 ly1)) (dx (- lx1 px)) (dy (- ly1 py)) (a2 (+ (* ax ax) (* ay ay))) (scalar (if (zerop a2) +big-int+ (/ (+ (* ax (- dx)) (* ay (- dy))) a2))) (x (+ dx (* scalar ax))) (y (+ dy (* scalar ay)))) (if (betw-0-and-1 scalar) (sqrt (+ (* x x) (* y y))) (min (distance-between point (p1 line)) (distance-between point (p2 line))))))) (defmethod distance-between ((line1 geom-line) (line2 geom-line)) (let* ((d1 (distance-between (p1 line1) line2)) (d2 (distance-between (p2 line1) line2)) (d3 (distance-between (p1 line2) line1)) (d4 (distance-between (p2 line2) line1))) (min (min d1 d2 d3 d4)))) (defmethod distance-between ((poly1 geom-polygon) (poly2 geom-polygon)) (let* ( (line-arr1 (line-arr poly1)) (line-arr2 (line-arr poly2)) (ind1 (high-index line-arr1)) (ind2 (high-index line-arr2))) (loop for i from 0 to ind1 minimize (loop for j from 0 to ind2 minimize (distance-between (aref line-arr1 i) (aref line-arr2 j)))))) (defmethod distance-between ((line geom-line) (poly geom-polygon)) (let ( (line-arr (line-arr poly))) (loop for i from 0 to (high-index line-arr) minimize (distance-between (aref line-arr i) line)))) (defmethod distance-between ((poly geom-polygon) (line geom-line)) (distance-between line poly)) (defmethod distance-between ((poly geom-polygon) (point geom-point)) (let ( (line-arr (line-arr poly))) (loop for i from 0 to (high-index line-arr) minimize (distance-between point (aref line-arr i))))) (defmethod distance-between ((point geom-point) (poly geom-polygon)) (distance-between poly point)) ;;; ;;; ;;; (defmethod inside-s ((point1 geom-point) (point2 geom-point)) nil) (defmethod inside-s ((point geom-point) (line geom-line)) nil) (defmethod inside-s ((line geom-line) (point geom-point)) nil) (defmethod inside-s ((line1 geom-line) (line2 geom-line)) nil) (defmethod inside-s ((polygon geom-polygon) (point geom-point)) nil) (defmethod inside-s ((polygon geom-polygon) (line geom-line)) nil) (defmethod inside-s ((point geom-point) (polygon geom-polygon)) "Nicht ganz korrekt !!! Quelle: Sedgewick, modifiziert!" (when (closed polygon) (let* ((count1 0) (count2 0) (j 0) (arr (point-arr polygon)) (n (- (first (array-dimensions arr)) 2)) (x (x point)) (y (y point)) (lp (make-geom-line (make-geom-point 0 0) (make-geom-point 0 0))) (lt (make-geom-line (make-geom-point x y) (make-geom-point +big-int+ y)))) ; wegen ALIAS-Effekten! (dotimes (m n) (let ((i (1+ m))) (setf (p1 lp) (aref arr i)) (when (and (not (and (= (y (p1 lp)) (y (p1 lt))) (>= (x (p1 lp)) (x (p1 lt))))) (not (and (= (y (aref arr j)) (y (p1 lt))) (>= (x (aref arr j)) (x (p1 lt)))))) (setf (p2 lp) (aref arr j)) (setf j i) (when (intersects-s lp lt :dim nil) (incf count1))))) (let ((lt (make-geom-line (make-geom-point x y) (make-geom-point (- +big-int+) y)))) ; wegen ALIAS-Effekten! (dotimes (m n) (let ((i (1+ m))) (setf (p1 lp) (aref arr i)) (when (and (not (and (= (y (p1 lp)) (y (p1 lt))) (<= (x (p1 lp)) (x (p1 lt))))) (not (and (= (y (aref arr j)) (y (p1 lt))) (<= (x (aref arr j)) (x (p1 lt)))))) (setf (p2 lp) (aref arr j)) (setf j i) (when (intersects-s lp lt :dim nil) (incf count2))))) (or (not (zerop (mod count1 2))) (not (zerop (mod count2 2)))))))) (defmethod inside-s ((poly1 geom-polygon) (poly2 geom-polygon)) (when (closed poly2) (let* ((arr (point-arr poly1)) (ok (dotimes (i (- (first (array-dimensions arr)) 2)) (when (not (inside-s (aref arr (1+ i)) poly2)) (return t))))) (not ok)))) (defmethod inside-s ((line geom-line) (poly geom-polygon)) (and (not (intersects-s line poly :dim nil)) (inside-s (p1 line) poly) (inside-s (p2 line) poly))) ;;; ;;; ;;; (defmethod inside ((object1 geom-thing) (object2 geom-thing)) "Fuer Aussen-Benutzung" (and (not (intersects-s object1 object2 :dim nil)) (inside-s object1 object2))) ;;; ;;; ;;; (defmethod intersects-s ((point1 geom-point) (point2 geom-point) &key &allow-other-keys) (values nil nil)) (defmethod intersects-s ((point geom-point) (line geom-line) &key (dim nil)) (if (or (zerop (ccw (p1 line) (p2 line) point)) (zerop (ccw (p2 line) (p1 line) point))) (if dim (values t 0) t) (if dim (values nil nil) nil))) (defmethod intersects-s ((line geom-line) (point geom-point) &key (dim nil)) (intersects-s point line :dim dim)) (defmethod intersects-s ((l1 geom-line) (l2 geom-line) &key (dim nil)) "Quelle: Sedgewick" (let ((l1p1 (p1 l1)) (l2p1 (p1 l2)) (l1p2 (p2 l1)) (l2p2 (p2 l2))) (let ((a1 (* (ccw l1p1 l1p2 l2p1) (ccw l1p1 l1p2 l2p2))) (a2 (* (ccw l2p1 l2p2 l1p1) (ccw l2p1 l2p2 l1p2)))) (if (and (<= a1 0) (<= a2 0)) (if dim (if (and (parallelp l1 l2) (not (or (and (same-point l1p1 l2p1) (not (intersects-s l1 l2p2 :dim nil))) (and (same-point l1p1 l2p2) (not (intersects-s l1 l2p1 :dim nil))) (and (same-point l1p2 l2p1) (not (intersects-s l1 l2p2 :dim nil))) (and (same-point l1p2 l2p2) (not (intersects-s l1 l2p1 :dim nil)))))) (values t 1) (values t 0)) t) (if dim (values nil nil) nil))))) (defun same-point (p1 p2) (and (= (x p1) (x p2)) (= (y p1) (y p2)))) #| (defmethod intersects-s ((line geom-line) (poly geom-polygon)) (let* ((larr (line-arr poly)) (max-dim (loop for i from 0 to (1- (first (array-dimensions larr))) maximize (multiple-value-bind (intersectsp dim) (intersects-s (aref larr i) line) (if intersectsp dim -1))))) (if (minusp max-dim) (values nil nil) (values t max-dim)))) |# (defmethod intersects-s ((line geom-line) (poly geom-polygon) &key (dim nil)) (let* ((larr (line-arr poly))) (if dim (let ((max-dim (loop for i from 0 to (1- (first (array-dimensions larr))) maximize (multiple-value-bind (intersectsp dim) (intersects-s (aref larr i) line :dim t) (if intersectsp dim -1))))) (if (minusp max-dim) (values nil nil) (values t (max max-dim (if (closed poly) (calculate-dim-of-intersect line poly) -1) )))) (loop for i from 0 to (1- (first (array-dimensions larr))) thereis (intersects-s (aref larr i) line :dim nil))))) (defmethod calculate-dim-of-intersect ((line geom-line) (poly geom-polygon)) (if (one-part-is-inside line poly) 1 0)) (defconstant +epsilon+ 3) (defmethod one-part-is-inside ((line geom-line) (poly geom-polygon)) (let* ((p1 (p1 line)) (p2 (p2 line)) (d (distance-between p1 p2))) (cond ((and (inside-s p1 poly) (inside-s p2 poly)) t) ((< d +epsilon+) nil) (t (let* ((middle-point (make-geom-point (round (/ (+ (x p1) (x p2)) 2)) (round (/ (+ (y p1) (y p2)) 2)))) (l1 (make-geom-line p1 middle-point)) (l2 (make-geom-line middle-point p2))) (or (one-part-is-inside l1 poly) (one-part-is-inside l2 poly))))))) (defmethod intersects-s ((poly geom-polygon) (line geom-line) &key (dim nil)) (intersects-s line poly :dim dim)) (defmethod intersects-s ((poly1 geom-polygon) (poly2 geom-polygon) &key (dim nil)) (let* ((arr (line-arr poly1)) (parr (point-arr poly1)) (counter 0)) (if dim (let ((max-dim (loop for i from 0 to (1- (first (array-dimensions arr))) maximize (multiple-value-bind (intersectsp dim) (intersects-s (aref arr i) poly2 :dim t) (if intersectsp (progn (incf counter) dim) -1))))) (if (minusp max-dim) (values nil nil) (values t (if (and (> counter 1) (closed poly1) (loop for i from 0 to (1- (first (array-dimensions parr))) thereis (inside (aref parr i) poly2))) 2 max-dim)))) (loop for i from 0 to (1- (first (array-dimensions arr))) thereis (intersects-s (aref arr i) poly2 :dim nil))))) (defmethod intersects-s ((point geom-point) (poly geom-polygon) &key (dim nil)) (let* ((arr (line-arr poly)) (ok (dotimes (i (first (array-dimensions arr))) (if (intersects-s point (aref arr i) :dim nil) (return t))))) (if ok (if dim (values t 0) t) (if dim (values nil nil) nil)))) (defmethod intersects-s ((poly geom-polygon) (point geom-point) &key (dim nil)) (intersects-s point poly :dim dim)) ;;; ;;; (defmethod intersects ((thing1 geom-thing) (thing2 geom-thing) &key (dim nil)) (if dim (multiple-value-bind (ip1 dim1) (intersects-s thing1 thing2 :dim t) (if (not ip1) (values nil nil) (multiple-value-bind (ip2 dim2) (intersects-s thing2 thing1 :dim t) (values t (max dim1 dim2))))) (intersects-s thing1 thing2 :dim nil))) ;;; ;;; ;;; (defmethod touching-tres ((thing1 geom-thing) (thing2 geom-thing) tres) "Arbeitet mit dem minimalen Abstand. Fuer Aussen-Benutzung" (and (not (intersects-s thing1 thing2 :dim nil)) (let ((d (distance-between thing1 thing2))) (if (<= d tres) d)))) ;;; ;;; ;;; (defmethod covers-tres ((thing1 geom-thing) (thing2 geom-thing) tres) "Fuer Aussen-Benutzung" (and (inside-s thing2 thing1) (touching-tres thing2 thing1 tres))) ;;; ;;; ;;; (defun distance-and-orientation (x1 y1 x2 y2) (let* ( (dx (- x2 x1)) (dy (- y2 y1)) (d (sqrt (+ (* dx dx) (* dy dy)))) (phi (if (zerop dx) (if (minusp dy) (- (/ pi 2)) (/ pi 2)) (atan (/ dy dx)))) (phi2 (if (minusp dx) (+ phi pi) phi))) (values d phi2))) ;;; ;;; Master-Function ;;; (defun inverse (relation) (case relation (is-inside 'contains) (is-covered-by 'covers) (contains 'is-inside) (covers 'is-covered-by) (t relation))) (defun clear-hashtable () (clrhash *hash-table*)) (defun delete-object-from-cache (thing object-liste) (dolist (elem object-liste) (unless (eq elem thing) (let* ((goedel1 (get-goedel thing elem)) (goedel2 (get-goedel elem thing))) (remhash goedel1 *hash-table*) (remhash goedel2 *hash-table*))))) #| (defun get-goedel (x y) (unless (tickval x) (setf (tickval x) (incf *tick-counter*))) (unless (tickval y) (setf (tickval y) (incf *tick-counter*))) (let ((r (* (expt 2 (tickval x)) (expt 3 (tickval y))))) r)) |# (defconstant +hash-table-delta+ 3000) (defun get-goedel (x y) (unless (tickval x) (setf (tickval x) (incf *tick-counter*))) (unless (tickval y) (setf (tickval y) (incf *tick-counter*))) (+ (* +hash-table-delta+ (tickval x)) (tickval y))) ;;; ;;; ;;; (defun relate-poly-to-poly-unary-tres (thing1 thing2 tres &key (dim nil)) (or (gethash (get-goedel thing1 thing2) *hash-table*) (inverse (gethash (get-goedel thing2 thing1) *hash-table*)) (let ((relation (if (intersects thing1 thing2 :dim nil) (if dim (multiple-value-bind (intersectsp dim) (intersects thing1 thing2 :dim t) (case dim (0 'intersects-0) (1 'intersects-1) (2 'intersects-2))) 'intersects) (if (inside-s thing1 thing2) (let ((d (distance-between thing1 thing2))) (if (<= d tres) 'is-covered-by 'is-inside)) (if (inside-s thing2 thing1) (let ((d (distance-between thing2 thing1))) (if (<= d tres) 'covers 'contains)) (let ((d (distance-between thing1 thing2))) (if (<= d tres) 'touches 'is-disjoint-with))))))) (setf (gethash (get-goedel thing1 thing2) *hash-table*) relation) relation)))
17,210
Common Lisp
.lisp
582
24.001718
93
0.578057
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e0807caf450e2c9e04b9d7c0b0a5b18ae59e9b1712aabac36a996036090c5ba9
11,201
[ -1 ]
11,202
newgeo7.lisp
lambdamikel_GenEd/src/geometry/newgeo7.lisp
;;; -*- Mode: LISP; Syntax: Ansi-Common-Lisp; Package: GEOMETRY -*- (in-package geometry) (defconstant +big-int+ 10000) (defparameter *tick-counter* 1) (defparameter *hash-table* (make-hash-table :size 200 :rehash-size 50)) ;;; ;;; Topological Relations for Polygons. ;;; ;;; ;;; ;;; (defclass geom-thing () ((tickval :initform nil :accessor tickval :initarg :tickval))) (defclass geom-line (geom-thing) ((p1 :initform nil :initarg :p1 :accessor p1) (p2 :initform nil :initarg :p2 :accessor p2))) (defclass geom-point (geom-thing) ((x :initform 0 :initarg :x :accessor x) (y :initform 0 :initarg :y :accessor y))) (defclass geom-polygon (geom-thing) ((point-arr :initform nil :initarg :point-arr :accessor point-arr) (line-arr :initform nil :initarg :line-arr :accessor line-arr) (closed :initform t :initarg :closed :accessor closed))) (defmethod get-points ((object geom-polygon)) (mapcan #'(lambda (point) (list (x point) (y point))) (coerce (point-arr object) 'list))) ;;; ;;; ;;; (defmethod ccw ((p0 geom-point) (p1 geom-point) (p2 geom-point)) "Quelle: Sedgewick" (let* ((x0 (x p0)) (x1 (x p1)) (x2 (x p2)) (y0 (y p0)) (y1 (y p1)) (y2 (y p2)) (dx1 (- x1 x0)) (dy1 (- y1 y0)) (dx2 (- x2 x0)) (dy2 (- y2 y0))) (cond ((> (* dx1 dy2) (* dy1 dx2)) 1) ((< (* dx1 dy2) (* dy1 dx2)) -1) ((or (< (* dx1 dx2) 0) (< (* dy1 dy2) 0)) -1) ((< (+ (* dx1 dx1) (* dy1 dy1)) (+ (* dx2 dx2) (* dy2 dy2))) 1) (t 0)))) ;;; ;;; ;;; (defun make-geom-polygon (point-list &key (is-closed t) (tickval nil)) (let* ((poly (make-instance 'geom-polygon :closed is-closed :tickval tickval))) (setf (point-arr poly) (make-geom-point-arr point-list) (line-arr poly) (make-geom-line-arr (point-arr poly) :closed is-closed)) poly)) (defun make-geom-point (x y &key (tickval nil)) (make-instance 'geom-point :x x :y y :tickval tickval)) (defun make-geom-point-arr (liste) (let ((arr (make-array (+ 2 (length liste)))) (i 1)) (dolist (elem liste) (setf (aref arr i) (make-geom-point (first elem) (second elem))) (incf i)) (setf (aref arr 0) (aref arr (1- i))) (setf (aref arr i) (aref arr 1)) arr)) (defun make-geom-line (p1 p2 &key (tickval nil)) (make-instance 'geom-line :p1 p1 :p2 p2 :tickval tickval)) (defun make-geom-line-arr (point-arr &key (closed t)) (let* ((dim (if closed (- (first (array-dimensions point-arr)) 2) (- (first (array-dimensions point-arr)) 3))) (arr (make-array (list dim)))) (dotimes (i dim) (setf (aref arr i) (make-geom-line (aref point-arr (+ i 1)) (aref point-arr (+ i 2))))) arr)) ;;;; ;;;; ;;;; (defun high-index (arr) (1- (first (array-dimensions arr)))) (defun calculate-bounding-box (arr) (let* ((minx (x (aref arr 0))) (miny (y (aref arr 0))) (maxx minx) (maxy miny)) (dotimes (i (1- (first (array-dimensions arr)))) (let* ((point (aref arr i)) (y (y point)) (x (x point))) (cond ((< x minx) (setf minx x)) ((> x maxx) (setf maxx x)) ((< y miny) (setf miny y)) ((> y maxy) (setf maxy y))))) (values minx miny maxx maxy))) (defun calculate-center (arr) (multiple-value-bind (xf yf xt yt) (calculate-bounding-box arr) (values (/ (+ xf xt) 2) (/ (+ yf yt) 2)))) ;;; ;;; Abstandsfunktionen ;;; (defmethod parallelp ((thing1 geom-thing) (thing2 geom-thing)) nil) (defmethod parallelp ((line1 geom-line) (line2 geom-line)) (let ((dx1 (- (x (p1 line1)) (x (p2 line1)))) (dx2 (- (x (p1 line2)) (x (p2 line2)))) (dy1 (- (y (p1 line1)) (y (p2 line1)))) (dy2 (- (y (p1 line2)) (y (p2 line2))))) (or (zerop (- (* dx1 dy2) (* dx2 dy1))) (zerop (- (* dx2 dy1) (* dx1 dy2)))))) ;;; ;;; ;;; (defmethod distance-between ((point1 geom-point) (point2 geom-point)) (let ((dx (- (x point1) (x point2))) (dy (- (y point1) (y point2)))) (sqrt (+ (* dx dx) (* dy dy))))) (defmethod distance-between ((line geom-line) (point geom-point)) (distance-between point line)) (defmethod distance-between ((point geom-point) (line geom-line)) (flet ((betw-0-and-1 (number) (and (not (minusp number)) (<= number 1.0)))) (let* ((lp1 (p1 line)) (lp2 (p2 line)) (lx1 (x lp1)) (ly1 (y lp1)) (lx2 (x lp2)) (ly2 (y lp2)) (px (x point)) (py (y point)) (ax (- lx2 lx1)) (ay (- ly2 ly1)) (dx (- lx1 px)) (dy (- ly1 py)) (a2 (+ (* ax ax) (* ay ay))) (scalar (if (zerop a2) +big-int+ (/ (+ (* ax (- dx)) (* ay (- dy))) a2))) (x (+ dx (* scalar ax))) (y (+ dy (* scalar ay)))) (if (betw-0-and-1 scalar) (sqrt (+ (* x x) (* y y))) (min (distance-between point (p1 line)) (distance-between point (p2 line))))))) (defmethod distance-between ((line1 geom-line) (line2 geom-line)) (let* ((d1 (distance-between (p1 line1) line2)) (d2 (distance-between (p2 line1) line2)) (d3 (distance-between (p1 line2) line1)) (d4 (distance-between (p2 line2) line1))) (min d1 d2 d3 d4))) (defmethod distance-between ((poly1 geom-polygon) (poly2 geom-polygon)) (let* ( (line-arr1 (line-arr poly1)) (line-arr2 (line-arr poly2)) (ind1 (high-index line-arr1)) (ind2 (high-index line-arr2))) (loop for i from 0 to ind1 minimize (loop for j from 0 to ind2 minimize (distance-between (aref line-arr1 i) (aref line-arr2 j)))))) (defmethod distance-between ((line geom-line) (poly geom-polygon)) (let ( (line-arr (line-arr poly))) (loop for i from 0 to (high-index line-arr) minimize (distance-between (aref line-arr i) line)))) (defmethod distance-between ((poly geom-polygon) (line geom-line)) (distance-between line poly)) (defmethod distance-between ((poly geom-polygon) (point geom-point)) (let ( (line-arr (line-arr poly))) (loop for i from 0 to (high-index line-arr) minimize (distance-between point (aref line-arr i))))) (defmethod distance-between ((point geom-point) (poly geom-polygon)) (distance-between poly point)) ;;; ;;; ;;; (defmethod inside-s ((point1 geom-point) (point2 geom-point)) nil) (defmethod inside-s ((point geom-point) (line geom-line)) nil) (defmethod inside-s ((line geom-line) (point geom-point)) nil) (defmethod inside-s ((line1 geom-line) (line2 geom-line)) nil) (defmethod inside-s ((polygon geom-polygon) (point geom-point)) nil) (defmethod inside-s ((polygon geom-polygon) (line geom-line)) nil) (defmethod inside-s ((point geom-point) (polygon geom-polygon)) "Nicht ganz korrekt !!! Quelle: Sedgewick, modifiziert!" (when (closed polygon) (let* ((count1 0) (count2 0) (j 0) (arr (point-arr polygon)) (n (- (first (array-dimensions arr)) 2)) (x (x point)) (y (y point)) (lp (make-geom-line (make-geom-point 0 0) (make-geom-point 0 0))) (lt (make-geom-line (make-geom-point x y) (make-geom-point +big-int+ y)))) (dotimes (m n) (let ((i (1+ m))) (setf (p1 lp) (aref arr i)) (when (and (not (and (= (y (p1 lp)) (y (p1 lt))) (>= (x (p1 lp)) (x (p1 lt))))) (not (and (= (y (aref arr j)) (y (p1 lt))) (>= (x (aref arr j)) (x (p1 lt)))))) (setf (p2 lp) (aref arr j)) (setf j i) (when (intersects-s lp lt :dim nil) (incf count1))))) (let ((lt (make-geom-line (make-geom-point x y) (make-geom-point (- +big-int+) y)))) (dotimes (m n) (let ((i (1+ m))) (setf (p1 lp) (aref arr i)) (when (and (not (and (= (y (p1 lp)) (y (p1 lt))) (<= (x (p1 lp)) (x (p1 lt))))) (not (and (= (y (aref arr j)) (y (p1 lt))) (<= (x (aref arr j)) (x (p1 lt)))))) (setf (p2 lp) (aref arr j)) (setf j i) (when (intersects-s lp lt :dim nil) (incf count2))))) (or (not (zerop (mod count1 2))) (not (zerop (mod count2 2)))))))) (defmethod inside-s ((poly1 geom-polygon) (poly2 geom-polygon)) (when (closed poly2) (let* ((arr (point-arr poly1)) (ok (dotimes (i (- (first (array-dimensions arr)) 2)) (when (not (inside-s (aref arr (1+ i)) poly2)) (return t))))) (not ok)))) (defmethod inside-s ((line geom-line) (poly geom-polygon)) (and (not (intersects-s line poly :dim nil)) (inside-s (p1 line) poly) (inside-s (p2 line) poly))) ;;; ;;; ;;; (defmethod inside ((object1 geom-thing) (object2 geom-thing)) "Fuer Aussen-Benutzung" (and (not (intersects-s object1 object2 :dim nil)) (inside-s object1 object2))) ;;; ;;; ;;; (defmethod intersects-s ((point1 geom-point) (point2 geom-point) &key &allow-other-keys) (values nil nil)) (defmethod intersects-s ((point geom-point) (line geom-line) &key (dim nil)) (if (or (zerop (ccw (p1 line) (p2 line) point)) (zerop (ccw (p2 line) (p1 line) point))) (if dim (values t 0) t) (if dim (values nil nil) nil))) (defmethod intersects-s ((line geom-line) (point geom-point) &key (dim nil)) (intersects-s point line :dim dim)) (defmethod intersects-s ((l1 geom-line) (l2 geom-line) &key (dim nil) (top-level-use t)) "Quelle: Sedgewick" (let ((l1p1 (p1 l1)) (l2p1 (p1 l2)) (l1p2 (p2 l1)) (l2p2 (p2 l2))) (let ((a1 (* (ccw l1p1 l1p2 l2p1) (ccw l1p1 l1p2 l2p2))) (a2 (* (ccw l2p1 l2p2 l1p1) (ccw l2p1 l2p2 l1p2)))) (if (and (<= a1 0) (<= a2 0)) (if dim (if (parallelp l1 l2) (let ((l1p1-on-l2 (intersects l1p1 l2 :dim nil)) (l1p2-on-l2 (intersects l1p2 l2 :dim nil)) (l2p1-on-l1 (intersects l2p1 l1 :dim nil)) (l2p2-on-l1 (intersects l2p2 l1 :dim nil))) (if (or (and l1p1-on-l2 l1p2-on-l2) (and l2p1-on-l1 l2p2-on-l1) (not (or (and (same-point l1p1 l2p1) l1p1-on-l2 l2p1-on-l1) (and (same-point l1p1 l2p2) l1p1-on-l2 l2p2-on-l1) (and (same-point l1p2 l2p1) l1p2-on-l2 l2p1-on-l1) (and (same-point l1p2 l2p2) l1p2-on-l2 l2p2-on-l1)))) (values t (if top-level-use 1 'par)) (values t 0))) (values t 0)) t) (if dim (values nil nil) nil))))) (defun same-point (p1 p2) (and (= (x p1) (x p2)) (= (y p1) (y p2)))) (defun point< (p1 p2) (and (< (x p1) (x p2)) (< (y p1) (y p2)))) (defun point> (p1 p2) (and (> (x p1) (x p2)) (> (y p1) (y p2)))) (defmethod intersects-s ((line geom-line) (poly geom-polygon) &key (dim nil) (recursive-descent t) (top-level-use t)) (let* ((larr (line-arr poly)) (par)) (if dim (let ((max-dim (loop for i from 0 to (1- (first (array-dimensions larr))) maximize (multiple-value-bind (intersectsp dim) (intersects-s (aref larr i) line :dim t :top-level-use nil) (if intersectsp (if (numberp dim) dim (progn (setf par t) 1)) -1))))) (if (minusp max-dim) (values nil nil) (if (not par) (progn (values t (max max-dim (if (and (closed poly) recursive-descent) (calculate-dim-of-intersect line poly) -1)))) (values t (if top-level-use 1 'par))))) (loop for i from 0 to (1- (first (array-dimensions larr))) thereis (intersects-s (aref larr i) line :dim nil))))) (defmethod intersects-s ((poly geom-polygon) (line geom-line) &key (dim nil) (recursive-descent t) (top-level-use t)) (intersects-s line poly :dim dim :recursive-descent recursive-descent :top-level-use top-level-use)) (defmethod calculate-dim-of-intersect ((line geom-line) (poly geom-polygon)) (if (one-part-is-inside line poly) 1 0)) (defconstant +epsilon+ 3) (defmethod one-part-is-inside ((line geom-line) (poly geom-polygon)) (let* ((p1 (p1 line)) (p2 (p2 line)) (d (distance-between p1 p2))) (cond ((and (inside-s p1 poly) (inside-s p2 poly)) t) ((< d +epsilon+) nil) (t (let* ((middle-point (make-geom-point (/ (+ (x p1) (x p2)) 2) (/ (+ (y p1) (y p2)) 2))) (l1 (make-geom-line p1 middle-point)) (l2 (make-geom-line middle-point p2))) (or (one-part-is-inside l1 poly) (one-part-is-inside l2 poly))))))) (defmethod intersects-s ((poly1 geom-polygon) (poly2 geom-polygon) &key (dim nil)) (let* ((arr (line-arr poly1)) (counter 0) (col) (parlist)) (if dim (let ((max-dim (loop for i from 0 to (1- (first (array-dimensions arr))) maximize (multiple-value-bind (intersectsp dim) (intersects-s (aref arr i) poly2 :dim t :top-level-use nil :recursive-descent t) (cond ( (eq dim 'par) (push i parlist) 1) ( intersectsp (push i col) (incf counter) dim) (t -1)))))) (if (minusp max-dim) (values nil nil) (values t (if (and (> counter 0) (closed poly1) (loop for line in col thereis (let ((dim (calculate-dim-of-intersect (aref arr line) poly2))) (= dim 1)))) 2 max-dim)))) (loop for i from 0 to (1- (first (array-dimensions arr))) thereis (intersects-s (aref arr i) poly2 :dim nil))))) (defmethod intersects-s ((point geom-point) (poly geom-polygon) &key (dim nil)) (let* ((arr (line-arr poly)) (ok (dotimes (i (first (array-dimensions arr))) (if (intersects-s point (aref arr i) :dim nil) (return t))))) (if ok (if dim (values t 0) t) (if dim (values nil nil) nil)))) (defmethod intersects-s ((poly geom-polygon) (point geom-point) &key (dim nil)) (intersects-s point poly :dim dim)) ;;; ;;; (defmethod intersects ((thing1 geom-thing) (thing2 geom-thing) &key (dim nil)) (if dim (multiple-value-bind (ip1 dim1) (intersects-s thing1 thing2 :dim t) (if (not ip1) (values nil nil) (if (< dim1 2) (multiple-value-bind (ip2 dim2) (intersects-s thing2 thing1 :dim t) (declare (ignore ip2)) (values t (max dim1 dim2))) (values t 2)))) (intersects-s thing1 thing2 :dim nil))) ;;; ;;; ;;; (defmethod touching-tres ((thing1 geom-thing) (thing2 geom-thing) tres) "Arbeitet mit dem minimalen Abstand. Fuer Aussen-Benutzung" (and (not (intersects-s thing1 thing2 :dim nil)) (let ((d (distance-between thing1 thing2))) (if (<= d tres) d)))) ;;; ;;; ;;; (defmethod covers-tres ((thing1 geom-thing) (thing2 geom-thing) tres) "Fuer Aussen-Benutzung" (and (inside-s thing2 thing1) (touching-tres thing2 thing1 tres))) ;;; ;;; ;;; (defun distance-and-orientation (x1 y1 x2 y2) (let* ( (dx (- x2 x1)) (dy (- y2 y1)) (d (sqrt (+ (* dx dx) (* dy dy)))) (phi (if (zerop dx) (if (minusp dy) (- (/ pi 2)) (/ pi 2)) (atan (/ dy dx)))) (phi2 (if (minusp dx) (+ phi pi) phi))) (values d phi2))) ;;; ;;; Master-Function ;;; (defun inverse (relation) (case relation (is-inside 'contains) (is-covered-by 'covers) (contains 'is-inside) (covers 'is-covered-by) (t relation))) (defun clear-hashtable () (clrhash *hash-table*)) (defun delete-object-from-cache (thing object-liste) (dolist (elem object-liste) (unless (eq elem thing) (let* ((goedel1 (get-goedel thing elem)) (goedel2 (get-goedel elem thing))) (remhash goedel1 *hash-table*) (remhash goedel2 *hash-table*))))) #| (defun get-goedel (x y) (unless (tickval x) (setf (tickval x) (incf *tick-counter*))) (unless (tickval y) (setf (tickval y) (incf *tick-counter*))) (let ((r (* (expt 2 (tickval x)) (expt 3 (tickval y))))) r)) |# (defconstant +hash-table-delta+ 3000) (defun get-goedel (x y) (unless (tickval x) (setf (tickval x) (incf *tick-counter*))) (unless (tickval y) (setf (tickval y) (incf *tick-counter*))) (+ (* +hash-table-delta+ (tickval x)) (tickval y))) ;;; ;;; ;;; (defun relate-poly-to-poly-unary-tres (thing1 thing2 tres &key (dim nil)) (or (gethash (get-goedel thing1 thing2) *hash-table*) (inverse (gethash (get-goedel thing2 thing1) *hash-table*)) (let ((relation (if (intersects thing1 thing2 :dim nil) (if dim (multiple-value-bind (intersectsp dim) (intersects thing1 thing2 :dim t) (declare (ignore intersectsp)) (case dim (0 'intersects-0) (1 'intersects-1) (2 'intersects-2))) 'intersects) (if (inside-s thing1 thing2) (let ((d (distance-between thing1 thing2))) (if (<= d tres) 'is-covered-by 'is-inside)) (if (inside-s thing2 thing1) (let ((d (distance-between thing2 thing1))) (if (<= d tres) 'covers 'contains)) (let ((d (distance-between thing1 thing2))) (if (<= d tres) 'touches 'is-disjoint-with))))))) (setf (gethash (get-goedel thing1 thing2) *hash-table*) relation) (remhash (get-goedel thing2 thing1) *hash-table*) relation)))
20,283
Common Lisp
.lisp
613
23.375204
119
0.500052
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
b074e86525bfb76da8a931f040b869d7027d482fdc28cf62a2ae9562ee7fe65f
11,202
[ -1 ]
11,203
disk.lisp
lambdamikel_GenEd/src/geometry/disk.lisp
(defconstant +big-int+ 10000) (defparameter *tick-counter* 1) (defparameter *hash-table* (make-hash-table :size 200 :rehash-size 50)) ;;; ;;; Topological Relations for Polygons. ;;; ;;; ;;; Konstruktoren ;;; (defclass geom-thing () ((tickval :initform nil :accessor tickval :initarg :tickval))) (defclass geom-line (geom-thing) ((p1 :initform nil :initarg :p1 :accessor p1) (p2 :initform nil :initarg :p2 :accessor p2))) (defclass geom-point (geom-thing) ((x :initform 0 :initarg :x :accessor x) (y :initform 0 :initarg :y :accessor y))) (defclass geom-polygon (geom-thing) ((point-arr :initform nil :initarg :point-arr :accessor point-arr) ; range: 1..n (line-arr :initform nil :initarg :line-arr :accessor line-arr) ; range: 0..n/n-1 (closed :initform t :initarg :closed :accessor closed))) (defmethod get-points ((object geom-polygon)) (mapcan #'(lambda (point) (list (x point) (y point))) (coerce (point-arr object) 'list))) ;;; ;;; Basis-Funktionen ;;; (defmethod ccw ((p0 geom-point) (p1 geom-point) (p2 geom-point)) "Quelle: Sedgewick" (let* ((x0 (x p0)) (x1 (x p1)) (x2 (x p2)) (y0 (y p0)) (y1 (y p1)) (y2 (y p2)) (dx1 (- x1 x0)) (dy1 (- y1 y0)) (dx2 (- x2 x0)) (dy2 (- y2 y0))) (cond ((> (* dx1 dy2) (* dy1 dx2)) 1) ((< (* dx1 dy2) (* dy1 dx2)) -1) ((or (< (* dx1 dx2) 0) (< (* dy1 dy2) 0)) -1) ((< (+ (* dx1 dx1) (* dy1 dy1)) (+ (* dx2 dx2) (* dy2 dy2))) 1) (t 0)))) ;;; ;;; Hilfsfunktionen ;;; (defun make-geom-polygon (point-list &key (is-closed t) (tickval nil)) ; Fehler: wenn &key (closed t) ! (let* ((poly (make-instance 'geom-polygon :closed is-closed :tickval tickval))) (setf (point-arr poly) (make-geom-point-arr point-list) (line-arr poly) (make-geom-line-arr (point-arr poly) :closed is-closed)) poly)) (defun make-geom-point (x y &key (tickval nil)) (make-instance 'geom-point :x x :y y :tickval tickval)) (defun make-geom-point-arr (liste) (let ((arr (make-array (+ 2 (length liste)))) (i 1)) (dolist (elem liste) (setf (aref arr i) (make-geom-point (first elem) (second elem))) (incf i)) (setf (aref arr 0) (aref arr (1- i))) (setf (aref arr i) (aref arr 1)) arr)) (defun make-geom-line (p1 p2 &key (tickval nil)) (make-instance 'geom-line :p1 p1 :p2 p2 :tickval tickval)) (defun make-geom-line-arr (point-arr &key (closed t)) (let* ((dim (if closed (- (first (array-dimensions point-arr)) 2) (- (first (array-dimensions point-arr)) 3))) (arr (make-array (list dim)))) (dotimes (i dim) (setf (aref arr i) (make-geom-line (aref point-arr (+ i 1)) (aref point-arr (+ i 2))))) arr)) ;;;; ;;;; ;;;; (defun high-index (arr) (1- (first (array-dimensions arr)))) (defun calculate-bounding-box (arr) (let* ((minx (x (aref arr 0))) (miny (y (aref arr 0))) (maxx minx) (maxy miny)) (dotimes (i (1- (first (array-dimensions arr)))) (let* ((point (aref arr i)) (y (y point)) (x (x point))) (cond ((< x minx) (setf minx x)) ((> x maxx) (setf maxx x)) ((< y miny) (setf miny y)) ((> y maxy) (setf maxy y))))) (values minx miny maxx maxy))) (defun calculate-center (arr) (multiple-value-bind (xf yf xt yt) (calculate-bounding-box arr) (values (/ (+ xf xt) 2) (/ (+ yf yt) 2)))) ;;; ;;; Abstandsfunktionen ;;; (defmethod parallelp ((thing1 geom-thing) (thing2 geom-thing)) nil) (defmethod parallelp ((line1 geom-line) (line2 geom-line)) (let ((dx1 (- (x (p1 line1)) (x (p2 line1)))) (dx2 (- (x (p1 line2)) (x (p2 line2)))) (dy1 (- (y (p1 line1)) (y (p2 line1)))) (dy2 (- (y (p1 line2)) (y (p2 line2))))) (or (zerop (- (* dx1 dy2) (* dx2 dy1))) (zerop (- (* dx2 dy1) (* dx1 dy2)))))) ;;; ;;; ;;; (defmethod distance-between ((point1 geom-point) (point2 geom-point)) (let ((dx (- (x point1) (x point2))) (dy (- (y point1) (y point2)))) (sqrt (+ (* dx dx) (* dy dy))))) (defmethod distance-between ((line geom-line) (point geom-point)) (distance-between point line)) (defmethod distance-between ((point geom-point) (line geom-line)) (flet ((betw-0-and-1 (number) (and (not (minusp number)) (<= number 1.0)))) (let* ((lp1 (p1 line)) (lp2 (p2 line)) (lx1 (x lp1)) (ly1 (y lp1)) (lx2 (x lp2)) (ly2 (y lp2)) (px (x point)) (py (y point)) (ax (- lx2 lx1)) (ay (- ly2 ly1)) (dx (- lx1 px)) (dy (- ly1 py)) (a2 (+ (* ax ax) (* ay ay))) (scalar (if (zerop a2) +big-int+ (/ (+ (* ax (- dx)) (* ay (- dy))) a2))) (x (+ dx (* scalar ax))) (y (+ dy (* scalar ay)))) (if (betw-0-and-1 scalar) (sqrt (+ (* x x) (* y y))) (min (distance-between point (p1 line)) (distance-between point (p2 line))))))) (defmethod distance-between ((line1 geom-line) (line2 geom-line)) (let* ((d1 (distance-between (p1 line1) line2)) (d2 (distance-between (p2 line1) line2)) (d3 (distance-between (p1 line2) line1)) (d4 (distance-between (p2 line2) line1))) (min (min d1 d2 d3 d4)))) (defmethod distance-between ((poly1 geom-polygon) (poly2 geom-polygon)) (let* ( (line-arr1 (line-arr poly1)) (line-arr2 (line-arr poly2)) (ind1 (high-index line-arr1)) (ind2 (high-index line-arr2))) (loop for i from 0 to ind1 minimize (loop for j from 0 to ind2 minimize (distance-between (aref line-arr1 i) (aref line-arr2 j)))))) (defmethod distance-between ((line geom-line) (poly geom-polygon)) (let ( (line-arr (line-arr poly))) (loop for i from 0 to (high-index line-arr) minimize (distance-between (aref line-arr i) line)))) (defmethod distance-between ((poly geom-polygon) (line geom-line)) (distance-between line poly)) (defmethod distance-between ((poly geom-polygon) (point geom-point)) (let ( (line-arr (line-arr poly))) (loop for i from 0 to (high-index line-arr) minimize (distance-between point (aref line-arr i))))) (defmethod distance-between ((point geom-point) (poly geom-polygon)) (distance-between poly point)) ;;; ;;; ;;; (defmethod inside-s ((point1 geom-point) (point2 geom-point)) nil) (defmethod inside-s ((point geom-point) (line geom-line)) nil) (defmethod inside-s ((line geom-line) (point geom-point)) nil) (defmethod inside-s ((line1 geom-line) (line2 geom-line)) nil) (defmethod inside-s ((polygon geom-polygon) (point geom-point)) nil) (defmethod inside-s ((polygon geom-polygon) (line geom-line)) nil) (defun aget (arr n) (aref arr (1+ (mod n (- (first (array-dimensions arr)) 2))))) (defmethod inside-s ((point geom-point) (polygon geom-polygon)) (when (closed polygon) ; geht nur für geschlossene Polygone (let* ((arr (point-arr polygon)) (highindex (first (array-dimensions arr))) (n (- highindex 2)) ; Polygon hat Start- und Endpunkt doppelt (x (x point)) (y (y point)) (count 0) (lp (make-geom-line (make-geom-point 0 0) (make-geom-point 0 0))) (i (loop for i from 0 while (= y (y (aget arr i))) ; Startindex bestimmen finally (return i))) (starti i) ; Startindex merken (lt (make-geom-line ; Teststrahl in horizontale Richtung (make-geom-point x y) (make-geom-point +big-int+ y)))) (loop until (= starti (- i n)) do ; einmal ganz rum (let ((bet-found 0) (lasti i)) (let* ((curpoint (aget arr i)) (nextpoint ; nächsten Punkt suchen, der nicht auf Teststrahl liegt (loop (incf i) (let ((nowpoint (aget arr i))) (setf (p1 lp) (aget arr (1- i))) (setf (p2 lp) nowpoint) (cond ((= y (y nowpoint)) ; Punkte zählen auf Teststrahl (when (intersects lp lt :dim nil) (incf bet-found))) (t ; Punkte gefunden, der nicht auf Teststrahl liegt (return nowpoint))))))) (cond ((= (1+ lasti) i) ; keine Punkt auf Teststrahl dazwischen (setf (p1 lp) curpoint) (setf (p2 lp) nextpoint) (when (intersects lp lt :dim nil) (incf count))) (t ; viele Punkte auf dem Teststrahl lagen dazwischen ! (when (and (not (zerop bet-found)) (or (< (y curpoint) y (y nextpoint)) (> (y curpoint) y (y nextpoint)))) (incf count))))))) (oddp count)))) (defmethod inside-s ((poly1 geom-polygon) (poly2 geom-polygon)) (when (closed poly2) (let* ((arr (point-arr poly1)) (ok (dotimes (i (- (first (array-dimensions arr)) 2)) (when (not (inside-s (aref arr (1+ i)) poly2)) (return t))))) (not ok)))) (defmethod inside-s ((line geom-line) (poly geom-polygon)) (and (not (intersects-s line poly :dim nil)) (inside-s (p1 line) poly) (inside-s (p2 line) poly))) ;;; ;;; ;;; (defmethod inside ((object1 geom-thing) (object2 geom-thing)) "Fuer Aussen-Benutzung" (and (not (intersects-s object1 object2 :dim nil)) (inside-s object1 object2))) ;;; ;;; ;;; (defmethod intersects-s ((point1 geom-point) (point2 geom-point) &key &allow-other-keys) (values nil nil)) (defmethod intersects-s ((point geom-point) (line geom-line) &key (dim nil)) (if (or (zerop (ccw (p1 line) (p2 line) point)) (zerop (ccw (p2 line) (p1 line) point))) (if dim (values t 0) t) (if dim (values nil nil) nil))) (defmethod intersects-s ((line geom-line) (point geom-point) &key (dim nil)) (intersects-s point line :dim dim)) (defmethod intersects-s ((l1 geom-line) (l2 geom-line) &key (dim nil) (top-level-use t)) "Quelle: Sedgewick" (let ((l1p1 (p1 l1)) (l2p1 (p1 l2)) (l1p2 (p2 l1)) (l2p2 (p2 l2))) (let ((a1 (* (ccw l1p1 l1p2 l2p1) (ccw l1p1 l1p2 l2p2))) (a2 (* (ccw l2p1 l2p2 l1p1) (ccw l2p1 l2p2 l1p2)))) (if (and (<= a1 0) (<= a2 0)) (if dim (if (parallelp l1 l2) (let ((l1p1-on-l2 (intersects l1p1 l2 :dim nil)) (l1p2-on-l2 (intersects l1p2 l2 :dim nil)) (l2p1-on-l1 (intersects l2p1 l1 :dim nil)) (l2p2-on-l1 (intersects l2p2 l1 :dim nil))) (if (or (and l1p1-on-l2 l1p2-on-l2) (and l2p1-on-l1 l2p2-on-l1) (not (or (and (same-point l1p1 l2p1) l1p1-on-l2 l2p1-on-l1) (and (same-point l1p1 l2p2) l1p1-on-l2 l2p2-on-l1) (and (same-point l1p2 l2p1) l1p2-on-l2 l2p1-on-l1) (and (same-point l1p2 l2p2) l1p2-on-l2 l2p2-on-l1)))) (values t (if top-level-use 1 'par)) (values t 0))) (values t 0)) t) (if dim (values nil nil) nil))))) (defun same-point (p1 p2) (and (= (x p1) (x p2)) (= (y p1) (y p2)))) (defun point< (p1 p2) (and (< (x p1) (x p2)) (< (y p1) (y p2)))) (defun point> (p1 p2) (and (> (x p1) (x p2)) (> (y p1) (y p2)))) (defmethod intersects-s ((line geom-line) (poly geom-polygon) &key (dim nil) (recursive-descent t) (top-level-use t)) (let* ((larr (line-arr poly)) (par)) (if dim (let ((max-dim (loop for i from 0 to (1- (first (array-dimensions larr))) maximize (multiple-value-bind (intersectsp dim) (intersects-s (aref larr i) line :dim t :top-level-use nil) (if intersectsp (if (numberp dim) dim (progn (setf par t) 1)) -1))))) (if (minusp max-dim) (values nil nil) (if (not par) (progn (values t (max max-dim (if (and (closed poly) recursive-descent) (calculate-dim-of-intersect line poly) -1)))) (values t (if top-level-use 1 'par))))) (loop for i from 0 to (1- (first (array-dimensions larr))) thereis (intersects-s (aref larr i) line :dim nil))))) (defmethod intersects-s ((poly geom-polygon) (line geom-line) &key (dim nil) (recursive-descent t) (top-level-use t)) (intersects-s line poly :dim dim :recursive-descent recursive-descent :top-level-use top-level-use)) (defmethod calculate-dim-of-intersect ((line geom-line) (poly geom-polygon)) (if (one-part-is-inside line poly) 1 0)) (defconstant +epsilon+ 3) (defmethod one-part-is-inside ((line geom-line) (poly geom-polygon)) (let* ((p1 (p1 line)) (p2 (p2 line)) (d (distance-between p1 p2))) (cond ((and (inside-s p1 poly) (inside-s p2 poly)) t) ((< d +epsilon+) nil) (t (let* ((middle-point (make-geom-point (/ (+ (x p1) (x p2)) 2) (/ (+ (y p1) (y p2)) 2))) (l1 (make-geom-line p1 middle-point)) (l2 (make-geom-line middle-point p2))) (or (one-part-is-inside l1 poly) (one-part-is-inside l2 poly))))))) (defmethod intersects-s ((poly1 geom-polygon) (poly2 geom-polygon) &key (dim nil)) (let* ((arr (line-arr poly1)) (parr (point-arr poly1)) (counter 0) (col) (parlist)) (if dim (let ((max-dim (loop for i from 0 to (1- (first (array-dimensions arr))) maximize (multiple-value-bind (intersectsp dim) (intersects-s (aref arr i) poly2 :dim t :top-level-use nil :recursive-descent t) (cond ( (eq dim 'par) (push i parlist) 1) ( intersectsp collect i (push i col) (incf counter) dim) (t -1)))))) (if (minusp max-dim) (values nil nil) (values t (if (and (> counter 0) (closed poly1) (loop for line in col thereis (let ((dim (calculate-dim-of-intersect (aref arr line) poly2))) (= dim 1)))) 2 max-dim)))) (loop for i from 0 to (1- (first (array-dimensions arr))) thereis (intersects-s (aref arr i) poly2 :dim nil))))) (defmethod intersects-s ((point geom-point) (poly geom-polygon) &key (dim nil)) (let* ((arr (line-arr poly)) (ok (dotimes (i (first (array-dimensions arr))) (if (intersects-s point (aref arr i) :dim nil) (return t))))) (if ok (if dim (values t 0) t) (if dim (values nil nil) nil)))) (defmethod intersects-s ((poly geom-polygon) (point geom-point) &key (dim nil)) (intersects-s point poly :dim dim)) ;;; ;;; (defmethod intersects ((thing1 geom-thing) (thing2 geom-thing) &key (dim nil)) (if dim (multiple-value-bind (ip1 dim1) (intersects-s thing1 thing2 :dim t) (if (not ip1) (values nil nil) (if (< dim1 2) (multiple-value-bind (ip2 dim2) (intersects-s thing2 thing1 :dim t) (values t (max dim1 dim2))) (values t 2)))) (intersects-s thing1 thing2 :dim nil))) ;;; ;;; ;;; (defmethod touching-tres ((thing1 geom-thing) (thing2 geom-thing) tres) "Arbeitet mit dem minimalen Abstand. Fuer Aussen-Benutzung" (and (not (intersects-s thing1 thing2 :dim nil)) (let ((d (distance-between thing1 thing2))) (if (<= d tres) d)))) ;;; ;;; ;;; (defmethod covers-tres ((thing1 geom-thing) (thing2 geom-thing) tres) "Fuer Aussen-Benutzung" (and (inside-s thing2 thing1) (touching-tres thing2 thing1 tres))) ;;; ;;; ;;; (defun distance-and-orientation (x1 y1 x2 y2) (let* ( (dx (- x2 x1)) (dy (- y2 y1)) (d (sqrt (+ (* dx dx) (* dy dy)))) (phi (if (zerop dx) (if (minusp dy) (- (/ pi 2)) (/ pi 2)) (atan (/ dy dx)))) (phi2 (if (minusp dx) (+ phi pi) phi))) (values d phi2))) ;;; ;;; Master-Function ;;; (defun inverse (relation) (case relation (is-inside 'contains) (is-covered-by 'covers) (contains 'is-inside) (covers 'is-covered-by) (t relation))) (defun clear-hashtable () (clrhash *hash-table*)) (defun delete-object-from-cache (thing object-liste) (dolist (elem object-liste) (unless (eq elem thing) (let* ((goedel1 (get-goedel thing elem)) (goedel2 (get-goedel elem thing))) (remhash goedel1 *hash-table*) (remhash goedel2 *hash-table*))))) #| (defun get-goedel (x y) (unless (tickval x) (setf (tickval x) (incf *tick-counter*))) (unless (tickval y) (setf (tickval y) (incf *tick-counter*))) (let ((r (* (expt 2 (tickval x)) (expt 3 (tickval y))))) r)) |# (defconstant +hash-table-delta+ 3000) (defun get-goedel (x y) (unless (tickval x) (setf (tickval x) (incf *tick-counter*))) (unless (tickval y) (setf (tickval y) (incf *tick-counter*))) (+ (* +hash-table-delta+ (tickval x)) (tickval y))) ;;; ;;; ;;; (defun relate-poly-to-poly-unary-tres (thing1 thing2 tres &key (dim nil)) (or (gethash (get-goedel thing1 thing2) *hash-table*) (inverse (gethash (get-goedel thing2 thing1) *hash-table*)) (let ((relation (if (intersects thing1 thing2 :dim nil) (if dim (multiple-value-bind (intersectsp dim) (intersects thing1 thing2 :dim t) (case dim (0 'intersects-0) (1 'intersects-1) (2 'intersects-2))) 'intersects) (if (inside-s thing1 thing2) (let ((d (distance-between thing1 thing2))) (if (<= d tres) 'is-covered-by 'is-inside)) (if (inside-s thing2 thing1) (let ((d (distance-between thing2 thing1))) (if (<= d tres) 'covers 'contains)) (let ((d (distance-between thing1 thing2))) (if (<= d tres) 'touches 'is-disjoint-with))))))) (setf (gethash (get-goedel thing1 thing2) *hash-table*) relation) relation)))
21,847
Common Lisp
.lisp
603
24.238806
141
0.475093
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
8f84fed1e2f61aa956f399771b562a35e37f67ca118e97c02a02cd25d868a8c5
11,203
[ -1 ]
11,204
newgeo13.lisp
lambdamikel_GenEd/src/geometry/newgeo13.lisp
;;; -*- Mode: LISP; Syntax: Ansi-Common-Lisp; Package: GEOMETRY -*- (in-package geometry) (defconstant +big-int+ 10000) (defparameter *tick-counter* 1) (defparameter *hash-table* (make-hash-table :size 200 :rehash-size 50)) ;;; ;;; Topological Relations for Polygons. ;;; ;;; ;;; Konstruktoren ;;; (defclass geom-thing () ((tickval :initform nil :accessor tickval :initarg :tickval))) (defclass geom-line (geom-thing) ((p1 :initform nil :initarg :p1 :accessor p1) (p2 :initform nil :initarg :p2 :accessor p2))) (defclass geom-point (geom-thing) ((x :initform 0 :initarg :x :accessor x) (y :initform 0 :initarg :y :accessor y))) (defclass geom-polygon (geom-thing) ((point-arr :initform nil :initarg :point-arr :accessor point-arr) ; range: 1..n (line-arr :initform nil :initarg :line-arr :accessor line-arr) ; range: 0..n/n-1 (closed :initform t :initarg :closed :accessor closed))) (defmethod get-points ((object geom-polygon)) (mapcan #'(lambda (point) (list (x point) (y point))) (coerce (point-arr object) 'list))) ;;; ;;; Basis-Funktionen ;;; (defmethod ccw ((p0 geom-point) (p1 geom-point) (p2 geom-point)) "Quelle: Sedgewick" (let* ((x0 (x p0)) (x1 (x p1)) (x2 (x p2)) (y0 (y p0)) (y1 (y p1)) (y2 (y p2)) (dx1 (- x1 x0)) (dy1 (- y1 y0)) (dx2 (- x2 x0)) (dy2 (- y2 y0))) (cond ((> (* dx1 dy2) (* dy1 dx2)) 1) ((< (* dx1 dy2) (* dy1 dx2)) -1) ((or (< (* dx1 dx2) 0) (< (* dy1 dy2) 0)) -1) ((< (+ (* dx1 dx1) (* dy1 dy1)) (+ (* dx2 dx2) (* dy2 dy2))) 1) (t 0)))) ;;; ;;; Hilfsfunktionen ;;; (defun make-geom-polygon (point-list &key (is-closed t) (tickval nil)) ; Fehler: wenn &key (closed t) ! (let* ((poly (make-instance 'geom-polygon :closed is-closed :tickval tickval))) (setf (point-arr poly) (make-geom-point-arr point-list) (line-arr poly) (make-geom-line-arr (point-arr poly) :closed is-closed)) poly)) (defun make-geom-point (x y &key (tickval nil)) (make-instance 'geom-point :x x :y y :tickval tickval)) (defun make-geom-point-arr (liste) (let ((arr (make-array (+ 2 (length liste)))) (i 1)) (dolist (elem liste) (setf (aref arr i) (make-geom-point (first elem) (second elem))) (incf i)) (setf (aref arr 0) (aref arr (1- i))) (setf (aref arr i) (aref arr 1)) arr)) (defun make-geom-line (p1 p2 &key (tickval nil)) (make-instance 'geom-line :p1 p1 :p2 p2 :tickval tickval)) (defun make-geom-line-arr (point-arr &key (closed t)) (let* ((dim (if closed (- (first (array-dimensions point-arr)) 2) (- (first (array-dimensions point-arr)) 3))) (arr (make-array (list dim)))) (dotimes (i dim) (setf (aref arr i) (make-geom-line (aref point-arr (+ i 1)) (aref point-arr (+ i 2))))) arr)) ;;;; ;;;; ;;;; (defun high-index (arr) (1- (first (array-dimensions arr)))) (defun calculate-bounding-box (arr) (let* ((minx (x (aref arr 0))) (miny (y (aref arr 0))) (maxx minx) (maxy miny)) (dotimes (i (1- (first (array-dimensions arr)))) (let* ((point (aref arr i)) (y (y point)) (x (x point))) (cond ((< x minx) (setf minx x)) ((> x maxx) (setf maxx x)) ((< y miny) (setf miny y)) ((> y maxy) (setf maxy y))))) (values minx miny maxx maxy))) (defun calculate-center (arr) (multiple-value-bind (xf yf xt yt) (calculate-bounding-box arr) (values (/ (+ xf xt) 2) (/ (+ yf yt) 2)))) ;;; ;;; Abstandsfunktionen ;;; (defmethod parallelp ((thing1 geom-thing) (thing2 geom-thing)) nil) (defmethod parallelp ((line1 geom-line) (line2 geom-line)) (let ((dx1 (- (x (p1 line1)) (x (p2 line1)))) (dx2 (- (x (p1 line2)) (x (p2 line2)))) (dy1 (- (y (p1 line1)) (y (p2 line1)))) (dy2 (- (y (p1 line2)) (y (p2 line2))))) (or (zerop (- (* dx1 dy2) (* dx2 dy1))) (zerop (- (* dx2 dy1) (* dx1 dy2)))))) ;;; ;;; ;;; (defmethod distance-between ((point1 geom-point) (point2 geom-point)) (let ((dx (- (x point1) (x point2))) (dy (- (y point1) (y point2)))) (sqrt (+ (* dx dx) (* dy dy))))) (defmethod distance-between ((line geom-line) (point geom-point)) (distance-between point line)) (defmethod distance-between ((point geom-point) (line geom-line)) (flet ((betw-0-and-1 (number) (and (not (minusp number)) (<= number 1.0)))) (let* ((lp1 (p1 line)) (lp2 (p2 line)) (lx1 (x lp1)) (ly1 (y lp1)) (lx2 (x lp2)) (ly2 (y lp2)) (px (x point)) (py (y point)) (ax (- lx2 lx1)) (ay (- ly2 ly1)) (dx (- lx1 px)) (dy (- ly1 py)) (a2 (+ (* ax ax) (* ay ay))) (scalar (if (zerop a2) +big-int+ (/ (+ (* ax (- dx)) (* ay (- dy))) a2))) (x (+ dx (* scalar ax))) (y (+ dy (* scalar ay)))) (if (betw-0-and-1 scalar) (sqrt (+ (* x x) (* y y))) (min (distance-between point (p1 line)) (distance-between point (p2 line))))))) (defmethod distance-between ((line1 geom-line) (line2 geom-line)) (let* ((d1 (distance-between (p1 line1) line2)) (d2 (distance-between (p2 line1) line2)) (d3 (distance-between (p1 line2) line1)) (d4 (distance-between (p2 line2) line1))) (min (min d1 d2 d3 d4)))) (defmethod distance-between ((poly1 geom-polygon) (poly2 geom-polygon)) (let* ( (line-arr1 (line-arr poly1)) (line-arr2 (line-arr poly2)) (ind1 (high-index line-arr1)) (ind2 (high-index line-arr2))) (loop for i from 0 to ind1 minimize (loop for j from 0 to ind2 minimize (distance-between (aref line-arr1 i) (aref line-arr2 j)))))) (defmethod distance-between ((line geom-line) (poly geom-polygon)) (let ( (line-arr (line-arr poly))) (loop for i from 0 to (high-index line-arr) minimize (distance-between (aref line-arr i) line)))) (defmethod distance-between ((poly geom-polygon) (line geom-line)) (distance-between line poly)) (defmethod distance-between ((poly geom-polygon) (point geom-point)) (let ((line-arr (line-arr poly))) (loop for i from 0 to (high-index line-arr) minimize (distance-between point (aref line-arr i))))) (defmethod distance-between ((point geom-point) (poly geom-polygon)) (distance-between poly point)) ;;; ;;; ;;; (defmethod inside-s ((point1 geom-point) (point2 geom-point)) nil) (defmethod inside-s ((point geom-point) (line geom-line)) nil) (defmethod inside-s ((line geom-line) (point geom-point)) nil) (defmethod inside-s ((line1 geom-line) (line2 geom-line)) nil) (defmethod inside-s ((polygon geom-polygon) (point geom-point)) nil) (defmethod inside-s ((polygon geom-polygon) (line geom-line)) nil) (defun aget (arr n) (aref arr (1+ (mod n (- (first (array-dimensions arr)) 2))))) (defmethod inside-s ((point geom-point) (polygon geom-polygon)) (when (closed polygon) ; geht nur für geschlossene Polygone (let* ((arr (point-arr polygon)) (highindex (first (array-dimensions arr))) (n (- highindex 2)) ; Polygon hat Start- und Endpunkt doppelt (x (x point)) (y (y point)) (count 0) (lp (make-geom-line (make-geom-point 0 0) (make-geom-point 0 0))) (i (loop for i from 0 while (= y (y (aget arr i))) ; Startindex bestimmen finally (return i))) (starti i) ; Startindex merken (lt (make-geom-line ; Teststrahl in horizontale Richtung (make-geom-point x y) (make-geom-point +big-int+ y)))) (loop until (= starti (- i n)) do ; einmal ganz rum (let ((bet-found 0) (lasti i)) (let* ((curpoint (aget arr i)) (nextpoint ; nächsten Punkt suchen, der nicht auf Teststrahl liegt (loop (incf i) (let ((nowpoint (aget arr i))) (setf (p1 lp) (aget arr (1- i))) (setf (p2 lp) nowpoint) (cond ((= y (y nowpoint)) ; Punkte zählen auf Teststrahl (when (intersects lp lt :dim nil) (incf bet-found))) (t ; Punkte gefunden, der nicht auf Teststrahl liegt (return nowpoint))))))) (cond ((= (1+ lasti) i) ; keine Punkt auf Teststrahl dazwischen (setf (p1 lp) curpoint) (setf (p2 lp) nextpoint) (when (intersects lp lt :dim nil) (incf count))) (t ; viele Punkte auf dem Teststrahl lagen dazwischen ! (when (and (not (zerop bet-found)) (or (< (y curpoint) y (y nextpoint)) (> (y curpoint) y (y nextpoint)))) (incf count))))))) (oddp count)))) (defmethod inside-s ((poly1 geom-polygon) (poly2 geom-polygon)) (when (closed poly2) (let* ((arr (point-arr poly1)) (ok (dotimes (i (- (first (array-dimensions arr)) 2)) (when (not (inside-s (aref arr (1+ i)) poly2)) (return t))))) (not ok)))) (defmethod inside-s ((line geom-line) (poly geom-polygon)) (and (not (intersects-s line poly :dim nil)) (inside-s (p1 line) poly) (inside-s (p2 line) poly))) ;;; ;;; ;;; (defmethod inside ((object1 geom-thing) (object2 geom-thing)) "Fuer Aussen-Benutzung" (and (not (intersects-s object1 object2 :dim nil)) (inside-s object1 object2))) ;;; ;;; ;;; (defmethod intersects-s ((point1 geom-point) (point2 geom-point) &key &allow-other-keys) (values nil nil)) (defmethod intersects-s ((point geom-point) (line geom-line) &key (dim nil)) (if (or (zerop (ccw (p1 line) (p2 line) point)) (zerop (ccw (p2 line) (p1 line) point))) (if dim (values t 0) t) (if dim (values nil nil) nil))) (defmethod intersects-s ((line geom-line) (point geom-point) &key (dim nil)) (intersects-s point line :dim dim)) (defmethod intersects-s ((l1 geom-line) (l2 geom-line) &key (dim nil) (top-level-use t)) "Quelle: Sedgewick" (let ((l1p1 (p1 l1)) (l2p1 (p1 l2)) (l1p2 (p2 l1)) (l2p2 (p2 l2))) (let ((a1 (* (ccw l1p1 l1p2 l2p1) (ccw l1p1 l1p2 l2p2))) (a2 (* (ccw l2p1 l2p2 l1p1) (ccw l2p1 l2p2 l1p2)))) (if (and (<= a1 0) (<= a2 0)) (if dim (if (parallelp l1 l2) (let ((l1p1-on-l2 (intersects l1p1 l2 :dim nil)) (l1p2-on-l2 (intersects l1p2 l2 :dim nil)) (l2p1-on-l1 (intersects l2p1 l1 :dim nil)) (l2p2-on-l1 (intersects l2p2 l1 :dim nil))) (if (or (and l1p1-on-l2 l1p2-on-l2) (and l2p1-on-l1 l2p2-on-l1) (not (or (and (same-point l1p1 l2p1) l1p1-on-l2 l2p1-on-l1) (and (same-point l1p1 l2p2) l1p1-on-l2 l2p2-on-l1) (and (same-point l1p2 l2p1) l1p2-on-l2 l2p1-on-l1) (and (same-point l1p2 l2p2) l1p2-on-l2 l2p2-on-l1)))) (values t (if top-level-use 1 'par)) (values t 0))) (values t 0)) t) (if dim (values nil nil) nil))))) (defun same-point (p1 p2) (and (= (x p1) (x p2)) (= (y p1) (y p2)))) (defun point< (p1 p2) (and (< (x p1) (x p2)) (< (y p1) (y p2)))) (defun point> (p1 p2) (and (> (x p1) (x p2)) (> (y p1) (y p2)))) (defmethod intersects-s ((line geom-line) (poly geom-polygon) &key (dim nil) (recursive-descent t) (top-level-use t)) (let* ((larr (line-arr poly)) (par)) (if dim (let ((max-dim (loop for i from 0 to (1- (first (array-dimensions larr))) maximize (multiple-value-bind (intersectsp dim) (intersects-s (aref larr i) line :dim t :top-level-use nil) (if intersectsp (if (numberp dim) dim (progn (setf par t) 1)) -1))))) (if (minusp max-dim) (values nil nil) (if (not par) (progn (values t (max max-dim (if (and (closed poly) recursive-descent) (calculate-dim-of-intersect line poly) -1)))) (values t (if top-level-use 1 'par))))) (loop for i from 0 to (1- (first (array-dimensions larr))) thereis (intersects-s (aref larr i) line :dim nil))))) (defmethod intersects-s ((poly geom-polygon) (line geom-line) &key (dim nil) (recursive-descent t) (top-level-use t)) (intersects-s line poly :dim dim :recursive-descent recursive-descent :top-level-use top-level-use)) (defmethod calculate-dim-of-intersect ((line geom-line) (poly geom-polygon)) (if (one-part-is-inside line poly) 1 0)) (defconstant +epsilon+ 3) (defmethod one-part-is-inside ((line geom-line) (poly geom-polygon)) (let* ((p1 (p1 line)) (p2 (p2 line)) (d (distance-between p1 p2))) (cond ((and (inside-s p1 poly) (inside-s p2 poly)) t) ((< d +epsilon+) nil) (t (let* ((middle-point (make-geom-point (/ (+ (x p1) (x p2)) 2) (/ (+ (y p1) (y p2)) 2))) (l1 (make-geom-line p1 middle-point)) (l2 (make-geom-line middle-point p2))) (or (one-part-is-inside l1 poly) (one-part-is-inside l2 poly))))))) (defmethod intersects-s ((poly1 geom-polygon) (poly2 geom-polygon) &key (dim nil)) (let* ((arr (line-arr poly1)) (counter 0) (col) (parlist)) (if dim (let ((max-dim (loop for i from 0 to (1- (first (array-dimensions arr))) maximize (multiple-value-bind (intersectsp dim) (intersects-s (aref arr i) poly2 :dim t :top-level-use nil :recursive-descent t) (cond ( (eq dim 'par) (push i parlist) 1) ( intersectsp (push i col) (incf counter) dim) (t -1)))))) (if (minusp max-dim) (values nil nil) (values t (if (and (> counter 0) (closed poly1) (loop for line in col thereis (let ((dim (calculate-dim-of-intersect (aref arr line) poly2))) (= dim 1)))) 2 max-dim)))) (loop for i from 0 to (1- (first (array-dimensions arr))) thereis (intersects-s (aref arr i) poly2 :dim nil))))) (defmethod intersects-s ((point geom-point) (poly geom-polygon) &key (dim nil)) (let* ((arr (line-arr poly)) (ok (dotimes (i (first (array-dimensions arr))) (if (intersects-s point (aref arr i) :dim nil) (return t))))) (if ok (if dim (values t 0) t) (if dim (values nil nil) nil)))) (defmethod intersects-s ((poly geom-polygon) (point geom-point) &key (dim nil)) (intersects-s point poly :dim dim)) ;;; ;;; (defmethod intersects ((thing1 geom-thing) (thing2 geom-thing) &key (dim nil)) (if dim (multiple-value-bind (ip1 dim1) (intersects-s thing1 thing2 :dim t) (if (not ip1) (values nil nil) (if (< dim1 2) (multiple-value-bind (ip2 dim2) (intersects-s thing2 thing1 :dim t) (declare (ignore ip2)) (values t (max dim1 dim2))) (values t 2)))) (intersects-s thing1 thing2 :dim nil))) ;;; ;;; ;;; (defmethod touching-tres ((thing1 geom-thing) (thing2 geom-thing) tres) "Arbeitet mit dem minimalen Abstand. Fuer Aussen-Benutzung" (and (not (intersects-s thing1 thing2 :dim nil)) (let ((d (distance-between thing1 thing2))) (if (<= d tres) d)))) ;;; ;;; ;;; (defmethod covers-tres ((thing1 geom-thing) (thing2 geom-thing) tres) "Fuer Aussen-Benutzung" (and (inside-s thing2 thing1) (touching-tres thing2 thing1 tres))) ;;; ;;; ;;; (defun distance-and-orientation (x1 y1 x2 y2) (let* ( (dx (- x2 x1)) (dy (- y2 y1)) (d (sqrt (+ (* dx dx) (* dy dy)))) (phi (if (zerop dx) (if (minusp dy) (- (/ pi 2)) (/ pi 2)) (atan (/ dy dx)))) (phi2 (if (minusp dx) (+ phi pi) phi))) (values d phi2))) ;;; ;;; Master-Function ;;; (defun inverse (relation) (case relation (is-inside 'contains) (is-covered-by 'covers) (contains 'is-inside) (covers 'is-covered-by) (t relation))) (defun clear-hashtable () (clrhash *hash-table*)) (defun delete-object-from-cache (thing object-liste) (dolist (elem object-liste) (unless (eq elem thing) (let* ((goedel1 (get-goedel thing elem)) (goedel2 (get-goedel elem thing))) (remhash goedel1 *hash-table*) (remhash goedel2 *hash-table*))))) #| (defun get-goedel (x y) (unless (tickval x) (setf (tickval x) (incf *tick-counter*))) (unless (tickval y) (setf (tickval y) (incf *tick-counter*))) (let ((r (* (expt 2 (tickval x)) (expt 3 (tickval y))))) r)) |# (defconstant +hash-table-delta+ 3000) (defun get-goedel (x y) (unless (tickval x) (setf (tickval x) (incf *tick-counter*))) (unless (tickval y) (setf (tickval y) (incf *tick-counter*))) (+ (* +hash-table-delta+ (tickval x)) (tickval y))) ;;; ;;; ;;; (defun relate-poly-to-poly-unary-tres (thing1 thing2 tres &key (dim nil)) (or (gethash (get-goedel thing1 thing2) *hash-table*) (inverse (gethash (get-goedel thing2 thing1) *hash-table*)) (let ((relation (if (intersects thing1 thing2 :dim nil) (if dim (multiple-value-bind (intersectsp dim) (intersects thing1 thing2 :dim t) (declare (ignore intersectsp)) (case dim (0 'intersects-0) (1 'intersects-1) (2 'intersects-2))) 'intersects) (if (inside-s thing1 thing2) (let ((d (distance-between thing1 thing2))) (if (<= d tres) 'is-covered-by 'is-inside)) (if (inside-s thing2 thing1) (let ((d (distance-between thing2 thing1))) (if (<= d tres) 'covers 'contains)) (let ((d (distance-between thing1 thing2))) (if (<= d tres) 'touches 'is-disjoint-with))))))) (setf (gethash (get-goedel thing1 thing2) *hash-table*) relation) relation)))
18,851
Common Lisp
.lisp
604
24.387417
99
0.558605
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e5ab151e7ae020d1b430f377547b20bb9577dd344ef6c45b5786ebf931bd5990
11,204
[ -1 ]
11,205
newgeo3.lisp
lambdamikel_GenEd/src/geometry/newgeo3.lisp
;;; -*- Mode: LISP; Syntax: Ansi-Common-Lisp; Package: GEOMETRY -*- (in-package geometry) (defconstant +big-int+ 10000) (defparameter *tick-counter* 1) (defparameter *hash-table* (make-hash-table)) ;;; ;;; Topological Relations for Polygons. ;;; ;;; ;;; Konstruktoren ;;; (defclass geom-thing () ((tickval :initform 0 :accessor tickval :initarg :tickval))) (defclass geom-line (geom-thing) ((p1 :initform nil :initarg :p1 :accessor p1) (p2 :initform nil :initarg :p2 :accessor p2))) (defclass geom-point (geom-thing) ((x :initform 0 :initarg :x :accessor x) (y :initform 0 :initarg :y :accessor y))) (defclass geom-polygon (geom-thing) ((point-arr :initform nil :initarg :point-arr :accessor point-arr) ; range: 1..n (line-arr :initform nil :initarg :line-arr :accessor line-arr) ; range: 0..n/n-1 (closed :initform t :initarg :closed :accessor closed))) ;;; ;;; Basis-Funktionen ;;; (defmethod ccw ((p0 geom-point) (p1 geom-point) (p2 geom-point)) "Quelle: Sedgewick" (let* ((x0 (x p0)) (x1 (x p1)) (x2 (x p2)) (y0 (y p0)) (y1 (y p1)) (y2 (y p2)) (dx1 (- x1 x0)) (dy1 (- y1 y0)) (dx2 (- x2 x0)) (dy2 (- y2 y0))) (cond ((> (* dx1 dy2) (* dy1 dx2)) 1) ((< (* dx1 dy2) (* dy1 dx2)) -1) ((or (< (* dx1 dx2) 0) (< (* dy1 dy2) 0)) -1) ((< (+ (* dx1 dx1) (* dy1 dy1)) (+ (* dx2 dx2) (* dy2 dy2))) 1) (t 0)))) (defmethod intersects ((l1 geom-line) (l2 geom-line)) "Quelle: Sedgewick" (let ((l1p1 (p1 l1)) (l2p1 (p1 l2)) (l1p2 (p2 l1)) (l2p2 (p2 l2))) (and (<= (* (ccw l1p1 l1p2 l2p1) (ccw l1p1 l1p2 l2p2)) 0) (<= (* (ccw l2p1 l2p2 l1p1) (ccw l2p1 l2p2 l1p2)) 0)))) ;;; ;;; Hilfsfunktionen ;;; (defun make-geom-polygon (point-list &key (is-closed t)) ; Fehler: wenn &key (closed t) ! (let* ((poly (make-instance 'geom-polygon :closed is-closed :tickval (incf *tick-counter*)))) (setf (point-arr poly) (make-geom-point-arr point-list) (line-arr poly) (make-geom-line-arr (point-arr poly) :closed is-closed)) poly)) (defun make-geom-point (x y) (make-instance 'geom-point :tickval (incf *tick-counter*) :x x :y y)) (defun make-geom-point-arr (liste) (let ((arr (make-array (+ 2 (length liste)))) (i 1)) (dolist (elem liste) (setf (aref arr i) (make-geom-point (first elem) (second elem))) (incf i)) (setf (aref arr 0) (aref arr (1- i))) (setf (aref arr i) (aref arr 1)) arr)) (defun make-geom-line (p1 p2) (make-instance 'geom-line :tickval (incf *tick-counter*) :p1 p1 :p2 p2)) (defun make-geom-line-arr (point-arr &key (closed t)) (let* ((dim (if closed (- (first (array-dimensions point-arr)) 2) (- (first (array-dimensions point-arr)) 3))) (arr (make-array (list dim)))) (dotimes (i dim) (setf (aref arr i) (make-geom-line (aref point-arr (+ i 1)) (aref point-arr (+ i 2))))) arr)) ;;;; ;;;; ;;;; (defun high-index (arr) (1- (first (array-dimensions arr)))) (defun calculate-bounding-box (arr) (let* ((minx (x (aref arr 0))) (miny (y (aref arr 0))) (maxx minx) (maxy miny)) (dotimes (i (1- (first (array-dimensions arr)))) (let* ((point (aref arr i)) (y (y point)) (x (x point))) (cond ((< x minx) (setf minx x)) ((> x maxx) (setf maxx x)) ((< y miny) (setf miny y)) ((> y maxy) (setf maxy y))))) (values minx miny maxx maxy))) (defun calculate-center (arr) (multiple-value-bind (xf yf xt yt) (calculate-bounding-box arr) (values (/ (+ xf xt) 2) (/ (+ yf yt) 2)))) ;;; ;;; Abstandsfunktionen ;;; (defmethod distance-between ((point1 geom-point) (point2 geom-point)) (let ((dx (- (x point1) (x point2))) (dy (- (y point1) (y point2)))) (sqrt (+ (* dx dx) (* dy dy))))) (defmethod distance-between ((line geom-line) (point geom-point)) (distance-between point line)) #| (defmethod distance-between ((point geom-point) (line geom-line)) (let* ((lp1 (p1 line)) (lp2 (p2 line)) (lx1 (x lp1)) (ly1 (y lp1)) (lx2 (x lp2)) (ly2 (y lp2)) (px (x point)) (py (y point)) (ax (- lx2 lx1)) (ay (- ly2 ly1)) (dx (- lx1 px)) (dy (- ly1 py)) (a2 (+ (* ax ax) (* ay ay))) (scalar (/ (+ (* ax (- dx)) (* ay (- dy))) a2)) (x (+ dx (* scalar ax))) (y (+ dy (* scalar ay)))) (values (sqrt (+ (* x x) (* y y))) scalar x y))) |# (defmethod distance-between ((point geom-point) (line geom-line)) (flet ((betw-0-and-1 (number) (and (not (minusp number)) (<= number 1.0)))) (let* ((lp1 (p1 line)) (lp2 (p2 line)) (lx1 (x lp1)) (ly1 (y lp1)) (lx2 (x lp2)) (ly2 (y lp2)) (px (x point)) (py (y point)) (ax (- lx2 lx1)) (ay (- ly2 ly1)) (dx (- lx1 px)) (dy (- ly1 py)) (a2 (+ (* ax ax) (* ay ay))) (scalar (/ (+ (* ax (- dx)) (* ay (- dy))) a2)) (x (+ dx (* scalar ax))) (y (+ dy (* scalar ay)))) (if (betw-0-and-1 scalar) (sqrt (+ (* x x) (* y y))) (min (distance-between point (p1 line)) (distance-between point (p2 line))))))) (defmethod distance-between ((line1 geom-line) (line2 geom-line)) (let* ((d1 (distance-between (p1 line1) line2)) (d2 (distance-between (p2 line1) line2)) (d3 (distance-between (p1 line2) line1)) (d4 (distance-between (p2 line2) line1))) (min (min d1 d2 d3 d4)))) (defmethod distance-between ((poly1 geom-polygon) (poly2 geom-polygon)) (let* ( (line-arr1 (line-arr poly1)) (line-arr2 (line-arr poly2)) (ind1 (high-index line-arr1)) (ind2 (high-index line-arr2))) (loop for i from 0 to ind1 minimize (loop for j from 0 to ind2 minimize (distance-between (aref line-arr1 i) (aref line-arr2 j)))))) (defmethod distance-between ((line geom-line) (poly geom-polygon)) (let ( (line-arr (line-arr poly))) (loop for i from 0 to (high-index line-arr) minimize (distance-between (aref line-arr i) line)))) (defmethod distance-between ((poly geom-polygon) (line geom-line)) (distance-between line poly)) (defmethod distance-between ((poly geom-polygon) (point geom-point)) (let ( (line-arr (line-arr poly))) (loop for i from 0 to (high-index line-arr) minimize (distance-between point (aref line-arr i))))) (defmethod distance-between ((point geom-point) (poly geom-polygon)) (distance-between poly point)) ;;; ;;; Relationen! ;;; (defmethod inside ((point1 geom-point) (point2 geom-point)) nil) (defmethod inside ((point geom-point) (line geom-line)) nil) (defmethod inside ((line geom-line) (point geom-point)) nil) (defmethod inside ((line1 geom-line) (line2 geom-line)) nil) (defmethod inside ((polygon geom-polygon) (point geom-point)) nil) (defmethod inside ((polygon geom-polygon) (line geom-line)) nil) (defmethod inside ((point geom-point) (polygon geom-polygon)) "Nicht ganz korrekt !!! Quelle: Sedgewick, modifiziert!" (when (closed polygon) (let* ((count1 0) (count2 0) (j 0) (arr (point-arr polygon)) (n (- (first (array-dimensions arr)) 2)) (x (x point)) (y (y point)) (lp (make-geom-line (make-geom-point 0 0) (make-geom-point 0 0))) (lt (make-geom-line (make-geom-point x y) (make-geom-point +big-int+ y)))) ; wegen ALIAS-Effekten! (dotimes (m n) (let ((i (1+ m))) (setf (p1 lp) (aref arr i)) (when (and (not (and (= (y (p1 lp)) (y (p1 lt))) (>= (x (p1 lp)) (x (p1 lt))))) (not (and (= (y (aref arr j)) (y (p1 lt))) (>= (x (aref arr j)) (x (p1 lt)))))) (setf (p2 lp) (aref arr j)) (setf j i) (when (intersects lp lt) (incf count1))))) (let ((lt (make-geom-line (make-geom-point x y) (make-geom-point (- +big-int+) y)))) ; wegen ALIAS-Effekten! (dotimes (m n) (let ((i (1+ m))) (setf (p1 lp) (aref arr i)) (when (and (not (and (= (y (p1 lp)) (y (p1 lt))) (<= (x (p1 lp)) (x (p1 lt))))) (not (and (= (y (aref arr j)) (y (p1 lt))) (<= (x (aref arr j)) (x (p1 lt)))))) (setf (p2 lp) (aref arr j)) (setf j i) (when (intersects lp lt) (incf count2))))) (or (not (zerop (mod count1 2))) (not (zerop (mod count2 2)))))))) (defmethod inside ((poly1 geom-polygon) (poly2 geom-polygon)) (when (closed poly2) (let* ((arr (point-arr poly1)) (ok (dotimes (i (- (first (array-dimensions arr)) 2)) (when (not (inside (aref arr (1+ i)) poly2)) (return t))))) (not ok)))) (defmethod inside ((line geom-line) (poly geom-polygon)) (and (inside (p1 line) poly) (inside (p2 line) poly) (not (intersects line poly)))) ;;; ;;; ;;; (defmethod intersects ((point1 geom-point) (point2 geom-point)) nil) (defmethod intersects ((point geom-point) (line geom-line)) nil) (defmethod intersects ((line geom-line) (point geom-point)) nil) (defmethod intersects ((line geom-line) (poly geom-polygon)) (let* ((arr (line-arr poly)) (ok (dotimes (i (first (array-dimensions arr))) (if (intersects (aref arr i) line) (return t))))) ok)) (defmethod intersects ((poly geom-polygon) (line geom-line)) (intersects line poly)) (defmethod intersects ((poly1 geom-polygon) (poly2 geom-polygon)) (let* ((arr (line-arr poly1)) (ok (dotimes (i (first (array-dimensions arr))) (if (intersects (aref arr i) poly2) (return t))))) ok)) (defmethod intersects ((point geom-point) (poly geom-polygon)) nil) (defmethod intersects ((poly geom-polygon) (point geom-point)) nil) ;;; ;;; ;;; (defmethod disjoint ((poly1 geom-polygon) (poly2 geom-polygon)) (and (not (inside poly1 poly2)) (not (intersects poly1 poly2)))) ;;; ;;; ;;; (defmethod touching-tres ((poly1 geom-polygon) (poly2 geom-polygon) tres) "Arbeitet mit dem minimalen Abstand" (and (not (intersects poly1 poly2)) (let ((d (distance-between poly1 poly2))) (if (<= d tres) d)))) (defmethod touching-tres ((poly geom-polygon) (point geom-point) tres) (let ((d (distance-between poly point))) (if (<= d tres) d))) (defmethod touching-tres ((point geom-point) (poly geom-polygon) tres) (touching-tres poly point tres)) ;;; ;;; ;;; (defmethod covers-tres ((thing1 geom-thing) (thing2 geom-thing) tres) (and (inside thing2 thing1) (touching-tres thing2 thing1 tres))) ;;; ;;; ;;; (defun distance-and-orientation (x1 y1 x2 y2) (let* ( (dx (- x2 x1)) (dy (- y2 y1)) (d (sqrt (+ (* dx dx) (* dy dy)))) (phi (if (zerop dx) (if (minusp dy) (- (/ pi 2)) (/ pi 2)) (atan (/ dy dx)))) (phi2 (if (minusp dx) (+ phi pi) phi))) (values d phi2))) ;;; ;;; Master-Function ;;; (defun inverse (relation) (case relation (is-inside 'contains) (is-covered-by 'covers) (contains 'is-inside) (covers 'is-covered-by) (t relation))) (defun delete-object-from-cache (poly1 object-liste) (dolist (elem object-liste) (let* ((goedel1 (get-goedel poly1 elem)) (goedel2 (get-goedel elem poly1))) (remhash goedel1 *hash-table*) (remhash goedel2 *hash-table*)))) (defun get-goedel (x y) (* (expt 2 (tickval x)) (expt 3 (tickval y)))) ;;; ;;; ;;; (defun relate-poly-to-poly-unary-tres (poly1 poly2 tres) (let* ((goedel (get-goedel poly1 poly2)) (hash-rel (gethash goedel *hash-table*))) (if hash-rel hash-rel (let ((relation (if (intersects poly1 poly2) 'intersects (if (inside poly1 poly2) (let ((d (distance-between poly1 poly2))) (if (<= d tres) 'is-covered-by 'is-inside)) (let ((d (distance-between poly1 poly2))) (if (<= d tres) 'touches 'is-disjoint-with)))))) (setf (gethash goedel *hash-table*) relation) (if (member relation '(touches intersects)) (setf (gethash (get-goedel poly2 poly1) *hash-table*) relation)) relation))))
12,748
Common Lisp
.lisp
448
22.924107
93
0.569985
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
4037d2a394b488169c5ed6e1a516251907c820b8542e452d76b6189195aec745
11,205
[ -1 ]
11,206
janus-topology-4.lisp
lambdamikel_GenEd/src/geometry/janus-topology-4.lisp
;;;-*- Mode: Lisp; Package: PJ -*- (in-package :pj) (defparameter *touching-threshold* 4) ;;;---------------------------------------------------------------------------- ;;; Interface to subclasses: mixins (defclass topology-mixin () () (:documentation "Provides access to topological, spatial and geometrical~ features between geometrical objects with bounding boxes~ describing their spatial extent.")) (defclass rect-topology-mixin (topology-mixin) () (:documentation "Provides access to topological, spatial and geometrical~ features for rectangular objects.")) (defclass line-topology-mixin (rect-topology-mixin) () (:documentation "Provides access to topological, spatial and geometrical~ features for line-type objects.")) (defclass point-topology-mixin (line-topology-mixin) () (:documentation "Provides access to topological, spatial and geometrical~ features for point-type objects.")) ;;;---------------------------------------------------------------------------- ;;; Interface which has to be provided by subclasses (defgeneric get-topleft (object) (:documentation "Return topleft position of minimal rectangle which encloses this object")) (defgeneric get-bottomright (object &optional non-empty) (:documentation "Return bottomright position of minimal rectangle which encloses this object")) (defgeneric get-start-point (line-object) (:documentation "Return start point of line segment")) (defgeneric get-end-point (line-object) (:documentation "Return extended end point of line segment")) (defgeneric get-extended-start-point (line-object) (:documentation "Return extended start point of line segment")) (defgeneric get-extended-end-point (line-object) (:documentation "Return end point of line segment")) (defgeneric get-point (point-object) (:documentation "Return point of corresponding line segment")) (defgeneric get-extended-point (point-object) (:documentation "Return extended point of corresponding line segment")) ;;;---------------------------------------------------------------------------- ;;; Interface to subclasses: primitive topological relations (defgeneric disjoint-p (object1 object2) (:documentation "Two objects are disjoint if the intersection of their *extended* regions (1 pixel to right and bottom) is empty. disjoint is symmetric and applies to every situation.")) (defgeneric touching-p (object1 object2) (:documentation "Two objects are touching if only the boundaries of their *extended* regions (1 pixel to right and bottom) are intersecting. touching is symmetric and applies to every situation but point/point.")) (defgeneric overlapping-p (object1 object2) (:documentation "Two objects are overlapping if the intersection of their *original* regions is either a line or a point which is different to both objects. overlapping is symmetric and applies only to area/area and line/line situations.")) (defgeneric crossing-p (object1 object2) (:documentation "Two lines are crossing if their intersection is an internal point. A line crosses an area if the line is partly inside and outside of the area of the area's *extended* region (1 pixel to right and bottom). overlapping is symmetric and applies only to line/line and line/area situations.")) (defgeneric equal-p (object1 object2) (:documentation "Objects are equal if their regions have the same position end extent. equal is symmetric and applies to every situation.")) (defgeneric containing-p (object1 object2) (:documentation "An object A contains an object B if the intersection between A's and B's extended regions (1 pixel to right and bottom) is equal to B and and the interiors of their extended regions intersect. containing's inverse is inside. They apply to every situation.")) (defgeneric inside-p (object1 object2) (:documentation "inside is inverse of containing.")) (defgeneric query-relation (object relation candidate-list) (:documentation "Return every object in 'candidate-list' which is in 'relation' with 'object'")) (defgeneric spatial-orientation (object1 object2) (:documentation "Computes relative orientation between both objects. Recognized orientations: above, below, left-of, right-of. Second value is offset for touching.")) ;;;---------------------------------------------------------------------------- ;;; Interface to subclasses: composed topological relations (defgeneric covering-p (object1 object2) (:documentation "An object A is covering an object B if A's region completely contains B's region and B is touching A. covering applies only to area/area and area/line situations.")) (defgeneric covered-by-p (object1 object2) (:documentation "covered-by is inverse of covering.")) ;;;---------------------------------------------------------------------------- ;;; Macros (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant bb-size-correction #@(1 1) "Areas are sometimes reduced by size #@(1 1)")) (defmacro reduced (bottomright &optional (correction bb-size-correction)) `(subtract-points ,bottomright ,correction)) (defmacro extended (bottomright &optional (correction bb-size-correction)) `(add-points ,bottomright ,correction)) (eval-when (:compile-toplevel :load-toplevel :execute) (defun gen-features-decl (decl-list reduced-p) (mapcar #'(lambda (decl) `(,(first decl) (make-feature ,(second decl) ,reduced-p))) decl-list))) (defmacro with-orig-features (decl-list &body body) `(let ,(gen-features-decl decl-list nil) ,@body)) (defmacro with-reduced-features (decl-list &body body) `(let ,(gen-features-decl decl-list t) ,@body)) (defvar *pj-object-features* (make-hash-table :test #'eq)) (defmethod make-feature :around ((object topology-mixin) reduced-p) (let ((features (or (gethash object *pj-object-features*) (list nil)))) (prog1 (if reduced-p (or (cdr features) (setf (cdr features) (call-next-method))) (or (car features) (setf (car features) (call-next-method)))) (setf (gethash object *pj-object-features*) features)))) (defmethod make-feature ((object rect-topology-mixin) reduced-p) (slet ((br (get-bottomright object))) (make-area :topleft (get-topleft object) :bottomright (if reduced-p (reduced br) br)))) (defmethod make-feature ((object line-topology-mixin) reduced-p) (make-line (list (if reduced-p (get-start-point object) (get-extended-start-point object)) (if reduced-p (get-end-point object) (get-extended-end-point object))))) (defmethod make-feature ((object point-topology-mixin) reduced-p) (if reduced-p (get-point object) (get-extended-point object))) (defmethod make-feature ((object point-topology-mixin) reduced-p) (if reduced-p (get-point object) (make-area :pos (subtract-points (get-point object) #@(1 1)) :size #@(2 2)))) ;;;---------------------------------------------------------------------------- ;;; Topological predicates for rectangles (defmethod dim-of-intersect ((o1 rect-topology-mixin) (o2 rect-topology-mixin)) (with-reduced-features ((area1 o1) (area2 o2)) (dim-of-intersect area1 area2))) (defmethod disjoint-p ((o1 rect-topology-mixin) (o2 rect-topology-mixin)) (with-orig-features ((area1 o1) (area2 o2)) (not (intersecting-p area1 area2)))) (defmethod touching-p ((o1 rect-topology-mixin) (o2 rect-topology-mixin)) (and (with-orig-features ((area1 o1) (area2 o2)) (intersecting-p area1 area2)) (with-reduced-features ((area1 o1) (area2 o2)) (not (intersecting-p area1 area2))))) (defmethod almost-touching-p ((o1 rect-topology-mixin) (o2 rect-topology-mixin)) (with-orig-features ((area1 o1) (area2 o2)) (let ((dist (feature-distance area1 area2)))(print (point-string dist)) (< (max (abs (point-h dist)) (abs (point-v dist))) *touching-threshold*)))) (defmethod overlapping-p ((o1 rect-topology-mixin) (o2 rect-topology-mixin)) (and (with-reduced-features ((area1 o1) (area2 o2)) (intersecting-p area1 area2)) (not (or (containing-p o1 o2) (containing-p o2 o1))))) (defmethod crossing-p ((o1 rect-topology-mixin) (o2 rect-topology-mixin)) nil) (defmethod equal-p ((o1 rect-topology-mixin) (o2 rect-topology-mixin)) (with-orig-features ((area1 o1) (area2 o2)) (feature= area1 area2))) (defmethod containing-p ((o1 rect-topology-mixin) (o2 rect-topology-mixin)) (with-reduced-features ((feature1 o1) (feature2 o2)) (and (multiple-value-call #'bb-in-bb-p (bounding-box feature2) (bounding-box feature1)) (not (equal-p o1 o2))))) (defmethod inside-p ((o1 rect-topology-mixin) (o2 rect-topology-mixin)) (containing-p o2 o1)) ;;;---------------------------------------------------------------------------- ;;; Topological predicates for rectangles/lines and lines/lines (defmethod overlapping-p ((o1 rect-topology-mixin) (o2 line-topology-mixin)) nil) (defmethod overlapping-p ((o1 line-topology-mixin) (o2 rect-topology-mixin)) nil) (defmethod crossing-p ((o1 rect-topology-mixin) (o2 line-topology-mixin)) (with-orig-features ((area o1) (line o2)) (when (intersecting-p area line) (slet ((sp-in (multiple-value-call #'point-in-bb-p (start-point line) (bounding-box area))) (ep-in (multiple-value-call #'point-in-bb-p (end-point line) (bounding-box area)))) (not (and sp-in ep-in)))))) (defmethod crossing-p ((o1 rect-topology-mixin) (o2 line-topology-mixin)) (with-orig-features ((area o1) (line o2)) (and (intersecting-p area line) (with-reduced-features ((rarea o1) (rline o2)) (intersecting-p rarea rline)) (not (containing-p o1 o2)) (= (dim-of-intersect area line) (1- (max (dimension area) (dimension line))))))) (defmethod crossing-p ((o1 line-topology-mixin) (o2 rect-topology-mixin)) (crossing-p o2 o1)) (defmethod crossing-p ((o1 line-topology-mixin) (o2 line-topology-mixin)) (with-reduced-features ((feature1 o1) (feature2 o2)) (eq (dim-of-intersect feature1 feature2) 0))) (defmethod equal-p ((o1 rect-topology-mixin) (o2 line-topology-mixin)) nil) (defmethod equal-p ((o1 line-topology-mixin) (o2 rect-topology-mixin)) nil) (defmethod equal-p ((o1 line-topology-mixin) (o2 line-topology-mixin)) (and (= (get-topleft o1) (get-topleft o2)) (= (get-bottomright o1) (get-bottomright o2)) (with-orig-features ((feature1 o1) (feature2 o2)) (feature= feature1 feature2)))) (defmethod containing-p ((o1 line-topology-mixin) (o2 line-topology-mixin)) (and (call-next-method) (with-orig-features ((feature1 o1) (feature2 o2)) (= 1 (dim-of-intersect feature1 feature2))))) (defmethod almost-touching-p ((o1 rect-topology-mixin) (o2 line-topology-mixin)) (with-reduced-features ((area1 o1) (area2 o2)) (let ((dist (feature-distance area1 area2)))(print (point-string dist)) (< (max (abs (point-h dist)) (abs (point-v dist))) *touching-threshold*)))) (defmethod almost-touching-p ((o1 line-topology-mixin) (o2 rect-topology-mixin)) (almost-touching-p o2 o1)) (defmethod almost-touching-p ((o1 line-topology-mixin) (o2 line-topology-mixin)) (with-orig-features ((feature1 o1) (feature2 o2)) (feature-distance feature1 feature2))) ;;;---------------------------------------------------------------------------- ;;; Topological predicates for point/other (defmethod dim-of-intersect ((o1 point-topology-mixin) (o2 point-topology-mixin)) (with-reduced-features ((point1 o1) (point2 o2)) (when (= point1 point2) 0))) (defmethod touching-p ((o1 point-topology-mixin) (o2 point-topology-mixin)) nil) (defmethod overlapping-p ((o1 point-topology-mixin) (o2 line-topology-mixin)) nil) (defmethod overlapping-p ((o1 line-topology-mixin) (o2 point-topology-mixin)) nil) (defmethod overlapping-p ((o1 point-topology-mixin) (o2 point-topology-mixin)) nil) (defmethod crossing-p ((o1 point-topology-mixin) (o2 rect-topology-mixin)) nil) (defmethod crossing-p ((o1 rect-topology-mixin) (o2 point-topology-mixin)) nil) (defmethod crossing-p ((o1 line-topology-mixin) (o2 point-topology-mixin)) nil) (defmethod crossing-p ((o1 point-topology-mixin) (o2 point-topology-mixin)) nil) (defmethod containing-p ((o1 point-topology-mixin) (o2 rect-topology-mixin)) nil) (defmethod containing-p ((o1 line-topology-mixin) (o2 point-topology-mixin)) (with-reduced-features ((feature1 o1) (feature2 o2)) (intersecting-p feature1 feature2))) (defmethod containing-p ((o1 rect-topology-mixin) (o2 point-topology-mixin)) (with-reduced-features ((feature1 o1) (feature2 o2)) (intersecting-p feature1 feature2))) (defmethod inside-p ((o1 rect-topology-mixin) (o2 point-topology-mixin)) nil) (defmethod inside-p ((o1 line-topology-mixin) (o2 point-topology-mixin)) nil) (defmethod inside-p ((o1 point-topology-mixin) (o2 rect-topology-mixin)) (containing-p o2 o1)) (defmethod equal-p ((o1 point-topology-mixin) (o2 rect-topology-mixin)) nil) (defmethod equal-p ((o1 rect-topology-mixin) (o2 point-topology-mixin)) nil) (defmethod equal-p ((o1 line-topology-mixin) (o2 point-topology-mixin)) nil) (defmethod equal-p ((o1 point-topology-mixin) (o2 point-topology-mixin)) (with-orig-features ((point1 o1) (point2 o2)) (feature= point1 point2))) ;;;---------------------------------------------------------------------------- ;;; Composed topological predicates (defmethod covering-p ((o1 rect-topology-mixin) (o2 rect-topology-mixin)) (and (containing-p o1 o2) (with-reduced-features ((area1 o1) (area2 o2)) (weak-covering-p area1 area2)))) (defmethod covered-by-p ((o1 rect-topology-mixin) (o2 rect-topology-mixin)) (covering-p o2 o1)) (defun weak-covering-p (area1 area2) (slet* ((barea2 (boundary area2)) (dim (dim-of-intersect (boundary (interior area1)) barea2))) (and dim (= dim (dimension barea2))))) ;;;---------------------------------------------------------------------------- ;;; Compute topological relations (defun compute-topology-relation (o1 o2) (with-orig-features ((feature1 o1) (feature2 o2)) (if (intersecting-p feature1 feature2) (if (equal-p o1 o2) 'equal (with-reduced-features ((rfeature1 o1) (rfeature2 o2)) (if (intersecting-p rfeature1 rfeature2) (cond ((containing-p o1 o2) (if (weak-covering-p rfeature1 rfeature2) 'covering 'containing)) ((containing-p o2 o1) (if (weak-covering-p rfeature2 rfeature1) 'covered-by 'inside)) ((= (dim-of-intersect feature1 feature2) (1- (max (dimension feature1) (dimension feature2)))) 'crossing) (t 'overlapping)) 'touching))) 'disjoint))) (defun compute-all-relations (object-list) (maplist #'(lambda (list1) (compute-relation (first list1) (rest list1))) object-list)) (defmethod compute-relation ((object-list-1 list) (object-list-2 list)) (mapcar #'(lambda (obj) (compute-relation obj (remove obj object-list-2))) object-list-1)) (defmethod compute-relation ((object topology-mixin) (object-list list)) (list* object (apply #'nconc (mapcar #'(lambda (obj) (compute-relation object obj)) (remove object object-list))))) (defmethod compute-relation ((object-1 point-topology-mixin) (object-2 point-topology-mixin)) nil) (defmethod compute-relation ((object-1 topology-mixin) (object-2 topology-mixin)) (let ((rel-dim (topology-relation object-1 object-2 nil))) (verify-relation (or (car rel-dim) 'disjoint) object-1 object-2) (when rel-dim (list (list (car rel-dim) object-2) #|(list 'intersection-dim object-2 (cdr rel-dim))|#)))) (defvar *pj-objects-in-cache* (make-hash-table :test #'eq)) (defvar *pj-relations-cache* (make-hash-table :test #'equal :size (* 2 (hash-table-size *pj-objects-in-cache*)))) (defun clear-caches () (setf *pj-object-features* (make-hash-table :test #'eq) *pj-objects-in-cache* (make-hash-table :test #'eq) *pj-relations-cache* (make-hash-table :test #'equal :size (* 2 (hash-table-size *pj-objects-in-cache*))))) (defun add-to-caches (key o1 o2 value) (push key (gethash o1 *pj-objects-in-cache*)) (push key (gethash o2 *pj-objects-in-cache*)) (setf (gethash key *pj-relations-cache*) value) value) (defun do-remove-from-caches (object) (dolist (key (gethash object *pj-objects-in-cache*)) (remhash key *pj-relations-cache*)) (remhash object *pj-objects-in-cache*) (remhash object *pj-object-features*)) (defmethod remove-from-caches ((object topology-mixin)) (do-remove-from-caches object)) (defmethod remove-from-caches ((object line-topology-mixin)) (do-remove-from-caches object) (dolist (point (points object)) (remove-from-caches point))) (defmethod remove-from-caches ((object point-topology-mixin)) (do-remove-from-caches object)) (defun print-caches (object) (pprint (list (list object (gethash object *pj-objects-in-cache*)) (mapcar #'(lambda (o) (list o (gethash o *pj-relations-cache*))) (gethash object *pj-objects-in-cache*)) (list object (gethash object *pj-object-features*)))) (when (slot-exists-p object 'points) (mapc #'print-caches (points object)))) (defun test-relations-cache () (loop for key being the hash-key of *pj-relations-cache* using (hash-value val) always (relation-exclusive-p (car val) (car key) (cdr key)))) (defun topology-relation (o1 o2 complete-p) (let ((key (cons o1 o2))) (or (gethash key *pj-relations-cache*) (let ((rel (compute-topology-relation o1 o2))) (if (eq rel 'disjoint) (and complete-p (cons 'disjoint nil)) (add-to-caches key o1 o2 (cons rel (dim-of-intersect o1 o2)))))))) (defmethod set-view-position :after ((view topology-mixin) h &optional v) (declare (ignore h v)) (remove-from-caches view)) (defmethod set-view-size :after ((view topology-mixin) h &optional v) (declare (ignore h v)) (remove-from-caches view)) (defmethod set-view-container :after ((view topology-mixin) new-container) (declare (ignore new-container)) (remove-from-caches view)) (defun relationp (rel o1 o2) (multiple-value-bind (value found) (gethash (cons o1 o2) *pj-relations-cache*) (print value) (and found (eq value rel)))) (defun print-topology-relation (o1 o2) (let ((rel (compute-topology-relation o1 o2)) (inv-rel (compute-topology-relation o2 o1))) (and (relation-exclusive-p rel o1 o2) (relation-exclusive-p inv-rel o2 o1)) (format t "~&Topological relation:~%~A ~A ~A" o1 rel o2) (format t "~%~A ~A INTERSECTION-DIM ~A~%" o1 o2 (dim-of-intersect o1 o2)) (unless (eq rel inv-rel) (format t "~&Topological relation:~%~A ~A ~A~%" o2 inv-rel o1)))) (defun verify-relation (rel o1 o2) (or (funcall (relation-function rel) o1 o2) (cerror "return T" "Inconsistency detected for relation:~%(~A-P ~S ~S) returned NIL" rel o1 o2) t)) (defconstant relations '(disjoint touching inside containing overlapping crossing equal)) (defun relation-exclusive-p (rel o1 o2) (and (verify-relation rel o1 o2) (let ((result (mapcar #'(lambda (rel) (funcall (relation-function rel) o1 o2)) relations))) (or (= 1 (count t result)) (cerror "return T" "relation ~A-P not exclusive for ~S ~S !~% result: ~S" rel o1 o2 (mapcar #'(lambda (rel pred) (list rel pred)) relations result)) t)))) (defun relation-function (relation) (case relation (disjoint #'disjoint-p) (touching #'touching-p) (inside #'inside-p) (containing #'containing-p) (overlapping #'overlapping-p) (crossing #'crossing-p) (equal #'equal-p) (covering #'covering-p) (covered-by #'covered-by-p) (otherwise (error "Relation function of ~A undefined" relation))))
20,934
Common Lisp
.lisp
431
42.422274
82
0.650527
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
d3579efe69c92eb025bcc3c35ca7ae4f16f07be58f7f5b4324a7bb94a4eab9a8
11,206
[ -1 ]
11,207
newgeo.lisp
lambdamikel_GenEd/src/geometry/newgeo.lisp
(require "~/geometry/defpackage.lisp") (in-package :geometry) (defconstant +big-int+ 10000) ;;; ;;; Topological Relations for Polygons. ;;; ;;; ;;; Konstruktoren ;;; (defclass geom-line () ((p1 :initform nil :initarg :p1 :accessor p1) (p2 :initform nil :initarg :p2 :accessor p2))) (defclass geom-point () ((x :initform 0 :initarg :x :accessor x) (y :initform 0 :initarg :y :accessor y))) (defclass geom-polygon () ((point-arr :initform nil :initarg :point-arr :accessor point-arr) ; range: 1..n (line-arr :initform nil :initarg :line-arr :accessor line-arr) ; range: 0..n/n-1 (ext-point-arr :initform nil :initarg :ext-point-arr :accessor ext-point-arr) ; range : 1..n (ext-line-arr :initform nil :initarg :ext-line-arr :accessor ext-line-arr) (closed :initform t :initarg :closed :accessor closed))) ;;; ;;; Basis-Funktionen ;;; (defmethod ccw ((p0 geom-point) (p1 geom-point) (p2 geom-point)) "Quelle: Sedgewick" (let* ((x0 (x p0)) (x1 (x p1)) (x2 (x p2)) (y0 (y p0)) (y1 (y p1)) (y2 (y p2)) (dx1 (- x1 x0)) (dy1 (- y1 y0)) (dx2 (- x2 x0)) (dy2 (- y2 y0))) (cond ((> (* dx1 dy2) (* dy1 dx2)) 1) ((< (* dx1 dy2) (* dy1 dx2)) -1) ((or (< (* dx1 dx2) 0) (< (* dy1 dy2) 0)) -1) ((< (+ (* dx1 dx1) (* dy1 dy1)) (+ (* dx2 dx2) (* dy2 dy2))) 1) (t 0)))) (defmethod intersects ((l1 geom-line) (l2 geom-line) &key &allow-other-keys) "Quelle: Sedgewick" (let ((l1p1 (p1 l1)) (l2p1 (p1 l2)) (l1p2 (p2 l1)) (l2p2 (p2 l2))) (and (<= (* (ccw l1p1 l1p2 l2p1) (ccw l1p1 l1p2 l2p2)) 0) (<= (* (ccw l2p1 l2p2 l1p1) (ccw l2p1 l2p2 l1p2)) 0)))) ;;; ;;; Hilfsfunktionen ;;; (defun draw-lines (l1 l2 col) #| (set-foreground-color my-window col) (draw-line my-window (make-position (round (x (p1 l1))) (round (y (p1 l1)))) (make-position (round (x (p2 l1))) (round (y (p2 l1))))) (draw-line my-window (make-position (round (x (p1 l2))) (round (y (p1 l2)))) (make-position (round (x (p2 l2))) (round (y (p2 l2)))))) |# ) (defun make-geom-polygon (point-list tres &key (is-closed t)) ; Fehler: wenn &key (closed t) ! (let* ((poly (make-instance 'geom-polygon :closed is-closed))) (setf (point-arr poly) (make-geom-point-arr point-list) (line-arr poly) (make-geom-line-arr (point-arr poly) :closed is-closed) (ext-point-arr poly) (make-ext-geom-point-arr (point-arr poly) tres) (ext-line-arr poly) (make-geom-line-arr (ext-point-arr poly) :closed is-closed)) poly)) (defun make-geom-point (x y) (make-instance 'geom-point :x x :y y)) (defun make-geom-point-arr (liste) (let ((arr (make-array (+ 2 (length liste)))) (i 1)) (dolist (elem liste) (setf (aref arr i) (make-geom-point (first elem) (second elem))) (incf i)) (setf (aref arr 0) (aref arr (1- i))) (setf (aref arr i) (aref arr 1)) arr)) (defun make-geom-line (p1 p2) (make-instance 'geom-line :p1 p1 :p2 p2)) ; Referenzen auf tats. Punkte, keine Kopien!!! (defun make-geom-line-arr (point-arr &key (closed t)) (let* ((dim (if closed (- (first (array-dimensions point-arr)) 2) (- (first (array-dimensions point-arr)) 3))) (arr (make-array (list dim)))) (dotimes (i dim) (setf (aref arr i) (make-geom-line (aref point-arr (+ i 1)) (aref point-arr (+ i 2))))) arr)) ;;;; ;;;; ;;;; (defun calculate-bounding-box (arr) (let* ((minx (x (aref arr 0))) (miny (y (aref arr 0))) (maxx minx) (maxy miny)) (dotimes (i (1- (first (array-dimensions arr)))) (let* ((point (aref arr i)) (y (y point)) (x (x point))) (cond ((< x minx) (setf minx x)) ((> x maxx) (setf maxx x)) ((< y miny) (setf miny y)) ((> y maxy) (setf maxy y))))) (values minx miny maxx maxy))) (defun calculate-center (arr) (multiple-value-bind (xf yf xt yt) (calculate-bounding-box arr) (values (/ (+ xf xt) 2) (/ (+ yf yt) 2)))) (defun make-ext-geom-point-arr (point-arr tres) (let* ((dim (first (array-dimensions point-arr))) (arr (make-array (list dim)))) (multiple-value-bind (xc yc) (calculate-center point-arr) (dotimes (i dim) (let* ((point (aref point-arr i)) (x (x point)) (y (y point)) (dx (- x xc)) (dy (- y yc)) (d (sqrt (+ (* dx dx) (* dy dy)))) (phi (if (zerop dx) (if (minusp dy) (- (/ pi 2)) (/ pi 2)) (atan (/ dy dx)))) (phi2 (if (minusp dx) (+ phi pi) phi)) (new-d (+ d tres)) (new-x (round (+ (* new-d (cos phi2)) xc))) (new-y (round (+ (* new-d (sin phi2)) yc)))) (setf (aref arr i) (make-geom-point new-x new-y))))) arr)) ;;; ;;; Abstandsfunktionen ;;; (defmethod distance-between ((point geom-point) (line geom-line)) (let* ((lp1 (p1 line)) (lp2 (p2 line)) (lx1 (x lp1)) (ly1 (y lp1)) (lx2 (x lp2)) (ly2 (y lp2)) (px (x point)) (py (y point)) (ax (- lx2 lx1)) (ay (- ly2 ly1)) (dx (- lx1 px)) (dy (- ly1 py)) (a2 (+ (* ax ax) (* ay ay))) (scalar (/ (+ (* ax (- dx)) (* ay (- dy))) a2)) (x (+ dx (* scalar ax))) (y (+ dy (* scalar ay)))) (values (sqrt (+ (* x x) (* y y))) scalar x y))) (defmethod distance-between ((line1 geom-line) (line2 geom-line)) (flet ((betw-0-and-1 (number) (and (not (minusp number)) (<= number 1.0)))) (multiple-value-bind (d1 s1 x1 y1) (distance-between (p1 line1) line2) (multiple-value-bind (d2 s2 x2 y2) (distance-between (p2 line1) line2) (multiple-value-bind (d3 s3 x3 y3) (distance-between (p1 line2) line1) (multiple-value-bind (d4 s4 x4 y4) (distance-between (p2 line2) line1) (let* ((big-int 10000) (min (min (if (betw-0-and-1 s1) d1 big-int) (if (betw-0-and-1 s2) d2 big-int) (if (betw-0-and-1 s3) d3 big-int) (if (betw-0-and-1 s4) d4 big-int)))) (cond ((= min d1) (values d1 x1 y1)) ((= min d2) (values d2 x2 y2)) ((= min d3) (values d3 x3 y3)) ((= min d4) (values d4 x4 y4)) (t (let* ((dx1 (- (x (p1 line1)) (x (p1 line2)))) (dx2 (- (x (p2 line1)) (x (p1 line2)))) (dx3 (- (x (p1 line1)) (x (p2 line2)))) (dx4 (- (x (p2 line1)) (x (p2 line2)))) (dy1 (- (y (p1 line1)) (y (p1 line2)))) (dy2 (- (y (p2 line1)) (y (p1 line2)))) (dy3 (- (y (p1 line1)) (y (p2 line2)))) (dy4 (- (y (p2 line1)) (y (p2 line2)))) (d1 (sqrt (+ (* dx1 dx1) (* dy1 dy1)))) (d2 (sqrt (+ (* dx2 dx2) (* dy2 dy2)))) (d3 (sqrt (+ (* dx3 dx3) (* dy3 dy3)))) (d4 (sqrt (+ (* dx4 dx4) (* dy4 dy4))))) (values (min d1 d2 d3 d4) 0 0))))))))))) (defmethod distance-between ((poly1 geom-polygon) (poly2 geom-polygon)) (let ((min +big-int+) (line-arr1 (line-arr poly1)) (line-arr2 (line-arr poly2))) (dotimes (i (first (array-dimensions line-arr1))) (dotimes (j (first (array-dimensions line-arr2))) (let ((d (distance-between (aref line-arr1 i) (aref line-arr2 j)))) (if (< d min) (setf min d))))) min)) ;;; ;;; Relationen! ;;; (defmethod inside ((point geom-point) (polygon geom-polygon) &key (mode :normal) (draw nil) &allow-other-keys) "Nicht ganz korrekt !!! Quelle: Sedgewick, modifiziert!" (when (closed polygon) (let* ((count1 0) (count2 0) (j 0) (arr (ecase mode (:normal (point-arr polygon)) (:extended (point-arr polygon)))) (n (- (first (array-dimensions arr)) 2)) (x (x point)) (y (y point)) (lp (make-geom-line (make-geom-point 0 0) (make-geom-point 0 0))) (lt (make-geom-line (make-geom-point x y) (make-geom-point +big-int+ y)))) ; wegen ALIAS-Effekten! (dotimes (m n) (let ((i (1+ m))) (setf (p1 lp) (aref arr i)) (when (and (not (and (= (y (p1 lp)) (y (p1 lt))) (>= (x (p1 lp)) (x (p1 lt))))) (not (and (= (y (aref arr j)) (y (p1 lt))) (>= (x (aref arr j)) (x (p1 lt)))))) (setf (p2 lp) (aref arr j)) (setf j i) (when (intersects lp lt) (incf count1) (if draw (draw-lines lp lt blue)))))) (if draw (print count1)) (let ((lt (make-geom-line (make-geom-point x y) (make-geom-point (- +big-int+) y)))) ; wegen ALIAS-Effekten! (dotimes (m n) (let ((i (1+ m))) (setf (p1 lp) (aref arr i)) (when (and (not (and (= (y (p1 lp)) (y (p1 lt))) (<= (x (p1 lp)) (x (p1 lt))))) (not (and (= (y (aref arr j)) (y (p1 lt))) (<= (x (aref arr j)) (x (p1 lt)))))) (setf (p2 lp) (aref arr j)) (setf j i) (when (intersects lp lt) (incf count2) (if draw (draw-lines lp lt blue)))))) (if draw (print count2)) (or (not (zerop (mod count1 2))) (not (zerop (mod count2 2)))))))) #| (defmethod inside ((point geom-point) (polygon geom-polygon) &key (mode :normal) (draw nil) &allow-other-keys) "Nur fuer konvexe Polygone" (let* ((arr (ecase mode (:normal (point-arr polygon)) (:extended (point-arr polygon)))) (n (- (first (array-dimensions arr)) 2)) (ok (dotimes (m n) (if (< (ccw (aref arr m) (aref arr (1+ m)) point) 0) (return t))))) (not ok))) |# (defmethod inside ((poly1 geom-polygon) (poly2 geom-polygon) &key &allow-other-keys) (when (closed poly2) (let* ((arr (point-arr poly1)) (ok (dotimes (i (- (first (array-dimensions arr)) 2)) (when (not (inside (aref arr (1+ i)) poly2)) (return t))))) (not ok)))) (defmethod intersects ((line geom-line) (poly geom-polygon) &key (poly-mode :normal) &allow-other-keys) (let* ((arr (ecase poly-mode (:normal (line-arr poly)) (:extended (ext-line-arr poly)))) (ok (dotimes (i (first (array-dimensions arr))) (if (intersects (aref arr i) line) (return t))))) ok)) (defmethod intersects ((poly1 geom-polygon) (poly2 geom-polygon) &key (poly-mode1 :normal) (poly-mode2 :normal) &allow-other-keys) (let* ((arr (ecase poly-mode1 (:normal (line-arr poly1)) (:extended (ext-line-arr poly1)))) (ok (dotimes (i (first (array-dimensions arr))) (if (intersects (aref arr i) poly2 :poly-mode poly-mode2) (return t))))) ok)) (defmethod disjoint ((poly1 geom-polygon) (poly2 geom-polygon)) (and (not (inside poly1 poly2)) (not (intersects poly1 poly2)))) (defmethod touching ((poly1 geom-polygon) (poly2 geom-polygon)) "Arbeitet mit dem unsichtbaren extended-Polygon-Rand (s. Harsleev)" (and (not (intersects poly1 poly2)) (or (intersects poly1 poly2 :poly-mode1 :extended) (intersects poly1 poly2 :poly-mode2 :extended)))) (defmethod touching-tres ((poly1 geom-polygon) (poly2 geom-polygon) tres) "Arbeitet mit dem minimalen Abstand" (and (not (intersects poly1 poly2)) (let ((d (distance-between poly1 poly2))) (if (<= d tres) d)))) (defmethod covers ((poly1 geom-polygon) (poly2 geom-polygon)) (and (inside poly2 poly1) (touching poly2 poly1))) (defmethod covers-tres ((poly1 geom-polygon) (poly2 geom-polygon) tres) (and (inside poly2 poly1) (touching-tres poly2 poly1 tres))) ;;; ;;; Master-Function ;;; (defun relate-poly-to-poly (poly1 poly2) #| (if (intersects poly1 poly2) 'intersects (if (inside poly1 poly2) (if (intersects poly1 poly2 :poly-mode1 :extended) 'covering 'inside) (if (intersects poly1 poly2 :poly-mode1 :extended) 'touching 'disjoint)))) |# ) (defun relate-poly-to-poly-tres (poly1 poly2 tres) (if (intersects poly1 poly2) 'intersects (if (inside poly1 poly2) (let ((d (distance-between poly1 poly2))) (if (<= d tres) 'is-covered-by 'is-inside)) (if (inside poly2 poly1) (let ((d (distance-between poly2 poly1))) (if (<= d tres) 'covers 'contains)) (let ((d (distance-between poly1 poly2))) (if (<= d tres) 'touches 'is-disjoint-with))))))
13,288
Common Lisp
.lisp
427
23.859485
84
0.529313
lambdamikel/GenEd
18
3
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
47d3af077336e98609ee23e1c7acb72fe97425337164bbf7df44332658717968
11,207
[ -1 ]