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
listlengths
1
47
6,689
numeric-date-utilities.lisp
white-flame_clyc/larkc-cycl/numeric-date-utilities.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc $ Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. $ Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. $ You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. $ This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at $ http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defconstant *seconds-in-a-leap-year* 31622400 "[Cyc] True") (defconstant *seconds-in-a-non-leap-year* 31536000 "[Cyc] Also True") (defconstant *seconds-in-a-week* 604800 "[Cyc] Right") (defconstant *seconds-in-a-day* 86400 "[Cyc] Yep.") (defconstant *seconds-in-an-hour* 3600 "[Cyc] uh-huh.") (defconstant *seconds-in-a-minute* 60 "[Cyc] the number of seconds in a minute") (defconstant *minutes-in-an-hour* 60 "[Cyc] the number of minues in an hour") (defconstant *hours-in-a-day* 24 "[Cyc] the number of hours in a day") (defconstant *months-in-a-year* 12 "[Cyc] the number of months in a year") (defun universal-time-seconds-from-now (seconds &optional (reference-time (get-universal-time))) "[Cyc] the universal time SECONDS from REFERENCE-TIME" (+ reference-time (if (integerp seconds) seconds (truncate seconds)))) (defun time-from-now (seconds) "[Cyc] Legacy function name" (universal-time-seconds-from-now seconds)) (defun timestring (&optional (universal-time (get-universal-time))) "[Cyc] TIMESTRING returns a string in the format mm/dd/yyyy hh:mm:ss from the universal time given. If none is given, the current time is used." (timestring-int universal-time)) (defun timestring-int (universal-time) (multiple-value-bind (second minute hour date month year) (decode-universal-time universal-time) (encode-timestring second minute hour date month year))) (defun encode-timestring (second minute hour date month year) (encode-datetime-string-from-template nil second minute hour date month year "mm/dd/yyyy hh:mm:ss")) (defun universal-timestring (&optional (universal-time (get-universal-time))) "[Cyc] UNIVERSAL-TIMESTRING returns a string in the format yyyymmddhhmmss from the universal time given. If none is given, the current time is used." (multiple-value-bind (second minute hour date month year) (decode-universal-time universal-time) (encode-universal-timestring second minute hour date month year))) (defun encode-universal-timestring (second minute hour date month year) (format nil "~4,'0d~2,'0d~2,'0d~2,'0d~2,'0d~2,'0d" year month date hour minute second)) (defun internal-real-time-p (object) "[Cyc] Return T iff OBJECT is an internal real time." (typep object '(integer 0))) (defun elapsed-internal-real-time (reference-time &optional (comparison-time (get-internal-real-time))) "[Cyc] Return the number of elapsed internal real time units from COMPARISON-TIME to REFERENCE-TIME." (- comparison-time reference-time)) (defun elapsed-internal-real-time-to-elapsed-seconds (elapsed) (/ elapsed internal-time-units-per-second)) (defun encode-datetime-string-from-template (millisecond second minute hour day month year template) "[Cyc] Returns a string in the format specified by TEMPLATE representing the datetime having the stated values for MILLISECOND, SECOND, MINUTE, HOUR, DAY, MONTH, YEAR." ;; TODO - this function is missing ;;(check-type template #'datetime-string-template-p) (let* ((subtemplates (break-words template #'non-whitespace-p)) (template1 (first subtemplates)) (template2 (second subtemplates)) (length (length subtemplates))) (cond ((and (= length 2) (date-template-p template1) (time-template-p template2)) (format nil "~a ~a" (encode-date-from-template day month year template1) (encode-time-from-template millisecond second minute hour template2))) ((and (= length 2) (time-template-p template1) (date-template-p template2)) (format nil "~a ~a" (encode-time-from-template millisecond second minute hour template1) (encode-date-from-template day month year template2))) ((and (= length 1) (date-template-p template1)) (encode-date-from-template day month year template1)) ((and (= length 1) (time-template-p template1)) (encode-time-from-template millisecond second minute hour template2)) (t (error "Template ~s is not a valid datetime-string template." template))))) (defun valid-date-template-char (char) (member char '(#\y #\Y #\m #\M #\d #\D #\/ #\- #\_))) (defun valid-date-separator (char) (member char '(#\/ #\- #\_))) (defun valid-year-token (char) (member char '(#\y #\Y))) (defun valid-month-token (char) (member char '(#\m #\M))) (defun valid-day-token (char) (member char '(#\d #\D))) (defun date-template-p (template) (every #'valid-date-template-char template)) (defun time-template-p (template) (member template '("hh:mm:ss" "hh:mm:ss.mmm" "hh:mm" "hh:mm:ss.m" "hh:mm:ss.mm") :test #'string=)) (defun n-digit-template-element-p (template n token-checker separator-checker) (when (>= (length template) n) (dotimes (index n) (unless (funcall token-checker (char template index)) (return nil))) (unless (and (> (length template) n) (not (funcall separator-checker (char template n)))) t))) (defun encode-date-from-template (day month year template) (cond ((n-digit-template-element-p template 4 #'valid-year-token #'valid-date-separator) (encode-next-date-element day month year template 4 year)) ((n-digit-template-element-p template 2 #'valid-year-token #'valid-date-separator) (encode-next-date-element day month year template 2 (mod year 100))) ((n-digit-template-element-p template 2 #'valid-month-token #'valid-date-separator) (encode-next-date-element day month year template 2 month)) ((n-digit-template-element-p template 2 #'valid-day-token #'valid-date-separator) (encode-next-date-element day month year template 2 day)) (t (error "Date template or template portion ~s didn't match any expected pattern" template)))) (defun encode-next-date-element (day month year template elem-length item) (let ((format-string (format nil "~~~a,'0d~~a" elem-length))) (format nil format-string item (if (> (1+ elem-length) (length template)) "" (format nil "~a~a" (char template elem-length) (encode-date-from-template day month year (subseq template (1+ elem-length)))))))) (defun encode-time-from-template (millisecond second minute hour template) (cond ((not hour) "") ((equalp template "hh:mm:ss") (format nil "~2,'0d:~2,'0d:~s,'0d" hour minute second)) ((equalp template "hh:mm") (format nil "~2,'0d:~2,'0d" hour minute)) ((equalp template "hh:mm:ss.mmm") (format nil "~2,'0d:~2,'0d:~2,'0d.~3,'0d" hour minute second millisecond)) ((equalp template "hh:mm:ss.mm") (format nil "~2,'0d:~2,'0d:~2,'0d.~2,'0d" hour minute second millisecond)) ((equalp template "hh:mm:ss.m") (format nil "~2,'0d:~2,'0d:~2,'0d.~1,'0d" hour minute second millisecond)) (t (error "Time template or template portion ~s didn't match any expected pattern" template)))) (defun decode-elapsed-seconds (elapsed-seconds) "[Cyc] Decode ELAPSED-SECONDS into 4 return values: seconds minutes hours elapsed-days" (declare ((integer 0) elapsed-seconds)) (multiple-value-bind (truncated-exact-seconds partial-seconds) (truncate elapsed-seconds) (destructuring-bind (whole-seconds &optional (minutes 0) (hours 0) (elapsed-days 0)) (decode-integer-multiples truncated-exact-seconds (list *seconds-in-a-minute* *minutes-in-an-hour* *hours-in-a-day*)) (values (+ whole-seconds partial-seconds) minutes hours elapsed-days)))) (defun universal-date-p (object) "[Cyc] Return T iff OBJECT is a valid universal date." (when (integerp object) (when (minusp object) (universal-date-p (- object))) (let* ((temp object) (day (rem temp 100))) (when (<= day 31) (setf temp (floor temp 100)) (let ((month (rem temp 100))) (and (<= 1 month) (<= month 12))))))) (defun get-universal-date (&optional (universal-time (get-universal-time)) time-zone) "[Cyc] Return the current date as an integer, i.e. 19660214." (multiple-value-bind (second minute hour day month year) (decode-universal-time universal-time time-zone) (declare (ignore second minute hour)) (encode-universal-date day month year))) (defun encode-universal-date (day month year) "[Cyc] Encode DAY MONTH YEAR in a universal date integer of the form yyyymmdd." (if (minusp year) (- (encode-universal-date day month (- year))) (+ (* year 10000) (* month 100) day))) (defconstant *julian-date-reference* (cons 20010801 2452122.5d0) "[Cyc] A known pair to compute offset from. The Julian date for the start of Aug 1, 2001 is 2452122.5.") (defglobal *julian-offsets* nil "[Cyc] ALISTP of number of days to add to get Julian date, with different precisions.") (defun universal-second-p (object) "[Cyc] Return T iff OBJECT is a valid universal second." (when (and (integerp object) (not (minusp object)) (<= object 235959)) (let ((temp object)) (when (< (rem temp 100) *seconds-in-a-minute*) (setf temp (floor temp 100)) (when (< (rem temp 100) *minutes-in-an-hour*) (setf temp (floor temp 100)) (< temp *hours-in-a-day*)))))) (defun get-universal-second (&optional (universal-time (get-universal-time))) "[Cyc] Return the current second within the day as an integer in HHMMSS form, i.e. 235959." (multiple-value-bind (second minute hour day month year) (decode-universal-time universal-time) (declare (ignore day month year)) (encode-universal-second second minute hour))) (defun encode-universal-second (second minute hour) "[Cyc] Encode SECOND MINUTE HOUR in a universal second integer of the form HHMMSS." (must (and (<= 0 second) (<= second 59)) "second ~s not in the range 0-59" second) (must (and (<= 0 minute) (<= minute 59)) "minute ~s not in the range 0-59" minute) (must (and (<= 0 hour) (<= hour 59)) "hour ~s not in the range 0-59" hour) (+ (* hour 10000) (* minute 100) second)) (defun get-utc-time-with-milliseconds () "[Cyc] Returns the current UTC time with millisecond accuracy, taking into account the platform-specfic implementations of get-internal-real-time." (let* ((internal-real-time (get-internal-real-time)) (universal-time (get-universal-time)) (divisor (/ internal-time-units-per-second 1000)) (internal-real-time-in-milliseconds (truncate (/ internal-real-time divisor))) (milliseconds (rem internal-real-time-in-milliseconds 1000)) (time-in-milliseconds (+ (* universal-time 1000) milliseconds))) time-in-milliseconds)) (deflexical *month-duration-table* '(31 28 31 30 31 30 31 31 30 31 30 31) "[Cyc] The usual number of days for each month.") (deflexical *number-wkday-table* '((0 . "Mon") (1 . "Tue") (2 . "Wed") (3 . "Thu") (4 . "Fri") (5 . "Sat") (6 . "Sun"))) (deflexical *number-month-table* '(( 1 . "Jan") ( 2 . "Feb") ( 3 . "Mar") ( 4 . "Apr") ( 5 . "May") ( 6 . "Jun") ( 7 . "Jul") ( 8 . "Aug") ( 9 . "Sep") (10 . "Oct") (11 . "Nov") (12 . "Dec"))) (defun elapsed-time-abbreviation-string (elapsed-seconds) (multiple-value-bind (secs mins hours days) (decode-elapsed-seconds elapsed-seconds) (setf secs (truncate secs)) (cond ((> days 0) (format nil "~d day~:p ~d:~2,'0d:~2,'0d" days hours mins secs)) ((> hours 0) (format nil "~d:~2,'0d:~2,'0d" hours mins secs)) (t (format nil "~d:~2,'0d" mins secs))))) (defconstant *seconds-in-a-century* 3155760000 "[Cyc] HACK") (defconstant *seconds-in-an-odd-millenium* 31556908800) (defconstant *seconds-in-an-even-millenium* 31556995200)
13,830
Common Lisp
.lisp
254
46.716535
170
0.652373
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
05f22b45f1617fea338f90c2931e4dc32f4833a16cd0a5f956f6e7662f4cd2cb
6,689
[ -1 ]
6,690
kb-mapping-utilities.lisp
white-flame_clyc/larkc-cycl/kb-mapping-utilities.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO - local stopgap for iteration macro, for kb-mapping-utilities usage (defmacro kmu-do-index-iteration ((assertion-var type params inner-params &key done-place) &body body) (with-gensyms (iterator done token final-index-spec valid final-index-iterator inner-done inner-token inner-valid) `(when (,(symbolicate 'do- type '-index-key-validator) ,@params) (let ((,iterator (,(symbolicate 'new- type '-final-index-spec-iterator) ,@params)) (,done ,done-place) (,token nil)) (until ,done (let* ((,final-index-spec (iteration-next-without-values-macro-helper ,iterator ,token)) (,valid (not (eq ,token ,final-index-spec)))) (when ,valid (let ((,final-index-iterator (new-final-index-iterator ,final-index-spec ,@inner-params))) (unwind-protect (let ((,inner-done ,done-place) (,inner-token nil)) (until ,inner-done (let* ((,assertion-var (iteration-next-without-values-macro-helper ,final-index-iterator ,inner-token)) (,inner-valid (not (eq ,inner-token ,assertion-var)))) (when ,inner-valid ,@body) ;; TODO - all from done-place? (setf ,inner-done (or (not ,inner-valid) ,done-place))))) (destroy-final-index-iterator ,final-index-iterator)))) (setf ,done (or (not ,valid) ,done-place)))))))) (defun some-pred-value (term pred &optional (index-arg 1) (truth :true)) "[Cyc] Find the first gaf assertion such that: a) the assertion is in a relevant microtheory (relevance is established outside) b) if TRUTH is non-nil, the assertion has TRUTH as its truth value c) PRED is the predicate used. d) TERM is the term in the INDEX-ARG position. Return T if such an assertion exists, otherwise return NIL." (let ((answer nil)) (kmu-do-index-iteration (assertion gaf-arg (term index-arg pred) (:gaf truth nil) :done-place answer) ;; TODO - bookkeeping macro (when *mapping-assertion-bookkeeping-fn* (funcall *mapping-assertion-bookkeeping-fn* assertion)) ;; TODO - this iteration needs to become a non-local return instead of the stupid flag management. (setf answer t)) answer)) (defun some-pred-value-in-any-mt (term pred &optional (index-arg 1) (truth :true)) "[Cyc] Find the first gaf assertion such that: a) the assertion is allowed to be in any microtheory b) if TRUTH is non-nil, the assertion has TRUTH as its truth value c) PRED is the predicate used. d) TERM is the term in the INDEX-ARG position. Return T if such an assertion exists, otherwise return NIL." ;; TODO - mt macro (let ((*relevant-mt-function* #'relevant-mt-is-everything) (*mt* #$EverythingPSC)) (some-pred-value term pred index-arg truth))) (defun some-pred-value-in-relevant-mts (term pred &optional mt (index-arg 1) (truth :true)) "[Cyc] If MT is NIL, behaves like SOME-PRED-VALUE. Otherwise, behaves like SOME-PRED-VALUE-IN-MT." (possibly-in-mt (mt) (some-pred-value term pred index-arg truth))) (defun some-pred-value-if (term pred test &optional (index-arg 1) (truth :true)) "[Cyc] Find teh first gaf assertion such that: a) the assertion is in a relevant microtheory (relevance is established outside) b) if TRUTH is non-nil, the assertion has TRUTH as its truth value c) PRED is the predicate used. d) TERM is the term in the INDEX-ARG position. e) TEST returns non-nil when applied to assertion. Return T if such an assertion exists, otherwise return NIL." (let ((answer nil)) (kmu-do-index-iteration (assertion gaf-arg (term index-arg pred) (:gaf truth nil) :done-place answer) (when (funcall test assertion) ;; TODO bookeeping macro (when *mapping-assertion-bookkeeping-fn* (funcall *mapping-assertion-bookkeeping-fn* assertion))) (setf answer t)) answer)) (defun fpred-value-gaf (term pred &optional (index-argnum 1) (truth :true)) "[Cyc] Find the first gaf assertion that: a) the assertion si in a relevant microtheory (relevance is established outside) b) if TRUTH is non-nil, the assertion has TRUTH as its truth value c) PRED is the predicate used. d) TERM is the term in the INDEX-ARGNUM position. Return the gaf if it exists. Otherwise, return NIL." (let ((answer nil)) (kmu-do-index-iteration (assertion gaf-arg (term index-argnum pred) (:gaf truth nil) :done-place answer) ;; TODO - bookkeeping macro (when-let ((fn *mapping-assertion-bookkeeping-fn*)) (funcall fn assertion)) ;; TODO - use nonlocal return instead (setf answer assertion)) answer)) (defun fpred-value-gaf-in-relevant-mts (term pred &optional mt (index-argnum 1) (truth :true)) "[Cyc] If MT is NIL, behaves like FPRED-VALUE-GAF. Otherwise, looks in all genlMts of MT." (possibly-in-mt (mt) (fpred-value-gaf term pred index-argnum truth))) (defun fpred-value (term pred &optional (index-arg 1) (gather-arg 2) (truth :true)) "[Cyc] Find the first gaf assertion such that: a) the assertion is in a relevant microtheory (relevance is established outside) b) if TRUTH is non-nil, the assertion has TRUTH as its truth value c) PRED is the predicate used. d) TERM is the term in the INDEX-ARG position. Return the term in the GATHER-ARG position if such an assertion exists. Otherwise, return NIL." (when-let ((assertion (fpred-value-gaf term pred index-arg truth))) (gaf-arg assertion gather-arg))) (defun fpred-value-in-any-mt (term pred &optional (index-arg 1) (gather-arg 2) (truth :true)) "[Cyc] Find the first gaf assertion such that: a) the assertion is allowed to be in any microtheory b) if TRUTH is non-nil, the assertion has TRUTH as its truth value c) PRED is the predicate used. d) TERM is the term in the INDEX-ARG position. Return the term in the GATHER-ARG position if such an assertion exists. Otherwise, return NIL." ;; TODO - mt macro (let ((*relevant-mt-function* #'relevant-mt-is-everything) (*mt* #$EverythingPSC)) (fpred-value term pred index-arg gather-arg truth))) (defun fpred-value-in-relevant-mts (term pred &optional mt (index-arg 1) (gather-arg 2) (truth :true)) "[Cyc] If MT is NIL, behaves like FPRED-VALUE. Otherwise, looks in all genlMts of MT." (possibly-in-mt (mt) (fpred-value term pred index-arg gather-arg truth))) (defun pred-values (term pred &optional (index-arg 1) (gather-arg 2) (truth :true)) "[Cyc] Find all gaf assertions such that: a) the assertion is in a relevant microtheory (relevance is established outside) b) if TRUTH is non-nil, the assertion has TRUTH as its truth value c) PRED is the predicate used. d) TERM is the term in the INDEX-ARG position. Return a list of the terms in the GATHER-ARG position of all such assertions." (let ((values nil)) (kmu-do-index-iteration (assertion gaf-arg (term index-arg pred) (:gaf truth nil)) ;; TODO - bookkeeping macro (when-let ((fn *mapping-assertion-bookkeeping-fn*)) (funcall fn assertion)) (let ((value (gaf-arg assertion gather-arg))) (if *mapping-equality-test* (pushnew value values :test *mapping-equality-test*) (push value values)))) values)) (defun pred-values-in-relevant-mts (term pred &optional mt (index-arg 1) (gather-arg 2) (truth :true)) "[Cyc] If MT is NIL, behaves like PRED-VALUES. Otherwise, behaves like PRED-VALUES-IN-MT." (possibly-in-mt (mt) (pred-values term pred index-arg gather-arg truth))) (defun pred-u-v-holds (pred u v &optional (u-arg 1) (v-arg 2) (truth :true)) "[Cyc] Find the first gaf assertion such that: a) the assertion is in a relevant microtheory (relevance is established outside) b) if TRUTH is non-nil, the assertion has TRUTH as its truth value c) PRED is the predicate used. d) U is the term in the U-ARG position. e) V is the term in the V-ARG position. Return T if such an assertion exists, otherwise return NIL." (let ((answer nil)) (kmu-do-index-iteration (assertion gaf-arg (u u-arg pred) (:gaf truth nil) :done-place answer) (when (funcall *mapping-equality-test* (gaf-arg assertion v-arg) v) ;; TODO - bookkeeping macro (when-let ((fn *mapping-assertion-bookkeeping-fn*)) (funcall fn assertion)) ;; TODO - nonlocal return instead (setf answer t))) answer)) (defun pred-u-v-holds-in-any-mt (pred u v &optional (u-arg 1) (v-arg 2) (truth :true)) "[Cyc] Find the first gaf assertion such that: a) the assertion is allowed to be in any microtheory b) if TRUTH is non-nil, the assertion has TRUTH as its truth value c) PRED is the predicate used. d) U is the term in the U-ARG position. e) V is the term in the V-ARG position. Return T if such an assertion exists, otherwise return NIL." ;; TODO - mt macro (let ((*relevant-mt-function* #'relevant-mt-is-everything) (*mt* #$EverythingPSC)) (pred-u-v-holds pred u v u-arg v-arg truth))) (defun pred-arg-values (term pred arg &optional (term-psn 1) (arg-psn 2) (gather-psn 3) (truth :true)) (let ((answer nil)) (kmu-do-index-iteration (assertion gaf-arg (term term-psn pred) (:gaf truth nil)) (when (equalp arg (gaf-arg assertion arg-psn)) ;; TODO - bookkeeping macro (when-let ((fn *mapping-assertion-bookkeeping-fn*)) (funcall fn assertion)) (if-let ((test *mapping-equality-test*)) (pushnew (gaf-arg assertion gather-psn) answer :test test) (push (gaf-arg assertion gather-psn) answer)))) answer)) ;; TODO - referenced in kb-accessors (missing-function-implementation pred-arg-values-in-relevant-mts) (defun pred-value-tuples (term pred index-arg gather-args &optional (truth :true)) "[Cyc] Find all gaf assertions such that: a) the assertion is in a relevant microtheory (relevance is established outside) b) if TRUTH is non-nil, the assertion has TRUTH as its truth value c) PRED Is the predicate used. d) TERM is the term in the INDEX-ARG position. Return a list of tuples formed from the GATHER-ARGS position of all such assertions." (must (every #'integerp gather-args) "~s is not a valid arg-position-list" gather-args) (let ((answer nil)) (kmu-do-index-iteration (assertion gaf-arg (term index-arg pred) (:gaf truth nil)) (let ((tuple (mapcar (lambda (arg) (gaf-arg assertion arg)) gather-args))) ;; TODO - bookkeeping macro (when-let ((fn *mapping-assertion-bookkeeping-fn*)) (funcall fn assertion)) (if-let ((test *mapping-equality-test*)) (pushnew tuple answer :test test) (push tuple answer)))) answer)) (defun pred-value-tuples-in-any-mt (term pred index-arg gather-args &optional (truth :true)) "[Cyc] Find all gaf assertions such that: a) the assertion is allowed to be from any microtheory b) if TRUTH is non-nil, the assertion has TRUTH as its truth value c) PRED is the predicate used. d) TERM is the term in the INDEX-ARG position. Return a list of tuples formed from the GATHER-ARGS positions of all such assertions." ;; TODO - mt macro (let ((*relevant-mt-function* #'relevant-mt-is-everything) (*mt* #$EverythingPSC)) (pred-value-tuples term pred index-arg gather-args truth)))
13,237
Common Lisp
.lisp
242
47.702479
140
0.67675
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
5693679a1708351555e4693a11005ab8c1dae7a0397bf00569beb78d1160c6ba
6,690
[ -1 ]
6,691
assertions-interface.lisp
white-flame_clyc/larkc-cycl/assertions-interface.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO - all these hl-modify-remote? checks are kinda crappy. The dispatch mechanism should be more centralized, and maybe use a function naming protocol to automatically generate the tests as to which function to call. (define-hl-creator kb-create-assertion (cnf mt) "[Cyc] Create a new assertion with CNF in MT." nil (if (hl-modify-remote?) (missing-larkc 32157) (kb-create-assertion-local cnf mt))) (defun kb-create-assertion-local (cnf mt) (let ((internal-id (kb-create-assertion-kb-store cnf mt))) (find-assertion-by-id internal-id))) (define-hl-modifier kb-remove-assertion (assertion) "[Cyc] Remove ASSERTION from the KB." nil (kb-remove-assertion-internal assertion)) ;; TODO DESIGN - instead of all these remote checks everywhere, can't we manifest a simpler struct cached locally and use the normal local accessors on it? (defmacro define-kb-non-remote (name params &body (docstring &optional (internal-func (symbolicate name "-INTERNAL")))) "Helper for these annoyingly repetetive functions. Maps the function KB-<name> to <name>-INTERNAL with the same parameters, after a hl-access-remote? check." `(defun ,(symbolicate "KB-" name) ,params ,docstring (if (hl-access-remote?) ;; These were different per instantiation, but whatever. (missing-larkc 29511) (,internal-func ,@params)))) (define-kb-non-remote assertion-cnf (assertion) "[Cyc] Return the CNF for ASSERTION.") (define-kb-non-remote possibly-assertion-cnf (assertion) "[Cyc] Return the CNF for ASSERTION or NIL.") (define-kb-non-remote assertion-mt (assertion) "[Cyc] Return the MT for ASSERTION.") (define-kb-non-remote lookup-assertion (cnf mt) "[Cyc] Return the assertion with CNF and MT, if it exists. Return NIL otherwise." find-assertion-internal) ;; TODO - ? vs -P disconnect (define-kb-non-remote gaf-assertion? (assertion) "[Cyc} Return T iff ASSERTION is a ground atomic formula (gaf)." assertion-gaf-p) (define-kb-non-remote assertion-gaf-hl-formula (asssertion) "[Cyc] Returns the HL clause of ASSERTION if it's a gaf, otherwise returns NIL. Ignores the truth - i.e. returns <blah> instead of (#$not <blah>) for negated gafs." assertion-gaf-formula-internal) (define-kb-non-remote assertion-cons (assertion) "[Cyc] Returns a CNF or GAF HL formula.") (define-kb-non-remote assertion-direction (assertion) "[Cyc] Return the direction of ASSERTION (either :BACKWARD, :FORWARD, or :CODE).") (define-kb-non-remote assertion-truth (assertion) "[Cyc] Return the current truth of ASSERTION -- either :TRUE :FALSE or :UNKNOWN") (define-kb-non-remote assertion-strength (assertion) "[Cyc] Return the current argumentation strength of ASSERTION -- either :MONOTONIC, :DEFAULT, or :UNKNOWN.") (define-kb-non-remote assertion-variable-names (assertion) "[Cyc] Return the variable names for ASSERTION.") (define-kb-non-remote assertion-asserted-by (assertion) "[Cyc] Return the asserted-by bookkeeping info for ASSERTION." asserted-by-internal) (define-kb-non-remote assertion-asserted-when (assertion) "[Cyc] Return the asserted-when bookkeeping info for ASSERTION." asserted-when-internal) (define-kb-non-remote assertion-asserted-why (assertion) "[Cyc] Return the asserted-why bookkeeping info for ASSERTION." asserted-why-internal) (define-kb-non-remote assertion-asserted-second (assertion) "[Cyc] Return the asserted-second bookkeeping info for ASSERTION." asserted-second-internal) (defmacro define-kb-hl-modifier (name params &body (docstring &optional (new-func (symbolicate name "-INTERNAL")))) `(define-hl-modifier ,(symbolicate "KB-" name) ,params ,docstring nil ;; TODO - original code had old-* variables that were unused, which read the overwritten value. Skipping since I don't believe it has side effects. (,new-func ,@params))) (define-kb-hl-modifier set-assertion-direction (assertion new-direction) "[Cyc] Change direction of ASSERTION to NEW-DIRECTION.") (define-kb-hl-modifier set-assertion-truth (assertion new-truth) "[Cyc] Change the truth of ASSERTION to NEW-TRUTH." reset-assertion-truth) (define-kb-hl-modifier set-assertion-strength (assertion new-strength) "[Cyc] Change the strength of ASSERTION to NEW-STRENGTH." reset-assertion-strength) (define-kb-hl-modifier set-assertion-variable-names (assertion new-variable-names) "[Cyc] Change the variable names for ASSERTION to NEW-VARIABLE-NAMES." reset-assertion-variable-names) (define-kb-hl-modifier set-assertion-asserted-by (assertion assertor) "[Cyc] Set the asserted-by-bookkeeping info for ASSERTION to ASSERTOR." set-assertion-asserted-by) (define-kb-hl-modifier set-assertion-asserted-when (assertion universal-date) "[Cyc] Set the aserted-when bookkeeping info for ASSERTION to UNIVERSAL-DATE." set-assertion-asserted-when) (define-kb-hl-modifier set-assertion-asserted-why (assertion reason) "[Cyc] Set the asserted-why bookkeeping info for ASSERTION to REASON." set-assertion-asserted-why) (define-kb-hl-modifier set-assertion-asserted-second (assertion universal-second) "[Cyc] Set the asserted-second bookkeeping info for ASSERTION to UNIVERSAL-SECOND." set-assertion-asserted-second) ;; TODO - Not sure why these aren't with the batch above the hl-modifiers. Figure out the grouping from the java declareFunction list. (define-kb-non-remote assertion-arguments (assertion) "[Cyc] Return the arguments for ASSERTION.") (define-kb-non-remote assertion-dependents (assertion) "[Cyc] Return the dependents of ASSERTION.")
7,000
Common Lisp
.lisp
123
53.609756
221
0.765284
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
f24fc89eb9267a885fc522c8b100deaee1eecce384808c3434229a1c9b11bbed
6,691
[ -1 ]
6,692
tries.lisp
white-flame_clyc/larkc-cycl/tries.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO - test the entire trie interface heavily. Some things might have gotten lost in translation ;; TODO DESIGN - still don't know how a multi-trie should store its stuff, everything with it is missing-larkc ;; TODO - move to closure & LABELS (defparameter *trie-objects* nil "[Cyc] Special variable used when gathering objects from a TRIE") ;; DESIGN - these features are effectively missing-larkc (defparameter *trie-relevant-marks* :all "[Cyc] Special variable used while walking over relevant portions of a multi-trie.") (defparameter *trie-ancestor-tracking* nil "[Cyc] Special varaible used to control whether we bother to track the ancestor path in a trie.") (defstruct trie name top-node unique case-sensitive entry-test-func ;; TODO - nothing ever seems to set this multi multi-keys multi-key-func) (deflexical *trie-free-list* nil "[Cyc] Free list for TRIE objects") (deflexical *trie-free-lock* (bt:make-lock "TRIE resource lock") "[Cyc] Lock for TRIE object free list") (defun init-trie (trie) "[Cyc] Initialize a TRIE for use" ;; micro-optimized, because why not (setf (trie-name trie) (setf (trie-top-node trie) (setf (trie-unique trie) (setf (trie-case-sensitive trie) (setf (trie-entry-test-func trie) (setf (trie-multi trie) (setf (trie-multi-keys trie) (setf (trie-multi-key-func trie) nil)))))))) trie) (defun get-trie () "[Cyc] Get a TRIE from the free list, or make a new one if needed." (if (not *structure-resourcing-enabled*) (if *structure-resourcing-make-static* ;; TODO - enable structure resourcing (missing-larkc 12494) (init-trie (make-trie))) (bt:with-lock-held (*trie-free-lock*) ;; TODO - seems like DEFINE-RESOURCE stuff is excluded. Would be reasonable to reimplement, as there's no magic to free lists. (missing-larkc 12492)))) ;; DESIGN - trie nodes, they all seem to be cons cells ;; (key . subnodes) ;; ((key . ?) . subnodes) - where do these come from? multi-tries? ;; (:end . data) - data is a list for non-unique tries, or plain dotted cdr for unique ;; TODO - when is the CAR ever a list? only chars ever get placed as the key slot (declaim (inline trie-node-key)) (defun trie-node-key (node) (let ((car (car node))) (if (atom car) car (car car)))) (declaim (inline trie-node-data)) (defun trie-node-data (node) (cdr node)) (declaim (inline trie-node-subnodes)) (defun trie-node-subnodes (node) (cdr node)) (declaim (inline trie-leaf-node-p)) (defun trie-leaf-node-p (node) (eq (trie-node-key node) :end)) (declaim (inline new-trie-terminal-node)) (defun new-trie-terminal-node (object unique?) (if unique? (cons :end object) (list :end object))) (defun new-trie-nonterminal-node (char case-sensitive) (cons (if case-sensitive char (char-downcase char)) nil)) ;; TODO - since these are used in tight search loops, they really should have the case-sensitivity decision hoisted (defun trie-key-= (key1 key2 case-sensitive) (if case-sensitive (char= key1 key2))) (defun trie-key-< (key1 key2 case-sensitive) (if case-sensitive (char< key1 key2) (char-lessp key1 key2))) (defun add-trie-subnode (node subnode case-sensitive) (do* ((data (trie-node-subnodes node)) (subkey (trie-node-key subnode)) (back node next) (next data (cdr next)) (key (trie-node-key (car next)) (trie-node-key (car next)))) ((or (null next) (eq subkey :end) (and (not (eq key :end)) (not (trie-key-< key subkey case-sensitive)))) (rplacd back (cons subnode next))))) (defun create-trie (unique &optional name (case-sensitive t) (test #'eql)) "[Cyc] Return a new TRIE datastructure." (let ((trie (get-trie))) ;; Manually initialize a potentially reused trie (setf (trie-name trie) name) (setf (trie-top-node trie) (list* :top nil)) ;; TODO - weird construction of this list. must be from a macro? (setf (trie-unique trie) unique) (setf (trie-case-sensitive trie) case-sensitive) (setf (trie-entry-test-func trie) test) (setf (trie-multi trie) nil) trie)) (defun trie-insert (trie string &optional (object string) (start 0) (end (length string))) "[Cyc] Add index to OBJECT via STRING in TRIE. START and END delimit the relvant portion of STRING." (declare (trie trie) (string string) (fixnum start end)) (let ((unique (trie-unique trie)) (case-sensitive (trie-case-sensitive trie)) (test (trie-entry-test-func trie)) (node (trie-top-node trie))) (initialize-trie-ancestor-tracking node) ;; In each iteration, we look at trie nodes with respect to the next character (do (;; This is set in the body of the iteration, so reset it to NIL at the beginning (next-node nil nil) (index start (1+ index))) (;; This exit test means we hit the end of the string successfully (= index end) ;; Here we should be able to add the object as a leaf/terminal under the current node (let ((existing-terminal nil)) (csome (subnode (trie-node-subnodes node) (when (trie-leaf-node-p subnode) (setf existing-terminal subnode)))) (if existing-terminal (progn (trie-ancestor-tracking-descend existing-terminal) ;; Error if this is holding a different item but supposed to be unique (if unique (unless (funcall test object (trie-node-data existing-terminal)) (error "There is already an object ~s not ~s to ~s in the trie!" (trie-node-data existing-terminal) test object)) ;; No uniqueness requirement, pushnew the item along the rest ;; TODO - the original had a (missing-larkc 12506), then did the work anyway? (pushnew object (cdr existing-terminal) :test test))) ;; no existing-terminal, create a new one (let ((new-terminal (new-trie-terminal-node object unique))) (multi-trie-new-insert-mark trie object) (add-trie-subnode node new-terminal case-sensitive))) (finish-trie-ancestor-tracking) trie)) ;; This is the DO body (declare (fixnum index)) ;; Still more characters to go, traverse a step down the branches (let ((ch (char string index))) ;; Find the subnode whose key matches our character (csome (subnode (trie-node-subnodes node) (let ((subkey (trie-node-key subnode))) (when (and (characterp subkey) (trie-key-= subkey ch case-sensitive)) ;; This non-NIL return value will break out of the loop (setf next-node subnode))))) ;; Here, next-node is the node which matches our key. ;; Or NIL if we didn't find one and will make one (setf node (or next-node ;; TODO - when we're creating a new node in non-case-sensitive mode, why is it downcasing? ;; I would think it would just preserve case and case sensitivity is more a thing for the querier. (let ((new-node (new-trie-nonterminal-node ch case-sensitive))) (add-trie-subnode node new-node case-sensitive) (setf node new-node)))) (trie-ancestor-tracking-descend node))))) (defun trie-remove (trie string &optional (object string) (start 0) (end (length string))) "[Cyc] Remove index to OBJECT via STRING in TRIE. START and END delimit the relevant portion of STRING." (declare (trie trie) (string string) (fixnum start end)) (let ((unique (trie-unique trie)) (case-sensitive (trie-case-sensitive trie)) (test (trie-entry-test-func trie)) (node (trie-top-node trie)) (last-branching-node nil) (last-branch nil)) (initialize-trie-ancestor-tracking node) ;; See trie-insert for more structural comments (do ((next-node nil nil) (index start (1+ index))) ((= index end) ;; DO result value body (let ((end-node nil)) (csome (subnode (trie-node-subnodes node) (when (trie-leaf-node-p subnode) (trie-ancestor-tracking-descend subnode) (setf end-node subnode)))) ;; Bail on no leaf end-node (unless end-node (finish-trie-ancestor-tracking) (return trie)) (if unique ;; See if we're actually removing the intended object (when (funcall test object (trie-node-data end-node)) (cerror "Remove it anyway" "The object found in trie for ~s is ~s, not ~s" string (trie-node-data end-node))) ;; Not unique, deal with a list of entries (let* ((old-data (trie-node-data end-node)) (new-data (delete object old-data :test test))) (unless (eq old-data new-data) (rplacd end-node new-data)) (when new-data ;; Clean up and exit if there are more entries, leaving the node in place (multi-trie-remove-mark trie object) (finish-trie-ancestor-tracking) (return trie)))) ;; Remove the actual node, as it no longer contains objects (multi-trie-remove-mark trie object) (cond ((rest (trie-node-subnodes node)) (rplacd node (delete end-node (trie-node-subnodes node) :test #'eq))) ((and last-branch last-branching-node) ;; TODO - this sets last-branching-node just before returning, but it's just a local variable ;; note also that SBCL whines if you're discarding the return value of DELETE. (setf last-branching-node (delete last-branch last-branching-node :test #'eq))) (t (missing-larkc 12480))) (finish-trie-ancestor-tracking) (return trie))) ;; DO body (declare (fixnum index)) (let ((ch (char string index))) (csome (subnode (trie-node-subnodes node) (let ((subkey (trie-node-key subnode))) (when (and (characterp subkey) (trie-key-= ch subkey case-sensitive)) (setf next-node subnode))))) (if next-node (progn ;; As we traverse through found nodes, record the parent details for removal (when (cdr (trie-node-subnodes node)) (setf last-branching-node node) (setf last-branch next-node)) (setf node next-node)) ;; If we didn't find the entry, then silently bail (progn (finish-trie-ancestor-tracking) (return trie))) (trie-ancestor-tracking-descend node))))) (defun trie-exact (trie string &optional case-sensitive? (start 0) end) "[Cyc] Return the unique object indexed by STRING in TRIE. If CASe-SENSITIVE? is non-NIL, STRING is compared case-insensitively. START and END determine the relevant portion of STRING" (must (trie-unique trie) "TRIE ~s does not have unique entries" trie) (setf case-sensitive? (and case-sensitive? (trie-case-sensitive trie))) (let ((node (trie-top-node trie)) (end (or end (length string)))) (declare (trie trie) (string string) (fixnum start end)) (initialize-trie-ancestor-tracking node) (do ((next-node nil nil) (i start (1+ i))) ;; TODO - Original relied on java operator precedence here, not paren nesting. Verify behavior ((or (= i end) ;; Must have processed at least 1 character and not found the next (and (> i 0) (not node))) ;; Exit return forms (let ((answer nil)) (when node (csome (subnode (trie-node-subnodes node) (when (trie-leaf-node-p subnode) (trie-ancestor-tracking-descend subnode) (when (trie-relevant-ancestor-path? trie) (let ((object (trie-node-data subnode))) (when (trie-relevant-object trie object) (setf answer object)))))))) (finish-trie-ancestor-tracking) answer)) ;; DO iteration body (let ((char (char string i))) (csome (subnode (trie-node-subnodes node) (let ((subkey (trie-node-key subnode))) (when (and (characterp subkey) (trie-key-= char subkey case-sensitive?)) (setf next-node subnode))))) (setf node next-node) (trie-ancestor-tracking-descend node))))) (defun trie-prefix (trie string &optional case-sensitive? exact-length? (start 0) (end (length string))) "[Cyc] Return a list of all objects indexed in TRIE where STRING is a prefix of the index. If CASE-SENSITIVE? is non-NIL, STRING is compared case-insensitively. If EXACT-LENGTH? is non-NIL, then the index must match STRING exactly. START and END determine the relevant portion of STRING." (if (or case-sensitive? (not (trie-case-sensitive trie))) (missing-larkc 12549) (trie-prefix-recursive trie string exact-length? start end))) (defun trie-prefix-recursive (trie string exact-length? start end) "[Cyc] Internal to TRIE-PREFIX" (declare (trie trie) (string string) (fixnum start end)) (let ((answer nil) (*trie-objects* nil) (top-node (trie-top-node trie))) (initialize-trie-ancestor-tracking top-node) (when (trie-relevant-ancestor-path? trie) (dolist (subnode (trie-node-subnodes top-node)) (trie-ancestor-tracking-descend subnode) (when (trie-relevant-ancestor-path? trie) (trie-prefix-recursive-int trie subnode string start end exact-length? (trie-unique trie))) (trie-ancestor-tracking-ascend))) (setf answer *trie-objects*) (finish-trie-ancestor-tracking) (nreverse answer))) (defun trie-prefix-recursive-int (trie node string index stop exact-length? unique?) "[Cyc] Internal to TRIE-PREFIX-RECURSIVE" (declare (trie trie) (string string) (fixnum index stop)) (if (= index stop) (if exact-length? (when (trie-leaf-node-p node) (all-trie-objects-in-leaf-node trie node unique?)) (missing-larkc 12474)) (let ((key (trie-node-key node))) (when (and (characterp key) (char-equal (char string index) key)) (dolist (subnode (trie-node-subnodes node)) (trie-ancestor-tracking-descend subnode) (when (trie-relevant-ancestor-path? trie) (trie-prefix-recursive-int trie subnode string (1+ index) stop exact-length? unique?)) (trie-ancestor-tracking-ascend)))))) (defun all-trie-objects-in-leaf-node (trie node unique?) (let ((data (trie-node-data node))) (if unique? (when (trie-relevant-object trie data) (push data *trie-objects*)) (progn (setf data (missing-larkc 12550)) ;;(push data *trie-objects*) )))) ;; Unused in larkc code (defparameter *trie-maximum-search-size* 1000) (defun new-trie-iterator (trie &optional (forward? t)) (new-iterator (new-trie-iterator-state trie forward?) #'trie-iterator-done #'trie-iterator-next ;; TODO - this function doesn't exist. Are iterators effectively nonfunctional? 'trie-iterator-finalize)) (defun new-trie-iterator-state (trie forward?) (vector trie (trie-top-node trie) forward? (if (trie-unique trie) nil (create-queue)) (create-stack))) (defun trie-iterator-done (state) (and (trie-iterator-done-node (aref state 1)) ;; TODO - because of this, are trie-iterators never used? (missing-larkc 12528))) (defun trie-iterator-done-node (node) (not node)) (defun trie-iterator-next (state) (let ((trie (aref state 0)) (node (aref state 1)) (forward? (aref state 2)) (queue (aref state 3)) (stack (aref state 4))) (multiple-value-bind (next invalid? new-node) (if (queue-p queue) (missing-larkc 12530) (trie-iterator-next-unique trie node forward? stack)) (if invalid? (progn (setf (aref state 1) nil) (setf (aref state 3) nil) (clear-stack stack)) (setf (aref state 1) new-node)) (values next state invalid?)))) (defun trie-iterator-next-unique (trie node forward? stack) (let ((next nil) (invalid? nil)) (until (or next invalid?) (if (trie-leaf-node-p node) (let ((data (trie-node-data node))) (when (trie-relevant-object trie data) (setf next data))) (let ((subnodes (trie-node-subnodes node))) (if forward? (dolist (subnode (reverse subnodes)) (stack-push subnode stack)) (dolist (subnode subnodes) (stack-push subnode stack))))) (setf node (stack-pop stack)) (when (and (not next) (not node) (stack-empty-p stack)) (setf invalid? t))) (values next invalid? node))) ;; TODO - all of this stuff is missing-larkc'd when enabled, so I'm reducing it to nothing (defparameter *trie-ancestor-tracking-resource* nil) (defparameter *trie-ancestor-tracking-lock* (bt:make-lock "Ancestor tracking resource")) (defparameter *trie-ancestor-tracking-vector-size* 100) (defparameter *trie-ancestor-vector* nil) (defparameter *trie-ancestor-next* nil) (defun* initialize-trie-ancestor-tracking (top-node) (:ignore t)) (defun* finish-trie-ancestor-tracking () (:ignore t)) (defun* trie-ancestor-tracking-descend (node) (:ignore t)) (defun* trie-ancestor-tracking-ascend () (:ignore t)) (defun* trie-relevant-ancestor-path? (trie) (:ignore t) t) (defun* trie-relevant-object (trie object) (:ignore t) t) (defun* multi-trie-new-insert-mark (trie object) (:ignore t)) (defun* multi-trie-remove-mark (trie object) (:ignore t))
20,743
Common Lisp
.lisp
411
39.532847
290
0.606714
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
b7eb2f7051b0629a4aecd2ad50840d4525fca44ff08bce2f6e76df22a5267e52
6,692
[ -1 ]
6,693
kb-indexing.lisp
white-flame_clyc/larkc-cycl/kb-indexing.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO - massive macro extraction and inlining of utility functions required here! ;; TODO - desparately needs testing. (defun get-subindex (term keys) (let ((subindex (term-index term))) ;; TODO - this should early exit if subindex ever goes to NIL? (dolist (key keys) (when (and key subindex) (setf subindex (intermediate-index-lookup subindex key)))) subindex)) (defun term-add-indexing-leaf (term keys leaf) "[Cyc] Walks down the indexing for TERM by following successive elements of KEYS, and once it gets to the bottom, inserts LEAF." (mark-term-index-as-muted term) (if (simple-indexed-term-p term) (add-simple-index term leaf) (intermediate-index-insert (term-index term) keys leaf))) (defun term-rem-indexing-leaf (term keys leaf) "[Cyc] Walks down the indexing for TERM by following successive elements of KEYS, and once it gets to the bottom, deletes LEAF." (mark-term-index-as-muted term) (if (simple-indexed-term-p term) (rem-simple-index term leaf) (progn (intermediate-index-delete (term-index term) keys leaf) (possibly-toggle-term-index-mode term) ;; TODO - return value? leaf))) (defun* all-mt-subindex-keys-relevant-p () (:inline t) (any-or-all-mts-are-relevant?)) (defun relevant-mt-subindex-count-with-cutoff (mt-subindex cutoff) (cond ((all-mt-subindex-keys-relevant-p) (min cutoff (subindex-leaf-count mt-subindex))) ((only-specified-mt-is-relevant?) (let* ((mt (current-mt-relevance-mt)) (subindex (subindex-lookup mt-subindex mt))) (if subindex (min cutoff (subindex-leaf-count subindex)) 0))) (t (let ((count 0)) (do-intermediate-index (mt subindex mt-subindex) (if (number-has-reached-cutoff? count cutoff) (return-from do-intermediate-index) (when (relevant-mt? mt) (incf count (subindex-leaf-count subindex))))) (min cutoff count))))) (defun mark-term-index-as-muted (term) (cond ((constant-p term) (when-let ((id (constant-suid term))) (mark-constant-index-as-muted id))) ((nart-p term) (missing-larkc 30874)) ((kb-unrepresented-term-p term) (when-let ((id (unrepresented-term-suid term))) (mark-unrepresented-term-index-as-muted id))))) ;; GAF arg index (defun num-gaf-arg-index (term &optional argnum pred mt) "[Cyc] Return the number of gafs indexed off of TERM ARGNUM PRED MT." (let ((num 0)) ;; TODO - this pattern is clearly a macro that should be passing in NUM as a place directly (if (simple-indexed-term-p term) (let ((count 0)) (dolist (ass (do-simple-index-term-assertion-list term)) (when (matches-gaf-arg-index ass term argnum pred mt) (incf count))) (setf num count)) (setf num (if-let ((subindex (get-gaf-arg-subindex term argnum pred mt))) (subindex-leaf-count subindex) 0))) num)) (defun relevant-num-gaf-arg-index (term &optional argnum pred) "[Cyc] Return the assertion count at relevant mts under TERM ARGNUM PRED." (let ((num 0)) ;; TODO - might be the same as num-gaf-arg-index, but uses NUM as a place directly, instead of just returning straight from the COND (cond ((all-mt-subindex-keys-relevant-p) (setf num (num-gaf-arg-index term argnum pred))) ((simple-indexed-term-p term) (dolist (ass (do-simple-index-term-assertion-list term)) (when (and (matches-gaf-arg-index ass term argnum pred) (relevant-mt? (assertion-mt ass))) (incf num)))) (t (let ((good-key-count (number-of-non-null-args-in-order argnum pred))) ;; TODO - macro usage, subtracting constants (if (= good-key-count (- 3 1)) (when-let ((mt-subindex (get-gaf-arg-subindex term argnum pred))) (missing-larkc 12807)) (missing-larkc 4718))))) num)) (defun relevant-num-gaf-arg-index-with-cutoff (term cutoff &optional argnum pred) "[Cyc] Return the assertion count at relevant mts under TERM ARGNUM PRED. CUTOFF: non-negative-integer-p; a number beyond which to stop counting relevant assertions and just return CUTOFF." (let ((num 0)) ;; TODO - suspicion of macro like num-gaf-arg-index & relevant-num-gaf-arg-index (cond ((all-mt-subindex-keys-relevant-p) ;; TODO - optimize check to a single write, but probably reveals structure of macro (setf num (num-gaf-arg-index term argnum pred)) (when (number-has-reached-cutoff? num cutoff) (setf num cutoff))) ((simple-indexed-term-p term) (dolist (ass (do-simple-index-term-assertion-list term)) ;; TODO - should abort the dolist if this is true instead (unless (number-has-reached-cutoff? num cutoff) (when (and (matches-gaf-arg-index ass term argnum pred) (relevant-mt? (assertion-mt ass))) (incf num))))) (t (let ((good-key-count (number-of-non-null-args-in-order argnum pred))) ;; TODO - macro substracting constants (if (= good-key-count (- 3 1)) (when-let ((mt-subindex (get-gaf-arg-subindex term argnum pred))) (setf num (relevant-mt-subindex-count-with-cutoff mt-subindex cutoff))) (missing-larkc 4719))))) num)) (defun clear-key-gaf-arg-index-cached () (when-let ((cs *key-gaf-arg-index-cached-caching-state*)) (caching-state-clear cs))) ;; TODO HACK - this requires the last 2 args to be optional, but I don't think we can currently express that! (defun-memoized key-gaf-arg-index-cached (term #|&optional|#argnum pred) (:capacity 5000 :test eq :clear-when :hl-store-modified) "[Cyc] Return a list of the keys to the next index level below TERM ARGNUM PRED." (key-gaf-arg-index term argnum pred)) (defun key-gaf-arg-index (term &optional argnum pred) "[Cyc] Return a list of the keys to the next index level below TERM ARGNUM PRED. @note destructible" (let ((keys nil)) ;; TODO - definintely a macro, passing keys-accum to keys (if (simple-indexed-term-p term) (let ((keys-accum nil)) (dolist (ass (do-simple-index-term-assertion-list term)) (setf keys-accum (simple-key-gaf-arg-index ass keys-accum term argnum pred))) (setf keys keys-accum)) (let ((next-level-subindex (get-gaf-arg-subindex term argnum pred))) (setf keys (if (intermediate-index-p next-level-subindex) (intermediate-index-keys next-level-subindex) nil)))) keys)) (defun gaf-arg-index-key-validator (term &optional argnum predicate mt) "[Cyc] Return T iff TERM, ARGNUM, PREDICATE, and MT are valid keys for the :GAF-ARG INDEX." (and (indexed-term-p term) (or (not argnum) (positive-integer-p argnum)) (or (not predicate) (fort-p predicate)) (or (not mt) (hlmt-p mt)))) (defun get-gaf-arg-subindex (term &optional argnum pred mt) "[Cyc] Return the subindex at TERM ARGNUM PRED MT. Return NIL if none present." (get-subindex term (list :gaf-arg argnum pred mt))) (defun add-gaf-arg-index (term argnum pred mt assertion) (term-add-indexing-leaf term (list :gaf-arg argnum pred mt) assertion)) (defun rem-gaf-arg-index (term argnum pred mt assertion) (term-rem-indexing-leaf term (list :gaf-arg argnum pred mt) assertion)) ;; NART arg index (defun num-nart-arg-index (term &optional argnum func) "[Cyc] Return the number of #$termOfUnit gafs indexed off of TERM ARGNUM FUNC." (let ((num 0)) ;; TODO - macro, similar to num-gaf-arg-index but different inc tests. Doesn't refer to macro helpers, so not sure exactly what the input here is supposed to be, and which of these usages share a macro. (if (simple-indexed-term-p term) (let ((count 0)) (dolist (ass (do-simple-index-term-assertion-list term)) (when (matches-nart-arg-index ass term argnum func) (incf count))) (setf num count)) (setf num (if-let ((subindex (get-nart-arg-subindex term argnum func))) (subindex-leaf-count subindex) 0))) num)) (defun key-nart-arg-index (term &optional argnum func) "[Cyc] Return a list of the keys to the next index level below TERM ARGNUM FUNC." (let ((keys nil)) ;; TODO - macro (if (simple-indexed-term-p term) (let ((keys-accum nil)) (dolist (ass (do-simple-index-term-assertion-list term)) (setf keys-accum (simple-key-nart-arg-index ass keys-accum term argnum func))) (setf keys keys-accum)) (setf keys (let ((next-level-subindex (get-nart-arg-subindex term argnum func))) (if (intermediate-index-p next-level-subindex) (intermediate-index-keys next-level-subindex) nil)))) keys)) (defun get-nart-arg-subindex (term &optional argnum func) "[Cyc] Return the subindex at TERM ARGNUM FUNC MT. Return NIL if none present." (get-subindex term (list :nart-arg argnum func))) ;; Predicate extent index (defun num-predicate-extent-index (pred &optional mt) "[Cyc] Return the assertion count at PRED MT." (let ((num 0)) ;; TODO - macro, as above (if (simple-indexed-term-p pred) (let ((count 0)) (dolist (ass (do-simple-index-term-assertion-list pred)) (when (matches-predicate-extent-index ass pred mt) (incf count))) (setf num count)) (setf num (if-let ((subindex (get-predicate-extent-subindex pred mt))) (subindex-leaf-count subindex) 0))) num)) (defun relevant-num-predicate-extent-index-with-cutoff (pred cutoff) "[Cyc] Compute the assertion count at relevant mts under PRED. CUTOFF: non-negative-integer-p; a number beyond which to stop counting relevant assertions and just return CUTOFF." (let ((num 0)) ;; TODO - macro, as above (cond ((all-mt-subindex-keys-relevant-p) (setf num (num-predicate-extent-index pred)) (when (number-has-reached-cutoff? num cutoff) (setf num cutoff))) ((simple-indexed-term-p pred) (dolist (ass (do-simple-index-term-assertion-list pred)) (unless (number-has-reached-cutoff? num cutoff) (when (and (matches-predicate-extent-index ass pred) (relevant-mt? (assertion-mt ass))) (incf num))))) ;; TODO - degenerate constructs from macrogen (t (let ((good-key-count (number-of-non-null-args-in-order))) (if (= good-key-count (- 1 1)) (when-let ((mt-subindex (get-predicate-extent-subindex pred))) (setf num (relevant-mt-subindex-count-with-cutoff mt-subindex cutoff))) (missing-larkc 4722))))) num)) (defun key-predicate-extent-index (pred) "[Cyc] Return a list of the keys to the next predicate-extent index level below PRED." (let ((keys nil)) ;; TODO - macro as above (if (simple-indexed-term-p pred) (let ((keys-accum nil)) (dolist (ass (do-simple-index-term-assertion-list pred)) (declare (ignore ass)) (missing-larkc 30241)) (setf keys keys-accum)) (setf keys (let ((next-level-subindex (get-predicate-extent-subindex pred))) (if (intermediate-index-p next-level-subindex) (intermediate-index-keys next-level-subindex) nil)))) keys)) (defun* predicate-extent-top-level-key () (:inline t) :predicate-extent) (defun add-predicate-extent-index (pred mt assertion) (term-add-indexing-leaf pred (list (predicate-extent-top-level-key) mt) assertion)) (defun rem-predicate-extent-index (pred mt assertion) (term-rem-indexing-leaf pred (list (predicate-extent-top-level-key) mt) assertion)) (defun get-predicate-extent-subindex (pred &optional mt) "[Cyc] Return the subindex at PRED MT, or NIL if none present." (get-subindex pred (list (predicate-extent-top-level-key) mt))) ;; Predicate rule index (defun num-predicate-rule-index (pred &optional sense mt direction) "[Cyc] Return the raw assertion count at PRED SENSE MT DIRECTION." (let ((num 0)) ;; TODO - macro as above. Starting to simplify, though, because it's annoying (if (simple-indexed-term-p pred) (dolist (ass (do-simple-index-term-assertion-list pred)) (when (matches-predicate-rule-index ass pred sense mt direction) (incf num))) (when-let ((subindex (get-predicate-rule-subindex pred sense mt direction))) (setf num (subindex-leaf-count subindex)))) num)) (defun relevant-num-predicate-rule-index (pred &optional sense) "[Cyc] Return the raw assertion count at relevant mts under PRED SENSE." (let ((num 0)) ;; TODO - macro, simplified (cond ((all-mt-subindex-keys-relevant-p) (setf num (num-predicate-rule-index pred sense))) ((simple-indexed-term-p pred) (dolist (ass (do-simple-index-term-assertion-list pred)) (when (and (matches-predicate-rule-index ass pred sense) (relevant-mt? (assertion-mt ass))) (incf num)))) (t (let ((good-key-count (number-of-non-null-args-in-order sense))) (if (= good-key-count (- 2 1)) (when-let ((mt-subindex (get-predicate-rule-subindex pred sense))) (missing-larkc 12809)) (missing-larkc 4724))))) num)) (defun key-predicate-rule-index (pred &optional sense mt) "[Cyc] Return a list of the keys to the next index level below PRED SENSE MT." (let ((keys nil)) ;; TODO - macro (if (simple-indexed-term-p pred) (dolist (ass (do-simple-index-term-assertion-list pred)) (declare (ignore ass)) (missing-larkc 30242)) (let ((next-level-subindex (get-predicate-rule-subindex pred sense mt))) (when (intermediate-index-p next-level-subindex) (setf keys (intermediate-index-keys next-level-subindex))))) keys)) (defun get-predicate-rule-subindex (pred &optional sense mt direction) "[Cyc] Return NIL or subindex-p" (get-subindex pred (list :predicate-rule sense mt direction))) (defun add-predicate-rule-index (pred sense mt direction assertion) (term-add-indexing-leaf pred (list :predicate-rule sense mt direction) assertion)) (defun rem-predicate-rule-index (pred sense mt direction assertion) (term-rem-indexing-leaf pred (list :predicate-rule sense mt direction) assertion)) ;; Leftover pieces of others (defun key-decontextualized-ist-predicate-rule-index (pred &optional sense) "[Cyc] Return a list of the keys to the next index level below PRED SENSE." (let ((keys nil)) ;; TODO - macro (if (simple-indexed-term-p pred) (dolist (ass (do-simple-index-term-assertion-list pred)) (declare (ignore ass)) (missing-larkc 30235)) (let ((next-level-subindex (get-decontextualized-ist-predicate-rule-subindex pred sense))) (when (intermediate-index-p next-level-subindex) (setf keys (intermediate-index-keys next-level-subindex))))) keys)) (defun get-decontextualized-ist-predicate-rule-subindex (pred &optional sense direction) "[Cyc] Return NIL or subindex-p" (get-subindex pred (list :decontextualized-ist-predicate-rule sense direction))) (defun key-isa-rule-index (col &optional sense mt) "[Cyc] Return a list of the keys to the next index level below COL SENSE MT." (let ((keys nil)) ;; TODO - macro (if (simple-indexed-term-p col) (dolist (ass (do-simple-index-term-assertion-list col)) (declare (ignore ass)) (missing-larkc 30239)) (let ((next-level-subindex (get-isa-rule-subindex col sense mt))) (when (intermediate-index-p next-level-subindex) (setf keys (intermediate-index-keys next-level-subindex))))) keys)) (defun get-isa-rule-subindex (col &optional sense mt direction) "[Cyc] Return NIL or SUBINDEX-P" (get-subindex col (list :isa-rule sense mt direction))) (defun num-quoted-isa-rule-index (col &optional sense mt direction) "[Cyc] Return the raw assertion count at COL SENSE MT DIRECTION." (let ((num 0)) ;; TODO - macro (if (simple-indexed-term-p col) (dolist (ass (do-simple-index-term-assertion-list col)) (when (matches-quoted-isa-rule-index ass col sense mt direction) (incf num))) (missing-larkc 12641)) num)) (defun num-genls-rule-index (col &optional sense mt direction) "[Cyc] Return the raw assertion count at COL SENSE MT DIRECTION." (let ((num 0)) ;; TODO - macro (if (simple-indexed-term-p col) (dolist (ass (do-simple-index-term-assertion-list col)) (when (matches-genls-rule-index ass col sense mt direction) (incf num))) (when-let ((subindex (get-genls-rule-subindex col sense mt direction))) (setf num (subindex-leaf-count subindex)))) num)) (defun key-genls-rule-index (col &optional sense mt) "[Cyc] Return a list of the keys to the next index level below COL SENSE MT." (let ((keys nil)) ;; TODO - macro (if (simple-indexed-term-p col) (dolist (ass (do-simple-index-term-assertion-list col)) (declare (ignore ass)) (missing-larkc 30238)) (let ((next-level-subindex (get-genls-rule-subindex col sense mt))) (when (intermediate-index-p next-level-subindex) (setf keys (intermediate-index-keys next-level-subindex))))) keys)) (defun get-genls-rule-subindex (col &optional sense mt direction) "[Cyc] Returns NIL or SUBINDEX-P" (get-subindex col (list :genls-rule sense mt direction))) (defun add-genls-rule-index (col sense mt direction assertion) (term-add-indexing-leaf col (list :genls-rule sense mt direction) assertion)) (defun rem-genls-rule-index (col sense mt direction assertion) (term-rem-indexing-leaf col (list :genls-rule sense mt direction) assertion)) (defun key-genl-mt-rule-index (col &optional sense mt) "[Cyc] Return a list of the keys to the next index level below COL SENSE MT." (let ((keys nil)) ;; TODO - macro (if (simple-indexed-term-p col) (dolist (ass (do-simple-index-term-assertion-list col)) (declare (ignore ass)) (missing-larkc 30237)) (let ((next-level-subindex (get-genl-mt-rule-subindex col sense mt))) (when (intermediate-index-p next-level-subindex) (setf keys (intermediate-index-keys next-level-subindex))))) keys)) (defun get-genl-mt-rule-subindex (col &optional sense mt direction) "[Cyc] Returns NIL or SUBINDEX-P." (get-subindex col (list :genl-mt-rule sense mt direction))) (defun key-function-rule-index (func &optional mt) "[Cyc] Return a list of the keys to the inext index level below FUNC MT." (let ((keys nil)) ;; TODO - macro (if (simple-indexed-term-p func) (dolist (ass (do-simple-index-term-assertion-list func)) (declare (ignore ass)) (missing-larkc 30236)) (let ((next-level-subindex (get-function-rule-subindex func mt))) (when (intermediate-index-p next-level-subindex) (setf keys (intermediate-index-keys next-level-subindex))))) keys)) (defun* function-rule-top-level-key () (:inline t) :function-rule) (defun get-function-rule-subindex (func &optional mt direction) "[Cyc] Return NIL or SUBINDEX-P." (get-subindex func (list (function-rule-top-level-key) mt direction))) (defun relevant-num-pragma-rule-index (rule) "[Cyc] Return the raw assertion count at relevant mts under RULE." (let ((num 0)) ;; TODO - macro (cond ((all-mt-subindex-keys-relevant-p) (missing-larkc 12801)) ((simple-indexed-term-p rule) (dolist (ass (do-simple-index-term-assertion-list rule)) (when (and (matches-pragma-rule-index ass rule) (relevant-mt? (assertion-mt ass))) (incf num)))) (t (let ((good-key-count (number-of-non-null-args-in-order))) (if (= good-key-count (- 1 1)) (missing-larkc 12737) (missing-larkc 4745))))) num)) (defun add-mt-index (term assertion) (unless (broad-mt? term) (add-mt-index-internal term assertion)) ;; TODO - necessary return value? assertion) (defun rem-mt-index (term assertion) (unless (broad-mt? term) (rem-mt-index-internal term assertion)) ;; TODO - return value? assertion) (defun* mt-top-level-key () (:inline t) :ist) (defun add-mt-index-internal (term assertion) (term-add-indexing-leaf term (list (mt-top-level-key)) assertion)) (defun rem-mt-index-internal (term assertion) (term-rem-indexing-leaf term (list (mt-top-level-key)) assertion)) (defun broad-mt? (mt) (let ((monad (hlmt-monad-mt mt))) (when (fort-p monad) (broad-microtheory-p monad)))) (defun num-other-index (term) "[Cyc] Return the number of assertions at the other index for TERM." (let ((num 0)) ;; TODO - macro (if (simple-indexed-term-p term) (dolist (ass (do-simple-index-term-assertion-list term)) (when (matches-other-index ass term) (incf num))) (when-let ((subindex (get-other-subindex term))) (setf num (subindex-leaf-count subindex)))) num)) (defun* other-top-level-key () (:inline t) :other) (defun get-other-subindex (term) (term-complex-index-lookup term (other-top-level-key))) (defun add-other-index (term assertion) (term-add-indexing-leaf term (list (other-top-level-key)) assertion)) (defun rem-other-index (term assertion) (term-rem-indexing-leaf term (list (other-top-level-key)) assertion)) ;; Higher level interface? (defun num-index (term) "[Cyc] The total number of assertions indexed from TERM." (if (simple-indexed-term-p term) (simple-num-index term) (complex-index-leaf-count (term-index term)))) (defun add-assertion-indices (assertion &optional term) (noting-terms-to-toggle-indexing-mode (when (valid-assertion-handle? assertion) (if (kb-gaf-assertion? assertion) (add-gaf-indices assertion term) (add-rule-indices assertion term))))) (defun remove-assertion-indices (assertion &optional term) (noting-terms-to-toggle-indexing-mode (if (gaf-assertion? assertion) (remove-gaf-indices assertion term) (remove-rule-indices assertion term))) ;; TODO - return value? assertion) ;; TODO - this gathers lists and then calls tms-remove-assertion-list, instead of iterating without consing up that intermediate list. Look into it. (defun remove-term-indices (term) "[Cyc] Remove all assertions about TERM from the KB. Return the TERM." (let ((*relevant-mt-function* #'relevant-mt-is-everything) (*mt* #$EverythingPSC) ;;(*ignore-warns?* t) ;; TODO - need this? ) (tms-remove-assertion-list (gather-other-index term)) (when (hlmt-p term) (tms-remove-assertion-list (gather-mt-index term))) (macrolet ((prefix (&body clauses) `(progn ,@(mapcar (lambda (clause) `(tms-remove-assertion-list ,clause)) clauses)))) (prefix (gather-predicate-rule-index term :pos) (gather-predicate-rule-index term :neg) (gather-decontextualized-ist-predicate-rule-index term :pos) (gather-decontextualized-ist-predicate-rule-index term :neg) (gather-isa-rule-index term :neg) (gather-isa-rule-index term :pos) (gather-quoted-isa-rule-index term :neg) (gather-quoted-isa-rule-index term :pos) (gather-genls-rule-index term :neg) (gather-genls-rule-index term :pos) (gather-genl-mt-rule-index term :neg) (gather-genl-mt-rule-index term :pos) (gather-function-rule-index term) (gather-exception-rule-index term) (gather-pragma-rule-index term))) (when (fort-p term) (tms-remove-assertion-list (gather-predicate-extent-index term)) (tms-remove-assertion-list (gather-function-extent-index term))) (dolist (argnum (sort (key-nart-arg-index term) #'>)) (declare (ignore argnum)) (missing-larkc 9445)) (dolist (argnum (sort (key-gaf-arg-index term) #'>)) (when (/= 1 argnum) (tms-remove-assertion-list (gather-gaf-arg-index term argnum nil nil nil)))) (let ((isa-assertions (gather-gaf-arg-index term 1 #$isa nil nil)) (genls-assertions (gather-gaf-arg-index term 1 #$genls nil nil)) (tou-assertions (gather-gaf-arg-index term 1 #$termOfUnit nil nil)) (arg1-assertions (gather-gaf-arg-index term 1 nil nil nil))) (dolist (assertion arg1-assertions) (when (and (valid-assertion assertion) (not (or (member? assertion isa-assertions) (member assertion genls-assertions) (member assertion tou-assertions)))) (tms-remove-assertion assertion))) (tms-remove-assertion-list genls-assertions) (tms-remove-assertion-list isa-assertions) (tms-remove-assertion-list tou-assertions)) (let ((remaining-assertions (all-term-assertions term t))) (when remaining-assertions (warn "Indexing problem while removing ~s" term)) (tms-remove-assertion-list remaining-assertions))) term) (defun determine-formula-indices (formula) "[Cyc] Return 0: alist-p, a list of (argnum . term) pairs Return 1: listp, a list of terms not indexed by any other argnum." (setf formula (ignore-sequence-vars formula)) (let ((others nil) (pairs nil) (terms (formula-terms formula :ignore))) (dolistn (argnum arg terms) (if (valid-indexed-term? arg) (push (cons argnum arg) pairs) (setf others (nunion (tree-gather arg #'valid-fully-indexed-term-p) others)))) (when others (setf others (loop for other in (fast-delete-duplicates others #'equal) unless (member? other pairs #'equal #'cdr) collect other))) (values (nreverse pairs) others))) (defun determine-gaf-indices (formula mt) "[Cyc] Return 0: alist-p, a list of (argnum . term) pairs Return 1: listp, a listof terms not indexed by any other argnum" (multiple-value-bind (argnum-pairs others) (determine-formula-indices formula) (unless (fort-p mt) (setf others (nunion (formula-gather mt #'fully-indexed-hlmt-term-p) others))) (values argnum-pairs others))) (defun add-gaf-indices (assertion &optional term) (let ((literal (gaf-formula assertion)) (mt (assertion-mt assertion))) (multiple-value-bind (alist others) (determine-gaf-indices literal mt) (let ((pred (cdr (assoc 0 alist)))) (unless (and (hlmt-p mt) (fort-p pred)) (cerror "So don't!" "Don't know how to index ~s" assertion) (return-from add-gaf-indices nil)) (when (or (not term) (hlmt-equal term mt)) (add-mt-index mt assertion)) (when (or (not term) (eq term pred)) (add-predicate-extent-index pred mt assertion)) (do-alist (argnum arg alist) (when (and (plusp argnum) arg (or (not term) (equal term arg))) (add-gaf-arg-index arg argnum pred mt assertion))) (cond ((eq pred #$termOfUnit) (missing-larkc 12694)) (t (dolist (fort others) (when (and (fully-indexed-term-p fort) (or (not term) (equal term fort))) (add-other-index fort assertion))))))))) (defun remove-gaf-indices (assertion &optional term) (let ((literal (gaf-formula assertion)) (mt (assertion-mt assertion))) (multiple-value-bind (alist others) (determine-gaf-indices literal mt) (let ((pred (cdr (assoc 0 alist)))) (unless (and (hlmt-p mt) (fort-p pred)) (cerror "So don't!" "Don't know how to index ~s" assertion) (return-from remove-gaf-indices nil)) (when (or (not term) (hlmt-equal term mt)) (rem-mt-index mt assertion)) (when (or (not term) (eq term pred)) (rem-predicate-extent-index pred mt assertion)) (do-alist (argnum arg alist) (when (and (plusp argnum) arg (or (not term) (equal term arg))) (rem-gaf-arg-index arg argnum pred mt assertion))) (if (eq pred #$termOfUnit) (missing-larkc 12831) (dolist (fort others) (when (and (fully-indexed-term-p fort) (or (not term) (equal term fort))) (rem-other-index fort assertion)))))))) (defun determine-rule-indices-int (asents sense) "[Cyc] Return 0: A list of pairs. The first element of each pair is the type of indexing (:pred, :ist-pred, :func, :isa, :genls, :genl-mt, :exception, or :pragma) and the second element of each pair is the term to be indexed with that type of indexing. Return 1: A list of terms to be potentically indexed via 'other' indexing." (let ((pairs nil) (other nil)) (macrolet ((do-push (test true-prefix &key (accessor '(sentence-arg2 asent)) no-else) `(let ((term ,accessor)) (pushnew (if (,test term) (list ,true-prefix term) ,(when no-else `(list :pred pred))) pairs :test #'equal)))) (dolist (asent asents) (let ((pred (atomic-sentence-predicate asent))) (cond ((eq pred #$isa) (do-push fort-p :isa)) ((eq pred #$quotedIsa) (do-push fort-p :quoted-isa)) ((eq pred #$genls) (do-push fort-p :genls)) ((eq pred #$genlMt) (do-push hlmt-p :genl-mt)) ((and (eq sense :neg) (eq pred #$termOfUnit)) (let ((naut (sentence-arg2 asent))) (if (possibly-naut-p naut) (do-push fort-p :func :accessor (nat-functor naut)) (pushnew (list :pred pred) pairs :test #'equal)))) ((and (eq sense :pos) (eq pred #$abnormal)) (do-push assertion-p :exception)) ((and (eq sense :pos) (eq pred #$meetsPragmaticRequirement)) (do-push assertion-p :pragma)) ((eq pred #$ist) (do-push fort-p :ist-pred :no-else t :accessor (literal-predicate (sentence-arg2 asent)))) ((fort-p pred) (pushnew (list :pred pred) pairs :test #'equal)))) (setf other (nunion other (tree-gather (sentence-args asent) #'fully-indexed-term-p)))) (values pairs other)))) (defun determine-rule-indices (cnf) "[Cyc] Return 0: A list of pairs. The first element of each pair is the type of indexing (:pred, :func, :isa, :genls, :genl-mt, :exception, or :pragma), and the second element of each pair is the term to be indexed with that type of indexing. All these pairs occurred as neg-lits in CNF. Return 1: A list of pairs that occurred as pos-lits in CNF. Return 2: A list of terms to be indexed via 'other' indexing." (multiple-value-bind (neg-pairs neg-other) (determine-rule-indices-int (neg-lits cnf) :neg) (multiple-value-bind (pos-pairs pos-other) (determine-rule-indices-int (pos-lits cnf) :pos) (let* ((neg-terms (mapcar #'second neg-pairs)) (pos-terms (mapcar #'second pos-pairs)) (other (nset-difference (nset-difference (fast-delete-duplicates (nunion neg-other pos-other)) neg-terms) pos-terms))) (values neg-pairs pos-pairs other))))) ;; TODO - all this stuff might be better handled via defmethod? (defun add-rule-indices (assertion &optional term) (let ((cnf (assertion-cnf assertion)) (mt (assertion-mt assertion)) (dir (assertion-direction assertion))) (multiple-value-bind (neg-pairs pos-pairs other) (determine-rule-indices cnf) (dolist (neg-pair neg-pairs) (destructuring-bind (neg-indexing-type neg-term) neg-pair (when (and (fully-indexed-term-p neg-term) (or (not term) (equal neg-term term))) (case neg-indexing-type ;; Shuffled the non-missing-larkc ones to the top (:pred (add-predicate-rule-index term :neg mt dir assertion)) (:genls (add-genls-rule-index neg-term :neg mt dir assertion)) (:ist-pred (missing-larkc 12690)) (:func (missing-larkc 12695)) (:isa (missing-larkc 12698)) (:quoted-isa (missing-larkc 12701)) (:genl-mt (missing-larkc 12696)) (:pragma (cerror "So don't!" "Can't index a pragmatic requirement as a neg-lit ~s" assertion)) (:exception (cerror "So don't!" "Can't index an exception as a neg-lit ~s" assertion)) (otherwise (cerror "So don't!" "Don't know how to handle indexing type ~s" neg-indexing-type)))))) (dolist (pos-pair pos-pairs) (destructuring-bind (pos-indexing-type pos-term) pos-pair (when (and (fully-indexed-term-p pos-term) (or (not term) (equal pos-term term))) (case pos-indexing-type ;; Shuffled the non-missing-larkc ones to the top (:pred (add-predicate-rule-index term :pos mt dir assertion)) (:genls (add-genls-rule-index pos-term :pos mt dir assertion)) (:ist-pred (missing-larkc 12691)) (:isa (missing-larkc 12699)) (:quoted-isa (missing-larkc 12702)) (:genl-mt (missing-larkc 12697)) (:pragma (missing-larkc 12700)) (:exception (missing-larkc 12692)) (:func (cerror "So don't!" "Can't index a function rule as a pos-lit ~s" assertion)) (otherwise (cerror "So don't!" "Don't know how to handle indexing type ~s" pos-indexing-type)))))) (dolist (other-term other) (when (and (fully-indexed-term-p other-term) (or (not term) (equal other-term term))) (add-other-index other-term assertion))) (when (and (hlmt-p mt) (or (not term) (hlmt-equal mt term))) (add-mt-index mt assertion))) (unless term (add-unbound-rule-indices assertion)))) (defun remove-rule-indices (assertion &optional term) (let ((cnf (assertion-cnf assertion)) (mt (assertion-mt assertion)) (dir (assertion-direction assertion))) (multiple-value-bind (neg-pairs pos-pairs other) (determine-rule-indices cnf) (dolist (neg-pair neg-pairs) (destructuring-bind (neg-indexing-type neg-term) neg-pair (when (and (fully-indexed-term-p neg-term) (or (not term) (equal neg-term term))) (case neg-indexing-type ;; Shuffled the non-missing-larkc ones to the top (:pred (rem-predicate-rule-index neg-term :neg mt dir assertion)) (:genls (rem-genls-rule-index neg-term :neg mt dir assertion)) (:ist-pred (missing-larkc 12827)) (:isa (missing-larkc 12835)) (:quoted-isa (missing-larkc 12838)) (:genl-mt (missing-larkc 12833)) (:func (missing-larkc 12832)) (:pragma (cerror "So don't!" "Can't remove the index of a pragmatic requirement as a neg-lit ~s" assertion)) (:exception (cerror "So don't!" "Can't remove the index of an exception as a neg-lit ~s" assertion)) (otherwise (cerror "So don't!" "Don't know how to handle indexing type ~s" neg-indexing-type)))))) (dolist (pos-pair pos-pairs) (destructuring-bind (pos-indexing-type pos-term) pos-pair (when (and (fully-indexed-term-p pos-term) (or (not term) (equal pos-term term))) (case pos-indexing-type (:pred (rem-predicate-rule-index pos-term :pos mt dir assertion)) (:genls (rem-genls-rule-index pos-term :pos mt dir assertion)) (:ist-pred (missing-larkc 12828)) (:isa (missing-larkc 12836)) (:quoted-isa (missing-larkc 12839)) (:genl-mt (missing-larkc 12834)) (:exception (missing-larkc 12829)) (:pragma (missing-larkc 12837)) (:func (cerror "So don't!" "Can't remove the index of a function rule as a pos-lit ~s" assertion)) (otherwise (cerror "So don't!" "Don't know how to handle indexing type ~s" pos-indexing-type)))))) (dolist (other-term other) (when (and (fully-indexed-term-p other-term) (or (not term) (equal other-term term))) (rem-other-index other-term assertion))) (when (and (hlmt-p mt) (or (not term) (hlmt-equal mt term))) (rem-mt-index mt assertion))) (unless term (rem-unbound-rule-indices assertion)))) (defun dependent-narts (fort) "[Cyc] Return a list of all current NARTs which are functions of FORT< or which have FORT as their functor." (let ((answer nil)) (do-nart-arg-index (assertion fort) (push (gaf-arg1 assertion) answer)) (do-function-extent-index (assertion fort) (push (gaf-arg1 assertion) answer)) (do-other-index (assertion fort) (when (and (tou-assertion? assertion) (expression-find fort (gaf-arg2 assertion) t)) (push (gaf-arg1 assertion) answer))) (fast-delete-duplicates answer))) (defun decent-rule-index (rule-cnf) "[Cyc] Return 0: The type of indexing: :pred-neg, :pred-pos, :ist-pred-neg, :ist-pred-pos, :func, :isa-neg, :isa-pos, :genls-neg, :genls-pos, :genl-mt-neg, :genl-mt-pos, :exception, :pragma, or :other. Return 1: The term to be indexed with that type of indexing." (let ((best-type nil) (best-term nil) (best-total most-positive-fixnum)) (multiple-value-bind (neg-pairs pos-pairs other) (determine-rule-indices rule-cnf) (dolist (pos-pair pos-pairs) ;; TODO - really, the above instances should do this as well. Grabbing first/second is faster than destructuring-bind (let ((pos-indexing-type (first pos-pair)) (pos-term (second pos-pair))) (when (indexed-term-p pos-term) (let ((total (case pos-indexing-type ;; Reordered (:pred (num-predicate-rule-index pos-term :pos)) (:quoted-isa (num-quoted-isa-rule-index pos-term :pos)) (:genls (num-genls-rule-index pos-term :pos)) (:ist-pred (missing-larkc 12773)) (:isa (missing-larkc 12795)) (:genl-mt (missing-larkc 12791)) (:pragma (missing-larkc 12803)) (:exception (missing-larkc 12779)) (otherwise (cerror "So don't!" "Don't know how to handle indexing type ~s" pos-indexing-type) most-positive-fixnum)))) (when (< total best-total) (setf best-total total best-term pos-term best-type (case pos-indexing-type (:pred :pred-pos) (:ist-pred :ist-pred-pos) (:isa :isa-pos) (:quoted-isa :quoted-isa-pos) (:genls :genls-pos) (:genl-mt :genl-mt-pos) (otherwise pos-indexing-type)))))))) (dolist (neg-pair neg-pairs) (let ((neg-indexing-type (first neg-pair)) (neg-term (second neg-pair))) (when (indexed-term-p neg-term) (let ((total (case neg-indexing-type ;; Reordered (:pred (num-predicate-rule-index neg-term :neg)) (:quoted-isa (num-quoted-isa-rule-index neg-term :neg)) (:genls (num-genls-rule-index neg-term :neg)) (:ist-pred (missing-larkc 12774)) (:isa (missing-larkc 12796)) (:genl-mt (missing-larkc 12792)) (:func (missing-larkc 12787)) (otherwise (cerror "So don't!" "Don't know how to handle indexing type ~s" neg-indexing-type) most-positive-fixnum)))) (when (< total best-total) (setf best-total total) (setf best-term neg-term) (setf best-type (case neg-indexing-type (:pred :pred-neg) (:ist-pred :ist-pred-neg) (:isa :isa-neg) (:quoted-isa :quoted-isa-neg) (:genls :genls-neg) (:genl-mt :genl-mt-neg) (otherwise neg-indexing-type)))))))) (dolist (other-term other) (when (indexed-term-p other-term) (let ((total (num-other-index other-term))) (when (< total best-total) (setf best-total total best-term other-term best-type :other)))))) (values best-type best-term))) (defun* lookup-index-get-property (lookup-index indicator &optional default) (:inline t) (getf lookup-index indicator default)) (defun* lookup-index-set-property (lookup-index indicator value) (:inline t) "[Cyc] Usage: (csetq li (lookup-index-set-property li :foo 212)) ." (putf lookup-index indicator value)) (defun* lookup-index-get-type (lookup-index) (:inline t) (lookup-index-get-property lookup-index :index-type)) (defun lookup-index-gaf-arg-values (lookup-index) "[Cyc] Assumes LOOKUP-INDEX is of type :gaf-arg. Return 0: term Return 1: argnum Return 2: predicate" (values (lookup-index-get-property lookup-index :term) (lookup-index-get-property lookup-index :argnum) (lookup-index-get-property lookup-index :predicate))) ;; TODO - probably a macro to expand these lookup-index-set-property chains, but there's only 2 uses so far, so whatever. (defun lookup-index-for-predicate-extent (predicate) (let* ((lookup-index (lookup-index-set-property nil :index-type :predicate-extent)) (lookup-index (lookup-index-set-property lookup-index :predicate predicate))) lookup-index)) (defun lookup-index-for-gaf-arg (best-term best-index-argnum index-pred) (let* ((lookup-index (lookup-index-set-property nil :index-type :gaf-arg)) (lookup-index (lookup-index-set-property lookup-index :term best-term)) (lookup-index (lookup-index-set-property lookup-index :argnum best-index-argnum)) (lookup-index (lookup-index-set-property lookup-index :predicate index-pred))) lookup-index)) (defun lookup-methods-include? (index-type methods) "[Cyc] Return T iff INDEX-TYPE is allowable, according to METHODS." (or (not methods) ;; TODO - probably :test #'eq since they're all keywords? (member index-type methods))) (defun best-gaf-lookup-index (asent truth &optional methods) "[Cyc] Returns a property list containing the property :index-type, which identifies which type of index is best for lookup of ASENT with TRUTH. The remaining elements on the plist are additional information pertaining to that type of index. A nil return value means that no possible index was found using the allowable methods. METHODS: The allowable methods (index-types) that the function can return. If NIL, all methods are allowed." (cond ((or (lookup-methods-include? :predicate-extent methods) (lookup-methods-include? :gaf-arg methods)) (best-gaf-lookup-index-try-all-allowed asent truth methods)) ((missing-larkc 12767)) ;;(missing-larkc 12754) )) (defun num-best-gaf-lookup-index (asent truth &optional methods) (cond ((or (lookup-methods-include? :predicate-extent methods) (lookup-methods-include? :gaf-arg methods)) (num-best-gaf-lookup-index-try-all-allowed asent truth methods)) ((missing-larkc 12768)) ;;(missing-larkc 5114) ;;(t 0) )) (defun best-gaf-lookup-index-try-all-allowed (asent truth methods) (multiple-value-bind (best-fort best-index-argnum index-pred best-count) (best-gaf-lookup-index-wrt-methods asent truth methods) (cond ((and (lookup-methods-include? :overlap methods) (lookup-should-use-index-overlap? asent best-count)) (missing-larkc 12755)) ((and (not best-fort) (not best-index-argnum) (not index-pred)) nil) ((and (lookup-methods-include? :predicate-extent methods) (zerop best-index-argnum)) (lookup-index-for-predicate-extent best-fort)) ((and (lookup-methods-include? :gaf-arg methods) (positive-integer-p best-index-argnum)) (lookup-index-for-gaf-arg best-fort best-index-argnum index-pred)) (t nil)))) (defun num-best-gaf-lookup-index-try-all-allowed (asent truth methods) (multiple-value-bind (best-fort best-index-argnum index-pred best-count) (best-gaf-lookup-index-wrt-methods asent truth methods) (declare (ignore best-fort best-index-argnum index-pred)) (cond ((and (lookup-methods-include? :overlap methods) (lookup-should-use-index-overlap? asent best-count)) (missing-larkc 5115)) (t best-count)))) (defun best-gaf-lookup-index-wrt-methods (asent truth methods) (let ((tweaked-asent (if (and (lookup-methods-include? :predicate-extent methods) (not (lookup-methods-include? :gaf-arg methods))) (make-formula (atomic-sentence-predicate asent) nil) asent))) (multiple-value-bind (best-term best-index-argnum index-pred best-count) (best-gaf-lookup-index-int tweaked-asent truth) (if (and (not (and (lookup-methods-include? :gaf-arg methods) (positive-integer-p best-index-argnum))) (not (and (lookup-methods-include? :predicate-extend methods) (zerop best-index-argnum))) (and (lookup-methods-include? :gaf-arg methods) (zerop best-index-argnum))) (values nil nil nil 0) (values best-term best-index-argnum index-pred best-count))))) (defun best-gaf-lookup-index-int (asent truth) "[Cyc] Determine the best gaf lookup index of ASENT with truth value TRUTH. First look for mt-insensitive counts, then, if not all mts are relevant, try to do better by finding a smaller mt-sensitive count, but use the min of the mt-insensitive counts as a cutoff so it won't waste time computing the relevance of things that aren't going to be any better." (declare (ignore truth)) (multiple-value-bind (argnum-pairs others) (determine-formula-indices asent) (declare (ignore others)) (let ((best-count nil) (best-fort nil) (best-argnum nil) (pred (cdr (assoc 0 argnum-pairs)))) (if (fort-p pred) (setf best-fort pred best-count (num-predicate-extent-index pred) best-argnum 0) (setf pred nil)) (do-alist (argnum arg argnum-pairs) (when (plusp argnum) (let ((num nil)) (when (indexed-term-p arg) (setf num (if pred (num-gaf-arg-index arg argnum pred) (num-gaf-arg-index arg argnum))) (when (or (not best-fort) (< num best-count)) (setf best-count num) (setf best-fort arg) (setf best-argnum argnum)))))) (unless (any-or-all-mts-are-relevant?) (when pred (do-alist (argnum arg argnum-pairs) (when (and (plusp argnum) (indexed-term-p arg)) (let ((arg-count (relevant-num-gaf-arg-index-with-cutoff arg best-count argnum pred))) (when (< arg-count best-count) (setf best-count arg-count) (setf best-fort arg) (setf best-argnum argnum)))))) (when (fort-p pred) (let ((pred-count (relevant-num-predicate-extent-index-with-cutoff pred best-count))) (when (< pred-count best-count) (setf best-fort pred best-count pred-count best-argnum 0))))) (values best-fort best-argnum pred best-count)))) ;; TODO - probably unused in clyc (deflexical *reindex-all-assertions-full-gc-threshold-constant-count* 10000 "[Cyc] When there are more than 10k constant, call (gc-full) to remove old indexes from static space.") (defparameter *warn-on-assertion-reindexing-errors?* nil "[Cyc] Controls whether the reindexing process complains about the indexing errors or just discards them silently.") (defun* find-assertion (cnf mt) (:inline t) "[Cyc] Find the assertion in MT with CNF. Return NIL if not present." (kb-lookup-assertion cnf mt)) (defun find-assertion-internal (cnf mt) ;; TODO - MT macro? find all occurrences where *mt* is bound and compare to the java macro names (let ((*relevant-mt-function* #'relevant-mt-is-eq) (*mt* mt)) (find-cnf cnf))) (defun find-assertion-any-mt (cnf) "[Cyc] Find any assertion in any mt with CNF. Return NIL if none are present." ;; TODO - mt macro (let ((*relevant-mt-function* #'relevant-mt-is-everything) (*mt* #$EverythingPSC)) (find-cnf cnf))) (defun find-gaf (gaf-formula mt) "[Cyc] Find the assertion in MT with GAF-FORMULA as its formula. Return NIL if not present." ;; TODO - mt macro (let ((*relevant-mt-function* #'relevant-mt-is-eq) (*mt* mt)) (find-gaf-formula gaf-formula))) (defun find-gaf-any-mt (gaf-formula) "[Cyc] Find any assertion in any mt with GAF-FORMULA as its formula. Return NIL if not present." ;; TODO - mt macro (let ((*relevant-mt-function* #'relevant-mt-is-everything) (*mt* #$EverythingPSC)) (find-gaf-formula gaf-formula))) (defun* find-gaf-in-relevant-mt (gaf-formula) (:inline t) "[Cyc] Find any assertion in any currently relevant with GAF-FORMULA as its formula. Return NIL if not present." ;; TODO - supposed to be "in any currently relevant MT"? (find-gaf-formula gaf-formula)) (defun find-cnf (cnf) "[Cyc] Return an assertion which has CNF as its cnf or NIL if none present. Relevant mts are assumed scoped from the outside." (if (gaf-cnf? cnf) (find-gaf-cnf cnf) (find-rule-cnf cnf))) (defun find-gaf-cnf (cnf) "[Cyc] Use the gaf indexing to find any assertion whose hl-cnf is CNF." (find-gaf-formula (cnf-to-gaf-formula cnf))) (defun find-rule-cnf (cnf) "[Cyc] Use the rule indexing to find any assertion whose hl-cnf is CNF." (multiple-value-bind (index term) (decent-rule-index cnf) (find-rule-cnf-via-index-int cnf index term))) (defun find-rule-cnf-via-index-int (cnf index term) (when (indexed-term-p term) ;; TODO - must be a better way than this weird catch stuff & dynamic bindings (let ((*mapping-target* cnf) (*mapping-answer* nil)) ;; TODO - catch_var value from java is ignored? (catch :mapping-done (case index (:other (map-other-index #'find-cnf-internal term nil nil)) (:pred-neg (map-predicate-rule-index #'find-cnf-internal term :neg)) (:pred-pos (map-predicate-rule-index #'find-cnf-internal term :pos)) (:ist-pred-neg (missing-larkc 9446)) (:ist-pred-pos (missing-larkc 9447)) (:isa-neg (missing-larkc 9463)) (:isa-pos (missing-larkc 9464)) (:genls-neg (missing-larkc 9460)) (:genls-pos (missing-larkc 9461)) (:genl-mt-neg (missing-larkc 9458)) (:genl-mt-pos (missing-larkc 9459)) (:func (missing-larkc 9451)) (:exception (missing-larkc 9448)) (:pragma (missing-larkc 9468)))) *mapping-answer*))) (defun find-cnf-internal (assertion) (when (and *mapping-target* (valid-assertion assertion)) (let ((cnf (assertion-cnf assertion)) (*candidate-assertion* assertion)) (when (funcall *cnf-matching-predicate* cnf *mapping-target*) (setf *mapping-answer* assertion) ;; TODO - macro from utilities-macros? (mapping-finished))))) (defun find-gaf-formula (gaf-formula) "[Cyc] Use the gaf indexing to find any assertion whose gaf formula is GAF-FORMULA, regardless of truth. If there are more than one, it will return an arbitrary one." ;; TODO - this is a bunch of nested macro helpers, which expands to quite a large java tree. grepping seems to indicate it's used often enough to go through and break it all out. just blindly transposed for now. (let* ((result nil) (l-index (best-gaf-lookup-index gaf-formula nil nil)) (method (do-gli-extract-method l-index))) (case method (:gaf-arg (multiple-value-bind (term argnum predicate) (do-gli-vga-extract-keys l-index) (cond (argnum (if predicate ;; TODO - iteration macro (let ((pred-var predicate)) (when (do-gaf-arg-index-key-validator term argnum pred-var) (let ((iterator-var (new-gaf-arg-final-index-spec-iterator term argnum pred-var)) (done-var result) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator nil)) (unwind-protect (let ((done-var-28 result) (token-var-29 nil)) (setf final-index-iterator (new-final-index-iterator final-index-spec :gaf nil nil)) (until done-var-28 (let* ((assertion (iteration-next-without-values-macro-helper final-index-iterator token-var-29)) (valid-30 (not (eq token-var-29 assertion)))) (when valid-30 (when-let ((possible-result (find-gaf-internal assertion gaf-formula))) (setf result possible-result))) (setf done-var-28 (or (not valid-30) result))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator))))) (setf done-var (or (not valid) result))))))) ;; not predicate (let ((pred-var nil)) (when (do-gaf-arg-index-key-validator term argnum pred-var) (let ((iterator-var (new-gaf-arg-final-index-spec-iterator term argnum pred-var)) (done-var result) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator nil)) (unwind-protect (let ((done-var-31 result) (token-var-32 nil)) (setf final-index-iterator (new-final-index-iterator final-index-spec :gaf nil nil)) (until done-var-31 (let* ((assertion (iteration-next-without-values-macro-helper final-index-iterator token-var-32)) (valid-33 (not (eq token-var-32 assertion)))) (when valid-33 (when-let ((possible-result (find-gaf-internal assertion gaf-formula))) (setf result possible-result))) (setf done-var-31 (or (not valid-33) result))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator))))) (setf done-var (or (not valid) result))))))))) (predicate (let ((pred-var predicate)) (when (do-gaf-arg-index-key-validator term nil pred-var) (let ((iterator-var (new-gaf-arg-final-index-spec-iterator term nil pred-var)) (done-var result) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator nil)) (unwind-protect (let ((done-var-34 result) (token-var-35 nil)) (setf final-index-iterator (new-final-index-iterator final-index-spec :gaf nil nil)) (until done-var-34 (let* ((assertion (iteration-next-without-values-macro-helper final-index-iterator token-var-35)) (valid-36 (not (eq token-var-35 assertion)))) (when valid-36 (when-let ((possible-result (find-gaf-internal assertion gaf-formula))) (setf result possible-result))) (setf done-var-34 (or (not valid-36) result))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator))))) (setf done-var (or (not valid) result)))))))) (t (let ((pred-var nil)) (when (do-gaf-arg-index-key-validator term nil pred-var) (let ((iterator-var (new-gaf-arg-final-index-spec-iterator term nil pred-var)) (done-var result) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator nil)) (unwind-protect (let ((done-var-37 result) (token-var-38 nil)) (setf final-index-iterator (new-final-index-iterator final-index-spec :gaf nil nil)) (until done-var-37 (let* ((assertion (iteration-next-without-values-macro-helper final-index-iterator token-var-38)) (valid-39 (not (eq token-var-38 assertion)))) (when valid-39 (when-let ((possible-result (find-gaf-internal assertion gaf-formula))) (setf result possible-result))) (setf done-var-37 (or (not valid-39) result))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator))))) (setf done-var (or (not valid) result))))))))))) (:predicate-extent (let ((pred-var (do-gli-vpe-extract-key l-index))) (when (do-predicate-extent-index-key-validator pred-var) (let ((iterator-var (new-predicate-extent-final-index-spec-iterator pred-var)) (done-var result) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator nil)) (unwind-protect (let ((done-var-40 result) (token-var-41 nil)) (setf final-index-iterator (new-final-index-iterator final-index-spec :gaf nil nil)) (until done-var-40 (let* ((assertion (iteration-next-without-values-macro-helper final-index-iterator token-var-41)) (valid-42 (not (eq token-var-41 assertion)))) (when valid-42 (when-let ((possible-result (find-gaf-internal assertion gaf-formula))) (setf result possible-result))) (setf done-var-40 (or (not valid-42) result))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator))))) (setf done-var (or (not valid) result)))))))) (:overlap (missing-larkc 5149)) (otherwise (missing-larkc 30381))) result)) (defun find-gaf-internal (assertion sentence) (when (and sentence (valid-assertion assertion) (gaf-assertion? assertion)) (let ((gaf (assertion-gaf-hl-formula assertion)) (*candidate-assertion* assertion)) (when (funcall *gaf-matching-predicate* gaf sentence) assertion)))) (defparameter *gathered-rule-assertions* nil "[Cyc] The list of gathered rule assertions.")
68,314
Common Lisp
.lisp
1,237
41.09135
330
0.571719
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
f9b87bc37f73a6c77bdf0a1a070cf2b1288083993e0031445776ede2da5f8d8c
6,693
[ -1 ]
6,694
arity.lisp
white-flame_clyc/larkc-cycl/arity.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (deflexical *kb-arity-table-equality-test* #'eq "[Cyc] The equality test used for the KB arity tables.") (defglobal *kb-arity-table* nil) (defun* arity-lookup (relation) (:inline t) (gethash relation *kb-arity-table*)) (defun* set-arity (relation arity) (:inline t) (setf (gethash relation *kb-arity-table*) arity)) (defun* rem-arity (relation) (:inline t) (remhash relation *kb-arity-table*)) (defun arity (relation) (cond ((fort-p relation) (arity-lookup relation)) ((reifiable-nat? relation #'cyc-var? *anect-mt*) (missing-larkc 10320)) ((kappa-predicate-p relation) (missing-larkc 30572)) ((lambda-function-p relation) (missing-larkc 30574)))) (defun* possibly-simplify-arity (arity) (:inline t) arity) (defun maybe-add-arity-for-relation (relation arity) (setf arity (possibly-simplify-arity arity)) (let ((arity-in-table (arity relation))) (when (and arity-in-table (not (eql arity-in-table arity))) (error "Trying to overload arity for ~a from ~a to ~a" relation arity-in-table arity)) (set-arity relation arity))) (defun maybe-remove-arity-for-relation (relation arity) (let ((dont-remove nil) (other-arity nil) (pred-var #$arity)) (kmu-do-index-iteration (assertion gaf-arg (relation 1 pred-var) (:gaf :true nil) :done-place dont-remove) (let ((asserted-arity (gaf-arg2 assertion))) (if (= arity asserted-arity) (setf dont-remove (assertion-still-there? assertion :true)) (setf other-arity asserted-arity)))) (unless dont-remove (rem-arity relation)) (when other-arity (set-arity relation other-arity)))) (defglobal *kb-arity-min-table* nil) (defun* arity-min-lookup (relation) (:inline t) (gethash relation *kb-arity-min-table*)) (defun arity-min (relation) "[Cyc] Return the arity-min for RELATION." (or (arity-min-int relation) 0)) (defun arity-min-int (relation) (cond ((fort-p relation) (or (arity-min-lookup relation) (missing-larkc 12071))) ((reifiable-nat? relation #'cyc-var? *anect-mt*) (missing-larkc 10321)))) (defglobal *kb-arity-max-table* nil) (defun* arity-max-lookup (relation) (:inline t) (gethash relation *kb-arity-max-table*)) (defun arity-max (relation) "[Cyc] Return the arityMax for RELATION." (cond ((fort-p relation) (or (arity-max-lookup relation) (initialize-arity-max-for-relation relation))) ((reifiable-nat? relation #'cyc-var? *anect-mt*) (missing-larkc 10322)))) (defun initialize-arity-max-for-relation (relation) (and (fpred-value-in-any-mt relation #$arityMax) (missing-larkc 12068))) (defun* binary? (relation) (:inline t) (eql (arity relation) 2)) (defun binary-arg-swap (arg) (case arg (1 2) (2 1) (otherwise arg))) (defun variable-arity? (relation) (isa-variable-arity-relation? relation *anect-mt*)) (defun* arity-cache-unbuilt? () (:inline t) (not *kb-arity-table*)) (defun load-arity-cache-from-stream (stream) (setf *kb-arity-table* (cfasl-input stream)) (setf *kb-arity-min-table* (cfasl-input stream)) (setf *kb-arity-max-table* (cfasl-input stream)) (cfasl-input stream))
4,639
Common Lisp
.lisp
109
38.110092
92
0.707284
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
733ee26914f75f9d04fbfda39bc5ac83b6349af70f0e7f1feba38d0bbb76ad65
6,694
[ -1 ]
6,695
constant-handles.lisp
white-flame_clyc/larkc-cycl/constant-handles.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; Invalid lookup is string->constant mapping ;; Valid lookup is suid->constant mapping (defstruct (constant (:conc-name "C-")) ;; Starts as NIL, which is invalid. ;; When it becomes integerp it is "valid". ;; TODO - are there other states, or just nil & integer? should test for non-nil as it's cheaper than integerp suid ;; TODO - String, but a lot of code tests for stringp of this in terms of registering it in tables. Why? name) (declaim (inline constant-handle-valid?)) (defun constant-handle-valid? (constant) (integerp (c-suid constant))) (defglobal *constant-from-suid* nil "[Cyc] The SUID->CONSTANT mapping table.") (defun* do-constants-table () (:inline t) *constant-from-suid*) (defun setup-constant-suid-table (size exact?) (declare (ignore exact?)) (unless *constant-from-suid* (initialize-constant-names-in-code) (setf *constant-from-suid* (new-id-index size 0)))) (defun finalize-constant-suid-table (&optional max-constant-suid) (set-next-constant-suid max-constant-suid) (unless max-constant-suid ;; TODO DESIGN - I don't think we'll support memory areas ;;(let ((*current-area* (get-static-area)))) (optimize-id-index *constant-from-suid*))) (defun clear-constant-suid-table () (clear-id-index *constant-from-suid*)) (defun constant-count () "[Cyc] Return the total number of constants." (if *constant-from-suid* (id-index-count *constant-from-suid*) 0)) (defun lookup-constant-by-suid (suid) (id-index-lookup *constant-from-suid* suid)) (defun new-constant-suid-threshold () (id-index-new-id-threshold *constant-from-suid*)) (defun set-next-constant-suid (&optional max-constant-suid) (let ((max -1)) (if max-constant-suid (setf max max-constant-suid) (do-id-index (idx constant (do-constants-table) :progress-message "Determining maximum constant SUID" ;; TODO - original code was in order, not sure why for a max scan :ordered t) (let ((suid (constant-suid constant))) (setf max (max max suid))))) (let ((next-suid (1+ max))) (set-id-index-next-id *constant-from-suid* next-suid) next-suid))) (declaim (inline reset-constant-suid)) (defun reset-constant-suid (constant new-suid) "[Cyc] Primitively change the SUID of CONSTANT to NEW-SUID." (setf (c-suid constant) new-suid) constant) (defun register-constant-suid (constant suid) "[Cyc] Note that SUID will be used as the suid for CONSTANT." (reset-constant-suid constant suid) (id-index-enter *constant-from-suid* suid constant) constant) (defun deregister-constant-suid (suid) "[Cyc] Note that SUID is not in use as a constant suid." (id-index-remove *constant-from-suid* suid)) (defun make-constant-suid () "[Cyc] Return a new integer suid for a constant." (id-index-reserve *constant-from-suid*)) ;; TODO - this doesn't seem like a good hash, see how it's used. Better to add a cached hash slot to the constant object, if it's used often, and hash on the name string (defmethod sxhash ((obj constant)) (let ((suid (c-suid obj))) (if (integerp suid) suid 0))) (defun get-constant () "[Cyc] Make a new constant shell, potentially in static space." (make-constant)) (declaim (inline init-constant)) (defun init-constant (constant) (setf (c-suid constant) nil) constant) (declaim (inline free-constant)) (defun free-constant (constant) "[Cyc] Invalidate constant." (init-constant constant)) (defun valid-constant-handle? (constant) "[Cyc] Return T iff OBJECT is a valid constant handle." (and (constant-p constant) (constant-handle-valid? constant))) (declaim (inline valid-constant?)) (defun valid-constant? (constant &optional robust) (declare (ignore robust)) (valid-constant-handle? constant)) (defun invalid-constant-handle? (constant) (and (constant-p constant) (not (valid-constant-handle? constant)))) (defun invalid-constant? (constant &optional robust) (declare (ignore robust)) (and (constant-p constant) (not (valid-constant? constant)))) (defglobal *invalid-constants* (make-hash-table :test #'equal)) (defun invalid-constant-names () (hash-table-keys *invalid-constants*)) (defun find-invalid-constant (name) (gethash name *invalid-constants*)) (defun register-invalid-constant-by-name (constant name) (setf (gethash name *invalid-constants*) constant)) (defun deregister-invalid-constant-by-name (name) (remhash name *invalid-constants*)) (defun make-constant-shell (name &optional use-existing?) (check-type name 'constant-name-spec-p) (or (and use-existing? (stringp name) (or (constant-shell-from-name name) (find-invalid-constant name))) ;; If it wasn't found (or we didn't allow using existing constants), ;; make one and register it as invalid. (let ((constant (make-constant-shell-internal name t))) (when (stringp name) (register-invalid-constant-by-name constant name)) constant))) ;; TODO - any reason this isn't setting NAME via the constructor? (defun make-constant-shell-internal (name static) (declare (ignore static)) (let ((constant (get-constant))) (setf (c-name constant) name) constant)) (defun reader-make-constant-shell (constant-name use-existing?) "[Cyc] Trampoline called by the #$ reader" (make-constant-shell constant-name use-existing?)) (defun create-sample-invalid-constant () "[Cyc] Create a sample invalid constant." ;; wow, great docstring. such explain. (make-constant-shell-internal nil nil)) (defun free-all-constants () (do-id-index (id constant (do-constants-table) :progress-message "Freeing constants" :ordered t) (free-term-index constant) (free-constant constant)) (clear-constant-tables)) (declaim (inline constant-suid)) (defun constant-suid (constant) "[Cyc] Return the SUID of CONSTANT." (c-suid constant)) (defun install-constant-suid (constant suid) (declare (integer suid)) (unless (integerp (constant-suid constant)) (register-constant-suid constant suid)) constant) (declaim (inline find-constant-by-suid)) (defun find-constant-by-suid (suid) (declare (integer suid)) (lookup-constant-by-suid suid)) (defun setup-constant-tables (size exact?) (setup-constant-guid-table size exact?) (set-constant-suid-table size exact?) (setup-constant-index-table size exact?)) (defun finalize-constants (&optional max-constant-suid) (finalize-constant-suid-table max-constant-suid)) (defun clear-constant-tables () (clear-constant-guid-table) (clear-constant-suid-table))
8,128
Common Lisp
.lisp
189
38.825397
170
0.71971
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
54daf2173a79723ed992e0ee4cc90e7a683493ab5bcd9d29bd73c44f06d95001
6,695
[ -1 ]
6,696
auxiliary-indexing.lisp
white-flame_clyc/larkc-cycl/auxiliary-indexing.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defparameter *auxiliary-indices* nil) (defun declare-auxiliary-index (aux-index name) (pushnew aux-index *auxiliary-indices*) (put aux-index :index-name name) ;; TODO - return value aux-index? ) (defun auxiliary-index-p (object) (member? object *auxiliary-indices*)) (defun get-auxiliary-index (aux-index) (get aux-index :index nil)) (defun reset-auxiliary-index (aux-index new-index) (if new-index (put aux-index :index new-index) (remprop aux-index :index)) ;; TODO - return value aux-index? ) (defun num-unbound-rule-index (&optional sense mt direction) "[Cyc] Return the unbound rule count at SENSE MT DIRECTION." (cond ((simple-indexed-term-p (unbound-rule-index)) (let ((count 0)) (dolist (ass (do-simple-index-term-assertion-list (unbound-rule-index))) (declare (ignore ass)) (when (missing-larkc 30227) (incf count))) count)) ((not sense) (let ((count 0)) (dolist (sense *valid-senses*) (incf count (num-unbound-rule-index sense))) count)) (t (if-let ((unbound-rule-subindex (get-unbound-rule-subindex sense mt direction))) (subindex-leaf-count unbound-rule-subindex) 0)))) (defun relevant-num-unbound-rule-index (&optional sense) "[Cyc] Return the unbound rule count at relevant mts under SENSE." (let ((count 0)) (cond ((simple-indexed-term-p (unbound-rule-index)) (dolist (ass (do-simple-index-term-assertion-list (unbound-rule-index))) (when (and (missing-larkc 30228) (relevant-mt? (assertion-mt ass))) (incf count)))) ((not sense) (dolist (sense *valid-senses*) (incf count (relevant-num-unbound-rule-index sense)))) (t (dolist (mt (key-unbound-rule-index sense)) (when (relevant-mt? mt) (incf count (num-unbound-rule-index sense mt)))))) count)) (defun key-unbound-rule-index (&optional sense mt) "[Cyc] Return a list of the keys to the next unbound rule index level below SENSE MT." (cond ((simple-indexed-term-p (unbound-rule-index)) (let ((answer nil)) (dolist (ass (do-simple-index-term-assertion-list (unbound-rule-index))) (declare (ignore ass)) (missing-larkc 30243)) answer)) ((not sense) (let ((keys nil)) (dolist (sense *valid-senses*) (when (plusp (num-unbound-rule-index sense)) (push sense keys))) keys)) (t (when-let ((subindex (get-unbound-rule-subindex sense mt))) (intermediate-index-keys subindex))))) (defun get-unbound-rule-subindex (sense &optional mt direction) "[Cyc] Returns NIL or subindex-p." (get-subindex (unbound-rule-index) (list sense mt direction))) (defun* unbound-rule-index () (:inline t) :unbound-rule-index) (defun add-unbound-rule-indices (assertion) (let ((cnf (assertion-cnf assertion)) (mt (assertion-mt assertion)) (direction (assertion-direction assertion))) (declare (ignore mt direction)) (dolist (sense *valid-senses*) (when (some-unbound-predicate-literal cnf sense) (missing-larkc 30772)))) ;; TODO - return value assertion ) (defun rem-unbound-rule-indices (assertion) (let ((cnf (assertion-cnf assertion)) (mt (assertion-mt assertion)) (direction (assertion-direction assertion))) (declare (ignore mt direction)) (dolist (sense *valid-senses*) (when (some-unbound-predicate-literal cnf sense) (missing-larkc 30776)))) ;; TODO - return value assertion ) (defun unbound-predicate-literal (literal) (and (consp literal) (variable-p (literal-predicate literal)))) (defun some-unbound-predicate-literal (clause sense) (let ((literals (if (eq sense :pos) (pos-lits clause) (neg-lits caluse)))) (find-if #'unbound-predicate-literal literals))) (defun load-auxiliary-indices (stream) (load-unbound-rule-index stream) (cfasl-input stream)) (defun load-unbound-rule-index (stream) (reset-auxiliary-index (unbound-rule-index) (cfasl-input stream))) (declare-index :unbound-rule-index-pos ;; TODO - make direct function objects out of the raw symbols here, if possible '(:NAME "Unbound positive rule index" :DOMAIN (:NAME "term" :VALIDITY-TEST AUXILIARY-INDEX-P) :TOP-LEVEL-KEY :POS :KEYS ((:NAME "sense" :VALIDITY-TEST SENSE-P :EQUAL-TEST EQ) (:NAME "mt" :MT? T :VALIDITY-TEST HLMT-P :RELEVANCE-TEST RELEVANT-MT? :EQUAL-TEST EQUAL) (:NAME "direction" :VALIDITY-TEST DIRECTION-P :EQUAL-TEST EQ)) :RANGE (:NAME "rule" :VALIDITY-TEST RULE-ASSERTION? :DOCUMENTATION "A rule assertion in mt MT with direction DIRECTION, which contains a pos-lit with a variable in the predicate position."))) (declare-index :unbound-rule-index-neg ;; TODO - make direct function objects out of the raw symbols here, if possible '(:NAME "Unbound negative rule index" :DOMAIN (:NAME "term" :VALIDITY-TEST AUXILIARY-INDEX-P) :TOP-LEVEL-KEY :NEG :KEYS ((:NAME "sense" :VALIDITY-TEST SENSE-P :EQUAL-TEST EQ) (:NAME "mt" :MT? T :VALIDITY-TEST HLMT-P :RELEVANCE-TEST RELEVANT-MT? :EQUAL-TEST EQUAL) (:NAME "direction" :VALIDITY-TEST DIRECTION-P :EQUAL-TEST EQ)) :RANGE (:NAME "rule" :VALIDITY-TEST RULE-ASSERTION? :DOCUMENTATION "A rule assertion in mt MT with direction DIRECTION, which contains a neg-lit with a variable in the predicate position.")))
7,663
Common Lisp
.lisp
172
35.133721
164
0.624329
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
714109bf52b656cff61ecb576293e050ddf43bfdb880d10f05f9852e72e7375b
6,696
[ -1 ]
6,697
system-parameters.lisp
white-flame_clyc/larkc-cycl/system-parameters.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (deflexical *valid-system-parameter-types* '(t-or-nil nil-or-string string full-path integer symbol none) "[Cyc] The list of all known valid system parameter types.") (defglobal *system-parameters* nil "[Cyc] The list of system parameters defined by DEFINE-SYSTEM-PARAMETER.") (defun register-system-parameter (name default type description) (unless (member type *valid-system-parameter-types*) (warn "~s ~s has an unknown type ~s." 'define-system-parameter name type)) (remove-system-parameter name) (push (list name default type description) *system-parameters*) name) (defmacro define-system-parameter (name default type &body description) "Assuming behavior from context, was referenced in the .java, but without implementation. &body is used purely for indentation." `(progn (defvar ,name :unset ,@description) (register-system-parameter ',name ,default ,type ,@description))) (defun remove-system-parameter (name) "[Cyc] Remove NAME from the system parameters." (declare (symbol name)) (setf *system-parameters* (delete name *system-parameters* :test #'eq :key #'car))) (defun system-parameter-value-unset-p (val) (eq val :unset)) (defun check-system-parameters () (dolist (entry *system-parameters*) (destructuring-bind (symbol default type description) entry (declare (ignore default description)) (cond ((not (boundp symbol)) (warn "The system parameter ~s is not bound." symbol)) ((system-parameter-value-unset-p symbol) (warn "The system parameter ~s was not initialized." symbol)) (t (let* ((val (symbol-value symbol))) (unless (case type (t-or-nil (typep val 'boolean)) (nil-or-string (typep val '(or null string))) (string (stringp val)) (full-path (typep val '(or string pathname))) (integer (integerp val)) (symbol (symbolp val)) (none t)) (warn "The system parameter ~s has the value ~s, but it is supposed to be of type ~s." symbol val type)))))))) (defun load-system-parameters () "[Cyc] Load the system-parameters file." (let ((filename (merge-pathnames #P"src/main/resources/parameters.lisp" *cyc-home-directory*))) (if (probe-file filename) (with-open-file (stream filename) (loop for form = (read-parameter-form stream) until (eq :eof form) do (evaluate-parameter-form form))) (warn "System parameters file ~a not loaded." filename)))) ;; TODO - does this need to be a separate function? inline it in the above? (defun read-parameter-form (stream) (let ((*read-eval* nil)) (read stream nil :eof))) (defun evaluate-parameter-form (form) (destructuring-bind (operator &rest args) form (case operator ;; TODO - which package in clyc? (in-package (eval '(in-package "CYC"))) ((setq csetq setf) (destructuring-bind (symbol value) args (when (member symbol *system-parameters* :key #'first) (set symbol (evaluate-parameter-value value))))) (check-system-parameters (check-system-parameters))))) (defun evaluate-parameter-value (value) (cond ((atom value) value) ((eq 'quote (first value)) (second value)))) ;; TODO - this doesn't quite properly envelope toplevel forms for the macroexpansion (define-system-parameter *auto-continue-transcript-problems* t 't-or-nil "[Cyc] Possible values: NIL, T. If NIL, transcript problems will cause error breaks that make the system stop. If T, such problems will not cause breakage.") (define-system-parameter *continue-agenda-on-error* t 't-or-nil "[Cyc] Possible values: NIL, T. If NIL, agenda errors will cause the system to halt. If T, they will be automatically continued.") (define-system-parameter *suspend-sbhl-type-checking?* nil 't-or-nil "[Cyc] Possible values: T, NIL. Type checking occurs in SBHL modules IFF this is NIL.") (define-system-parameter *really-count-transcript-ops* nil 't-or-nil "[Cyc] Possible values: T, Nil. If NIL, the System Info page (accessible to administrators only) will estimate, rather than actually count, the number of operations in the transcript. If T, it will actually count them, which takes longer but is accurate.") (define-system-parameter *dont-record-operations-locally* nil 't-or-nil "[Cyc] Possible values: NIL, T. If NIL, a local transcript will always be written when operations are done, even if those operations are also being written to the master transcript. If T, then the image does not quire to a local transcript file, and will write to the master transcript when it is set to transmit operations. This allows an image that is standalone, and always in :TRANSMIT-AND-RECEIVE, to keep only a single copy of its operations.") (define-system-parameter *startup-communication-mode* :deaf 'symbol "[Cyc] Possible values -- :TRANSMIT-AND-RECEIVE, :RECEIVE-ONLY, :ISOLATED, :DEAF, :DEAD. This is the communication mode the cyc image should get initialized to at startup.") (define-system-parameter *start-agenda-at-startup?* t 't-or-nil "[Cyc] Possible values: T, NIL. If NIL, the Cyc agenda is not started at startup, but can be enabled later by the user. If T, the agenda is enabled at startup.") (define-system-parameter *base-tcp-port* 3600 'integer "[Cyc] The base port offset for all the TCP services for the Cyc image.") (define-system-parameter *fi-port-offset* 1 'integer "[Cyc] Possible values: A number. This parameter specifies the offset of the Cyc API (application programming interface) service from *BASE-TCP-PORT*.") (define-system-parameter *cfasl-port-offset* 14 'integer "[Cyc] Possible values: A number. This parameter specifies the offset of the Cyc CFASL-server service from *BASE-TCP-PORT*.") (define-system-parameter *permit-api-host-access* t 't-or-nil "[Cyc] Possible values: T, NIL. If T, then API functions can access host services including the file system and outbound tcp connections. The most secure configuration leaves this parameter NIL.") (define-system-parameter *use-transcript-server* nil 't-or-nil "[Cyc] Possible values: T, NIL. If T, then writing to the master transcsript will be controlled by the Cyc Transcript Server, which will need to be installed at your site. You only need to set this to T if you are running multiple instances of Cyc. If NIL, then Cyc will read and write to the master transcript without regard to other processes doing the same.") (define-system-parameter *master-transcript-lock-host* nil 'nil-or-string "[Cyc] Possible values: NIL or a string. This parameter is only used if *USE-TRANSCRIPT-SERVER* is T. If so, then this parameter should be set to the name of the host offering the cyc-serializer serivce.") (define-system-parameter *master-transcript-service-port* 3608 'integer "[Cyc] Possible values: A number. This parameter is only used if *USE-TRANSCRIPT-SERVER* is T. If so, then this parameter should be set to the port number fo the cyc-serializer read service.") (define-system-parameter *allow-guest-to-edit?* nil 't-or-nil "[Cyc] Possible values: T, NIL. If NIL, require authentication before allowing modifications to the knowledge base. If T, any user is allowed to modify the knowledge base.") (define-system-parameter *default-cyclist-name* "Guest" 'string "[Cyc] Possible values: The name of a constant representing a Cyclist. This is the default Cyclist initially logged into the system.") (define-system-parameter *html-image-directory* "/cycdoc/img/" 'string "[Cyc] The directory under which Cyc images (.gif or otherwise) are stored") (define-system-parameter *html-javacript-directory* "/cycdoc/js/" 'string "[Cyc] The directory under which Javascript files used by the browser are stored") (define-system-parameter *html-css-directory* "/cycdoc/css/" 'string "[Cyc] The directory under which CSS files used by the browser are stored") (define-system-parameter *cyc-execution-context* :unknown 'symbol "[Cyc] Possible values: One of the symbols :CYCORP or :UNKNOWN. If the execution context is set to :CYCORP, then the CYC image can assume that it is running in Cycorp's development environment and make strong assumptions about setup and infrastructure.")
9,813
Common Lisp
.lisp
135
67.103704
452
0.728564
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
a7ecca9468b09cf929971ba9b143925b87d7722c1696f06b7011ae98098dbec1
6,697
[ -1 ]
6,698
constants-low.lisp
white-flame_clyc/larkc-cycl/constants-low.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defglobal *arete-constants-touched* (make-hash-table :test #'eq)) (defglobal *constant-guid-table* :uninitialized "[Cyc] ID -> constant-guid table") (defglobal *constant-merged-guid-table* :uninitialized "[Cyc] ID -> merged constant-guid table. Use for keeping track of merged guids for a Constant.") (defglobal *constant-from-guid* nil "[Cyc] The GUID -> CONSTANT mapping table.") (defun setup-constant-guid-table (size exact?) (let ((setup? nil)) (unless (id-index-p *constant-guid-table*) (setf *constant-guid-table* (new-id-index size 0)) (setf setup? t)) (unless (id-index-p *constant-merged-guid-table*) (setf *constant-merged-guid-table* (new-id-index 750 0)) (setf setup? t)) (unless (hash-table-p *constant-from-guid*) (setf *constant-from-guid* (make-hash-table :size size :test #'equalp)) (setf setup? t)) setup?)) (defun lookup-constant-guid (id) (id-index-lookup *constant-guid-table* id)) (defun lookup-constant-merged-guid (id) (id-index-lookup *constant-merged-guid-table* id)) (defun lookup-constant-by-guid (guid) (gethash guid *constant-from-guid*)) (defun register-constant-guid (id constant-guid constant) "[Cyc] Note that ID will be used as the id for CONSTANT-GUID, and that the constant with guid CONSTANT-GUID is CONSTANT." (id-index-enter *constant-guid-table* id constant-guid) (setf (gethash constant-guid *constant-from-guid*) constant) constant-guid) (defun deregister-constant-guid (id guid) "[Cyc] Note that ID is not in use as a CONSTANT id, i.e. no longer points to GUID." (id-index-remove *constant-guid-table* id) (remhash guid *constant-from-guid*)) (defun clear-constant-guid-table () (clear-id-index *constant-guid-table*) (clear-id-index *constant-merged-guid-table*) (clrhash *constant-from-guid*)) (defun kb-create-constant-kb-store (name external-id) "[Cyc] Create a new constant named NAME with id EXTERNAL-ID. Return a SUID." (let ((constant (lookup-constant-by-guid external-id))) (if constant (constant-internal-id constant) (let ((suid (make-constant-suid)) (constant (make-constant-shell name t))) (install-constant-suid constant suid) (when (stringp name) (deregister-invalid-constant-by-name name)) (kb-create-constant-int constant name external-id) suid)))) (defun kb-create-constant-int (constant name external-id) (install-constant-external-id constant external-id) (when (stringp name) (add-constant-to-completions constant name))) (defun install-constant-external-id (constant external-id) (let ((guid (if (constant-legacy-id-p external-id) (missing-larkc 31626) (and (guid-p external-id) external-id)))) (install-constant-guid constant guid) constant)) (defun kb-remove-constant-internal (constant) (let ((name (constant-name-internal constant))) (when (stringp name) (remove-constant-from-completions constant name) (deregister-invalid-constant-by-name name))) (deregister-constant-guts constant) (deregister-constant-ids constant) (free-constant constant)) (defun deregister-constant-guts (constant) (let ((suid (constant-suid constant))) (when (integerp suid) (deregister-constant-index suid))) constant) (defun deregister-constant-ids (constant) "[Cyc] Remove all the id indexing to CONSTANT." (let ((guid (constant-guid constant))) (when (guid-p guid) (deregister-constant-guid (constant-suid constant) guid))) (let ((guid (constant-merged-guid constant))) (when (guid-p guid) (missing-larkc 32190))) (let ((suid (constant-suid constant))) (when (integerp suid) (deregister-constant-suid suid))) constant) (defun constant-guid-internal (constant) (lookup-constant-guid (constant-suid constant))) (defun constant-merged-guid-internal (constant) (lookup-constant-merged-guid (constant-suid constant))) (defun constant-name-internal (constant) (c-name constant)) (defun constant-index (constant) "[Cyc] Return the indexing structure for CONSTANT." (let ((id (constant-suid constant))) (and id (lookup-constant-index id)))) (defun kb-rename-constant-internal (constant new-name) (when (kb-lookup-constant-by-name new-name) (error "A constant with the name ~s already exists." new-name)) (let ((old-name (constant-name constant))) (when (stringp old-name) (remove-constant-from-completions constant old-name) (deregister-invalid-constant-by-name old-name))) (reset-constant-name constant new-name) (when (stringp new-name) (add-constant-to-completions constant new-name) (register-invalid-constant-by-name new-name constant)) constant) (defun reset-constant-name (constant new-name) "[Cyc] Primitively change the name of CONSTANT to NEW-NAME." (setf (c-name constant) new-name) constant) (defun reset-constant-index (constant new-index) "[Cyc] Primitively change the assertion index for CONSTANT to NEW-INDEX." (register-constant-index (constant-suid constant) new-index) constant) (defun install-constant-guid (constant guid) (unless (guid-p (constant-guid constant)) (reset-constant-guid constant guid)) constant) (defun reset-constant-guid (constant new-guid) "[Cyc] Primitively change teh GUID of CONSTANT to NEW-GUID." (register-constant-guid (constant-suid constant) new-guid constant) constant) (defun load-install-constant-ids (constant dump-id guid) "[Cyc] Install GUID for COSNTANT with DUMP-ID in a KB load." (let ((name (constant-name-internal constant)) (suid dump-id)) (install-constant-suid constant suid) (deregister-invalid-constant-by-name name) (kb-create-constant-int constant name guid) constant))
7,242
Common Lisp
.lisp
159
41.188679
123
0.728255
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
f476d987f4f0ac19b8a25b795b150b340f4e40a29408f0c90e31536f0294240d
6,698
[ -1 ]
6,699
file-vector-utilities.lisp
white-flame_clyc/larkc-cycl/file-vector-utilities.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defparameter *show-file-vector-reference-payload-in-print* nil "[Cyc] Rebind this to T in order to see the contents of the file-vector reference payloads.") (defstruct (file-vector-reference (:conc-name "FVECTOR-REF-")) index payload) (defconstant *cfasl-opcode-fvector-reference* 69) ;; TODO - who creates the lock? the NIL route for this is missing-larkc around all the locks (defparameter *file-vector-backed-map-read-lock* nil "[Cyc] A lock that may or may not be defined to gate access to the underlying data stream.") (defun file-vector-reference-present? (ref) (or (file-vector-reference-present-pristine? ref) (file-vector-reference-present-mutated? ref))) (defun file-vector-reference-present-mutated? (ref) "[Cyc] The file vector reference stands in for an object that is not the one that was swapped in." (or (fvector-ref-has-mutated-index-p ref) (fvector-ref-payload-in-memory-p ref))) (defun fvector-ref-has-mutated-index-p (ref) (fvector-ref-mutated-index-p (fvector-ref-index ref))) (defun fvector-ref-payload-in-memory-p (ref) (fvector-ref-payload ref)) (defun fvector-ref-mutated-index-p (index) (declare (fixnum index)) (minusp index)) (defun file-vector-reference-present-pristine? (ref) "[Cyc] The file vector reference has brought the referenced object in from teh index in the reference and holds on to it in the payload." (and (fvector-ref-has-valid-index-p ref) (fvector-ref-payload-in-memory-p ref))) (defun fvactor-ref-has-valid-index-p (ref) (fvector-ref-valid-index-p (fvector-ref-index ref))) (defun file-vector-backed-map-w/-cache-get (map file-vector cache-strategy key &optional not-found) "[Cyc] Lookup the value. If the stored result is a FILE-VECTOR-REFERENCE-P, check whetehr it is loaded in. If it is present & pristine, update the cache-strategy's tracking. If it is not loaded, load the information, enable tracking with the cache-strategy for the key, and page out the key least likely to be needed according to the cache-strategy. CACHE-STRATEGY can be SYMBOLP if no cache strategy is needed. Returns the value retrieved under the KEY or NOT-FOUDN if not present." (let ((datum (map-get-without-values map key not-found))) (when (file-vector-reference-p datum) (cond ((file-vector-reference-present? datum) (let ((value (file-vector-reference-referenced-object datum))) (when (and (cache-strategy-p cache-strategy) (file-vector-reference-present-pristine? datum)) (bt:with-lock-held (*file-vector-backed-map-read-lock*) (cache-strategy-note-cache-hit cache-strategy) (cache-strategy-note-reference cache-strategy key))) value)) ((file-vector-reference-deleted? datum) not-found) ((file-vector-reference-swapped-out? datum) (let ((index (file-vector-reference-index datum)) (data-stream (get-file-vector-data-stream file-vector))) (prog1 (bt:with-lock-held (*file-vector-backed-map-read-lock*) (position-file-vector file-vector index) (file-vector-backed-map-read-value data-stream)) (let ((potential-loser (cache-strategy-track cache-strategy key))) (unless (eq potential-loser key) (missing-larkc 6234))) (cache-strategy-note-cache-miss cache-strategy)))) (t (error "Invalid state transition: ~A is neither present, nor deleted nor swapped out." datum)))))) (defun file-vector-reference-referenced-object (ref) (fvector-ref-payload ref)) (defun file-vector-reference-index (ref) (fvector-ref-index ref)) (defun file-vector-reference-swapped-out? (ref) "[Cyc] The file vector reference refers to an object in the file vector but that object does not reside yet in memory." (and (fvector-ref-has-valid-index-p ref) (not (fvector-ref-payload-in-memory-p ref)))) (defun file-vector-backed-map-read-value (data-stream) (cfasl-input data-stream)) (defun file-vector-reference-deleted? (ref) "[Cyc] The file vector reference refers to a deleted object." (and (fvector-ref-has-mutated-index-p ref) (not (fvector-ref-payload-in-memory-p ref)))) (defun file-vector-backed-map-m/-cache-put (map cache-strategy key value) "[Cyc] Put the value into the file-vector backed map. if the entry denoted by the key has a file vector backed reference, then mark the file vector reference as mutated and replace the payload with the value. If the CACHE-STRATEGY is valid, then untrack the key. Otherwise, simply store the passed-in new value. CACHE-STRATEGY can be SYMBOLP if no cache strategy is needed. Returns :MUTATED if the entry was a file-vector reference, NIL otherwise." (let ((new-value value) (current-value (map-get-without-values map key :not-found)) (mutated-p nil)) (if (file-vector-reference-p current-value) (missing-larkc 6215) (map-put map key new-value)) mutated-p)) (defun file-vector-backed-map-w/-cache-remove (map cache-strategy key &optional support-undo-p) (declare (ignore cache-strategy)) (let* ((current-value (map-get-without-values map key :not-found)) (is-file-vector-reference (file-vector-reference-p current-value)) (deleted-p nil)) (if support-undo-p (missing-larkc 6214) (map-remove map key)) (if (and is-file-vector-reference (missing-larkc 31228)) (bt:with-lock-held (*file-vector-backed-map-read-lock*) (missing-larkc 31248))) deleted-p)) (defun fvector-ref-valid-index-p (index) (declare (fixnum index)) (plusp index)) (defun new-file-vector-reference (index) (declare (fixnum index)) (must (> index 0) "File Vector references cannot be zero.") (let ((ref (make-file-vector-reference :index index))) (clear-file-vector-reference-referenced-object ref) ref)) (defun clear-file-vector-reference-referenced-object (ref) (set-file-vector-reference-referenced-object ref nil)) (defun set-file-vector-reference-referenced-object (ref object) (setf (fvector-ref-payload ref) object) ref) (defun cfasl-input-file-vector-reference (stream) (let ((index (cfasl-input stream))) (if (fvector-ref-valid-index-p index) (new-file-vector-reference index) (new-file-vector-reference-w/-payload index (cfasl-input stream))))) (defun new-file-vector-reference-w/-payload (index payload) (let ((ref (new-file-vector-reference index))) (set-file-vector-reference-referenced-object ref payload) ref)) (defun file-vector-backed-map-w/cache-touch (map cache-strategy key &optional fvector) "[Cyc] If the entry denoted by key has a file-vector backed reference, then mark the reference as mutated. This allows to percolate change information properly in situations where the value of a map is a container. Touched items have to be untracked in the cache strategy if caching is active. CACHE-STRATEGY can be SYMBOLP if no cache strategy is needed. FVECTOR need only be valid if the entry is swapped out at the time of the call, because touch must paget he absent values in. Returns :MUTATED if the entry was a file vector reference, nil otherwise." (let ((current-value (map-get-without-values map key :not-found))) (when (file-vector-reference-p current-value) (let ((ref current-value)) (when (file-vector-reference-swapped-out? ref) (file-vector-backed-map-w/-cache-get map fvector cache-strategy key)) (mark-file-vector-reference-as-mutated ref) (when (cache-strategy-p cache-strategy) (missing-larkc 31250)) :mutated)))) (defun mark-file-vector-reference-as-mutated (ref) (let* ((index (fvector-ref-index ref)) (mutated-index (- (abs index)))) (setf (fvector-ref-index ref) mutated-index)) ref) (defun swap-out-all-pristine-file-vector-backed-map-objects (map) "[Cyc] For all values in the MAP, if the value is a pristine file vector reference, then zero out its payload to make that data available for garbage collection. Return 0: the MAP Return 1: the count of paged out items." (let ((swapped-out 0) (iterator (new-map-iterator map)) (done nil)) (until done (multiple-value-bind (var valid) (iteration-next iterator) (if valid (multiple-value-bind (key value) var (declare (ignore key)) (when (potentially-swap-out-pristine-file-vector-backed-map-object value) (incf swapped-out))) (return (values map swapped-out))))))) (defun potentially-swap-out-pristine-file-vector-backed-map-object (value) "[Cyc] Helper for swapping out, both in the larger context of swapping out all and in the more specific context of swapping out some. Returns T if there was a file vector reference that was pristine and swapped out, NIL otherwise." (and (file-vector-reference-p value) (file-vector-reference-present-pristine? value) (progn (clear-file-vector-reference-referenced-object value) t))) (defstruct backed-map map fvector common-symbols) (defconstant *cfasl-opcode-backed-map* 76) (defparameter *current-backed-map-cache-strategy* nil "[Cyc] The current cache strategy to use for this backed-map operation. Defaults to none.") ;; TODO - most of the original defmethods were missing-larkc. Does this implemented one matter? Where's the defgeneric/defpolymorphic? (defmethod is-map-object-p ((object backed-map)) t)
10,957
Common Lisp
.lisp
198
49.929293
351
0.723364
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
bc033c839dfe0a8f685920b75f7fa9f11f2736c40b80b8ea69f30e52de9a9535
6,699
[ -1 ]
6,700
integer-sequence-generator.lisp
white-flame_clyc/larkc-cycl/integer-sequence-generator.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defstruct (integer-sequence-generator (:conc-name "ISG-")) lock current start limit delta) (defun new-integer-sequence-generator (&optional (start 0) limit (delta 1)) (must-not (zerop delta) "DELTA must not be zero") (make-integer-sequence-generator :lock (bt:make-lock "ISG") :current start :start start :limit limit :delta delta)) (defun integer-sequence-generator-reset (isg) "[Cyc] Reset an Integer Sequence Generator to its original state." (bt:with-lock-held ((isg-lock isg)) (setf (isg-current isg) (isg-start isg)))) (defconstant *cfasl-wide-opcode-isg* 130) ;; TODO DESIGN - This is a complete conversion from the .java version, but doesn't seem enough to be useful. ;; Other code creates these, but they don't ever seem to be stepped.
2,308
Common Lisp
.lisp
47
43.170213
108
0.720805
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
824d698307eeef07909bbb48f232ac35eee9a50d1c4a74389ea4e750eda729da
6,700
[ -1 ]
6,701
pattern-match.lisp
white-flame_clyc/larkc-cycl/pattern-match.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO OPTIMIZATION - change (destructuring-bind (single) list ...) to a specific check that the list is of length 1, erroring otherwise. Would be cheaper than calling into the destructuring-bind mechanism, assuming pattern matching is commonly called. ;; TODO - maybe make this a closure variable for performance (defparameter *pattern-matches-tree-bindings* nil) ;; TODO - could be a bit faster if it was (operator . method) (defparameter *pattern-matches-tree-atomic-methods* nil "[Cyc] Additional atomic methods for PATTERN-MATCHES-TREE. Entries are of the form (operator method). OPERATOR is a token indicating the match method. METHOD must be suitable for (funcall method <tree>).") (defparameter *pattern-matches-tree-methods* nil "[Cyc] Additional methods for PATTERN-MATCHES-TREE. Entries are of the form (operator method). OPERATOR is a token indicating the match method. METHOD must be suitable for (funcall method <pattern> <tree>).") (defun* add-pattern-matches-tree-binding (variable value) (:inline t) (setf *pattern-matches-tree-bindings* (alist-enter-without-values *pattern-matches-tree-bindings* variable value #'eql))) (defun pattern-matches-tree (pattern tree) "[Cyc] Return T iff PATTERN matches TREE." ;; Converted ignore-errors to handler-case in order to keep the number of return values consistent. (handler-case (let ((*pattern-matches-tree-bindings* nil)) (when (pattern-matches-tree-internal pattern tree) (values t (nreverse *pattern-matches-tree-bindings*)))) (error () (values nil nil)))) (defun* pattern-matches-tree-without-bindings (pattern tree) (:inline t) "[Cyc] Return T iff PATTERN matches TREE. :BIND expressions are not allowed in PATTERN." (pattern-matches-tree-internal pattern tree)) (defun* pattern-matches-tree-internal (pattern tree) (:inline t) "[Cyc] For use by pattern match methods in other files." (pattern-matches-tree-recursive pattern tree)) (defun* pattern-matches-tree-atomic-method-funcall (method tree) (:inline t) (funcall method tree)) (defun* pattern-matches-tree-method-funcall (method pattern tree) (:inline t) (funcall method pattern tree)) (defun pattern-matches-tree-recursive (pattern tree) (if (atom pattern) (case pattern (:anything t) (:nothing nil) (otherwise (dolist (method-info *pattern-matches-tree-atomic-methods* (equal pattern tree)) (when (eq (first method-info) pattern) (return (pattern-matches-tree-atomic-method-funcall (second method-info) tree)))))) (destructuring-bind (pattern-operator . pattern-args) pattern (declare (list pattern-args)) ;; TODO OPTIMIZATION - this smacks of needing precompilation, just like regex patterns (case pattern-operator (:bind (pattern-matches-tree-bind pattern tree)) ;; TODO DESIGN - is this for testing an already bound variable? (:value (missing-larkc 32006)) (:and (pattern-matches-tree-and pattern tree)) (:or (pattern-matches-tree-or pattern tree)) ;; TODO - is this just ensuring there is 1 element in the list? (:not (destructuring-bind (sub-pattern) pattern-args (not (pattern-matches-tree-recursive sub-pattern tree)))) ;; TODO - this presumably calls fixed-arity funcall functions in the original code, from 1-4 pattern-args. If there's more, there's no case to handle that and it silently contnues, which seems odd. However, maybe the intent is that covers all cases? Using the general case here. (:test (apply (first pattern-args) (rest pattern-args))) (:tree-find (destructuring-bind (sub-pattern) pattern-args (pattern-matches-tree-tree-find sub-pattern tree))) (:quote (destructuring-bind (quoted-object) pattern-args (equal quoted-object tree))) (otherwise (dolist (method-info *pattern-matches-tree-methods* (pattern-matches-tree-cons pattern tree)) (when (eq (car method-info) pattern-operator) (return (pattern-matches-tree-method-funcall (second method-info) pattern tree))))))))) (defun pattern-matches-tree-bind (pattern tree) (let ((variable (second pattern))) (add-pattern-matches-tree-binding variable tree))) (defun pattern-matches-tree-and (pattern tree) (dolist (sub-pattern (rest pattern) t) (unless (pattern-matches-tree-recursive sub-pattern tree) (return nil)))) (defun pattern-matches-tree-or (pattern tree) (dolist (sub-pattern (rest pattern) nil) (when (pattern-matches-tree-recursive sub-pattern tree) (return t)))) (defun pattern-matches-tree-test-funcall (test tree) (funcall test tree)) (defun pattern-matches-tree-tree-find (sub-pattern tree) (tree-find sub-pattern tree #'pattern-matches-tree-recursive)) (defun pattern-matches-tree-cons (pattern tree) (unless (atom tree) (destructuring-bind (pattern-operator . pattern-args) pattern (destructuring-bind (tree-operator . tree-args) tree (when (pattern-matches-tree-recursive pattern-operator tree-operator) (do ((rest-pattern-args pattern-args (cdr rest-pattern-args)) (rest-tree-args tree-args (cdr rest-tree-args))) ((or (atom rest-pattern-args) (atom rest-tree-args)) (pattern-matches-tree-recursive rest-pattern-args rest-tree-args)) (unless (pattern-matches-tree-recursive (car rest-pattern-args) (car rest-tree-args)) (return nil)))))))) (defparameter *pattern-transform-tree-bindings* nil) (defparameter *pattern-transform-match-method* nil) (defun pattern-transform-tree (pattern tree &optional bindings) "[Cyc] Use PATTERN to transform TREE, assuming BINDINGS. Return transformation result and updated BINDINGS." (let ((*pattern-transform-tree-bindings* bindings)) (values (pattern-transform-tree-internal pattern tree) *pattern-transform-tree-bindings*))) (defun pattern-transform-tree-internal (pattern tree) "[Cyc] For use by pattern transform methods in other files." (pattern-transform-tree-recursive pattern tree)) ;; TODO OPTIMIZATION - again, this would really want precompilation (defun pattern-transform-tree-recursive (pattern tree) (if (atom pattern) (case pattern (:input tree) (:bindings *pattern-transform-tree-bindings*) (otherwise pattern)) (destructuring-bind (pattern-operator . pattern-args) pattern (case pattern-operator (:value (destructuring-bind (variable) pattern-args (alist-lookup-without-values *pattern-transform-tree-bindings* variable #'eql nil))) (:tuple (pattern-transform-tuple pattern tree)) (:template (pattern-transform-template pattern tree)) (:call (pattern-transform-call pattern tree)) (:quote (destructuring-bind (quoted-object) pattern-args quoted-object)) (otherwise (pattern-transform-cons pattern tree)))))) (defun pattern-transform-tuple (pattern tree) (destructuring-bind (operator variables subpattern) pattern ;; The operator was already matched in pattern-perform-tree-recursive (declare (ignore operator)) (when (and (listp tree) (listp variables) (same-length-p tree variables)) (mapc (lambda (variable subtree) (add-pattern-matches-tree-binding variable subtree)) variables tree) (pattern-transform-tree-recursive subpattern nil)))) (defun pattern-transform-template (pattern tree) (destructuring-bind (operator match-pattern subpattern) pattern (declare (ignore operator)) (multiple-value-bind (success bindings) (if *pattern-transform-match-method* (funcall *pattern-transform-match-method* match-pattern tree) (pattern-matches-tree match-pattern tree)) (when success (dolist (binding bindings) (destructuring-bind (variable . value) binding (add-pattern-matches-tree-binding variable value))) (pattern-transform-tree-recursive subpattern nil))))) (defun pattern-transform-call (pattern tree) (destructuring-bind (operator method &rest method-args) pattern (declare (list method-args) (ignore operator)) ;; The original fast-pathed 0-4 args with a bunch of tests. ;; Not sure that helps in modern processors. TODO - profile (apply method (mapcar (lambda (arg) (pattern-transform-tree arg tree)) method-args)))) (defun pattern-transform-cons (pattern tree) (let ((answer (copy-list pattern))) ;; Transform the CARs and final CDR of the copied list. (do ((rest-answer answer (cdr answer))) ((atom (cdr rest-answer)) (rplaca rest-answer (pattern-transform-tree-recursive (car rest-answer) tree)) (when (cdr rest-answer) (rplacd rest-answer (pattern-transform-tree-recursive (cdr rest-answer) tree)))) (rplaca rest-answer (pattern-transform-tree-recursive (car rest-answer) tree))) answer))
10,861
Common Lisp
.lisp
195
47.723077
290
0.691866
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
b5e012485cc636e27b6fad31dddd08675c4baee5c6e21cc97b5a7317d3527b4f
6,701
[ -1 ]
6,702
vector-utilities.lisp
white-flame_clyc/larkc-cycl/vector-utilities.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun vector-elements (vector &optional (start-index 0)) "[Cyc] Convert VECTOR to a list of its elements." (loop for index from start-index below (length vector) collect (aref vector index))) (defun extend-vector-to (vector new-length &optional initial-value) (let ((new-vector (make-vector new-length initial-value))) (replace new-vector vector) new-vector))
1,778
Common Lisp
.lisp
35
47.314286
77
0.773124
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
748dc54004a9af4a4cfd9cf3f71441dfa904d2e3002f2e483e830311714aeb75
6,702
[ -1 ]
6,703
mt-vars.lisp
white-flame_clyc/larkc-cycl/mt-vars.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (deflexical *mt-var-basis-table* (make-hash-table)) (defun note-mt-var (var &optional basis) (when basis (note-mt-var-basis var basis))) (defun note-mt-var-basis (var basis) (setf (gethash var *mt-var-basis-table*) basis)) (defmacro defglobal-mt-var (var default &optional basis comment) ;; TODO - there's an error check message about an illegal basis argument. No idea what it's checking. `(progn (defglobal ,var ,default ,comment) (note-mt-var ',var ,basis))) (defglobal-mt-var *mt-root* #$BaseKB nil "[Cyc] The root of the microtheory heirarchy.") (defglobal-mt-var *theory-mt-root* #$BaseKB nil "[Cyc] The highest theory microtheory where assertions/deductions could possibly go.") (defglobal-mt-var *assertible-mt-root* #$BaseKB nil "[Cyc] The highest microtheory where assertions can normally be made.") (defglobal-mt-var *assertible-theory-mt-root* #$BaseKB nil "[Cyc] The highest theory microtheory where assertions can normally be made.") (defglobal-mt-var *core-mt-floor* #$BaseKB nil "[Cyc] The minimum (lowest) core microtheory.") (defglobal-mt-var *mt-mt* #$UniversalVocabularyMt #$Microtheory "[Cyc] The microtheory in which microtheories are asserted tobe instances of #$MicroTheory, and the microtheory where #$genlMt assertions go.") (defglobal-mt-var *defining-mt-mt* #$BaseKB #$definingMt "[Cyc] The microtheory where #$definintMt assertions go. Should be the same as the *MT-MT*") (defglobal-mt-var *decontextualized-predicate-mt* #$BaseKB #$decontextualizedPredicate "[Cyc] The microtheory where #$decontextualizedPredicate assertions go.") (defglobal-mt-var *decontextualized-collection-mt* #$BaseKB #$decontextualizedPredicate "[Cyc] The microtheory where #$decontextualizedCollection assertions go.") (defglobal-mt-var *ephemeral-term-mt* #$BaseKB #$ephemeralTerm "[Cyc] The microtheory where #$ephemeralTerm gafs go.") (defglobal-mt-var *ist-mt* #$BaseKB #$ist "[Cyc] The microtheory where #$ist code supports are supported from. It would be the microtheory where #$ist gafs would go, bu those shouldn't really be in the KB at all.") (defglobal-mt-var *inference-related-bookkeeping-predicate-mt* #$BaseKB #$InferenceRelatedBookkeepingPredicate "[Cyc] The microtheory where isa assertions to #$InferenceRelatedBookkeepingPredicate go.") (defglobal-mt-var *anect-mt* #$UniversalVocabularyMt #$AtemporalNecessarilyEssentialCollectionType "[Cyc] The mt where isas to instances of #$AtemporalNecessarilyEssentialCollectionType go. Note that this includes #$AtemporalNecessarilyEssentialCollectionType itself, and the code assumes that these mts are the same.") (defglobal-mt-var *broad-mt-mt* #$BaseKB #$BroadMicrotheory "[Cyc] The microtheory where isa assertions to #$BroadMicrotheory go.") (defglobal-mt-var *psc-mt* #$BaseKB #$ProblemSolvingCntxt "[Cyc] The microtheory where isa assertions to #$ProblemSolvingContext go.") (defglobal-mt-var *tou-mt* #$BaseKB #$termOfUnit "[Cyc] The microtheory where #$termOfUnit assertions go.") (defglobal-mt-var *skolem-mt* #$BaseKB #$skolem "[Cyc] The microtheory where #$skolem assertions go.") (defglobal-mt-var *thing-defining-mt* #$BaseKB #$Thing "[Cyc] The microtheory where #$Thing is defined.") (defglobal-mt-var *relation-defining-mt* #$BaseKB #$Relation "[Cyc] The microtheory where #$Relation is defined.") (defglobal-mt-var *equals-defining-mt* #$BaseKB #$equals "[Cyc] The microtheory where #$equals is defined.") (defglobal-mt-var *element-of-defining-mt* #$BaseKB #$elementOf) (defglobal-mt-var *subset-of-defining-mt* #$BaseKB #$subsetOf) (defglobal-mt-var *arity-mt* #$UniversalVocabularyMt #$arity "[Cyc] The microtheory where #$arity assertions go.") (defglobal-mt-var *sublid-mt* #$CycAPIMt #$subLIdentifier "[Cyc] The microtheory from which #$subLIdentifier and #$uniquelyIdentifiedInType assertions would be visible.") (defglobal-mt-var *not-assertible-mt-convention-mt* #$UniversalVocabularyMt #$notAssertibleMt "[Cyc] The microtheory where #$notAssertibleMt assertions go.") (defglobal-mt-var *default-ask-mt* #$BaseKB nil "[Cyc] The default mt for asks.") (defglobal-mt-var *default-assert-mt* #$BaseKB nil "[Cyc] The default mt for asserts.") (defglobal-mt-var *default-clone-mt* #$BaseKB nil "[Cyc] The default mt for cloning sentences -- should be the common genl of the above two.") (defglobal-mt-var *default-support-mt* #$BaseKB nil "[Cyc] The default mt for HL supports -- one should be specified, but this is what to use as a backup.") (defglobal-mt-var *default-comment-mt* #$BaseKB nil "[Cyc] The default mt for asserting comments and cyclistNotes.") (defglobal-mt-var *default-convention-mt* #$UniversalVocabularyMt nil "[Cyc] The default mt for the convertion mt of a decontextualized predicate or collection, to use if none is specified in the KB.") (defparameter *core-mt-optimization-enabled?* t "[Cyc] Temporary control variable; controls whether or not genlMt has special-case optimization for core-microtheory-p.") (deflexical *core-mts* '(#$LogicalTruthMt #$LogicalTruthImplementationMt #$CoreCycLMt #$CoreCycLImplementationMt #$UniversalVocabularyMt #$UniversalVocabularyImplementationMt #$BaseKB) "[Cyc] The cluster of mts up near the root of the microtheory hierarchy. Ordered from max (topmost) to min (lowest).") (deflexical *ordered-core-mts* '((#$LogicalTruthMt . 0) (#$LogicalTruthImplementationMt . 0) (#$CoreCycLMt . 1) (#$CoreCycLImplementationMt . 1) (#$UniversalVocabularyMt . 2) (#$UniversalVocabularyImplementationMt . 2) (#$BaseKB . 3)) "[Cyc] The cluster of mts up near the root of the microtheory hierarchy. Min numbered is topmost.") (defun core-microtheory-p (object) "[Cyc] Return T iff OBJECT is a core microtheory." (member-eq? object *core-mts*)) (defun core-microtheory-< (mt1 mt2) "[Cyc] Return T iff core microtheory MT1 is lower than MT2 in the #$genlMt hierarchy." ;; TODO - this is actually a <= comparison, not < (let ((level1 (alist-lookup-without-values *ordered-core-mts* mt1)) (level2 (alist-lookup-without-values *ordered-core-mts* mt2))) (and (integerp level1) (integerp level2) (<= level2 level1)))) (defun core-microtheory-> (mt1 mt2) "[Cyc] Return T iff core microtheory MT1 is higher than MT2 in the #$genlMt hierarchy." (let ((level1 (alist-lookup-without-values *ordered-core-mts* mt1)) (level2 (alist-lookup-without-values *ordered-core-mts* mt2))) (and (integerp level1) (integerp level2) (<= level1 level2)))) (defun core-genl-mt? (mt1 mt2) (if (and (special-core-loop-mt-p mt1) (special-core-loop-mt-p mt2)) t (core-microtheory-> mt1 mt2))) (deflexical *special-loop-core-mts* '(#$UniversalVocabularyMt #$BaseKB)) (defun special-core-loop-mt-p (object) (member-eq? object *special-loop-core-mts*)) (defun minimize-mts-wrt-core (mts) "[Cyc] Reduces MTS by eliminating any core microtheories that are proper gelMt of microtheories in MTS." (multiple-value-bind (core-mts non-core-mts) (partition-list mts #'core-microtheory-p) (or non-core-mts (non-null-answer-to-singleton (extremal core-mts #'core-microtheory-<))))) (defun maximize-mts-wrt-core (mts) "[Cyc] Reduces MTS by eliminating any non-core mts if there are any core mts, and then taking the maximal core mt." (let ((core-mts (remove-if-not #'core-microtheory-p mts))) (if core-mts (list (extremal core-mts #'core-microtheory->)) mts))) (defun minimize-mt-sets-wrt-core (mt-sets) "[Cyc] Reduces mts in MT-SETS by eliminating any proper genlMts of core microtheories in each element of MT-SETS." (let ((reduced-mt-sets nil)) (dolist (mt-set mt-sets) (pushnew (minimize-mts-wrt-core mt-set) reduced-mt-sets :test #'sets-equal?)) (nreverse reduced-mt-sets)))
10,046
Common Lisp
.lisp
161
54.285714
161
0.687532
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
2938fe6750200c5b8c7a13b1b2d1c291db9c7b41e5f3b8e1cc1074f548355ed2
6,703
[ -1 ]
6,704
hl-modifiers.lisp
white-flame_clyc/larkc-cycl/hl-modifiers.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun kb-create-asserted-argument-with-tv (assertion tv) (kb-create-asserted-argument assertion (tv-truth tv) (tv-strength tv))) (define-hl-modifier kb-create-asserted-argument (assertion truth strength) "[Cyc] Create an asserted argument for ASSERTION from TRUTH and STRENGTH, and hook up all the indexing between them." nil (let* ((tv (tv-from-truth-strength truth strength)) (asserted-argument (create-asserted-argument assertion tv))) (add-new-assertion-argument assertion asserted-argument) asserted-argument)) (define-hl-modifier kb-remove-asserted-argument (assertion asserted-argument) "[Cyc] Remove ASSERTED-ARGUMENT for ASSERTION." nil (set-assertion-asserted-by assertion nil) (set-assertion-asserted-when assertion nil) (set-assertion-asserted-why assertion nil) (set-assertion-asserted-second assertion nil) (remove-assertion-argument assertion asserted-argument) (kb-remove-asserted-argument-internal asserted-argument)) (define-hl-modifier hl-assert-bookkeeping-binary-gaf (pred arg1 arg2 mt) "[Cyc] Assert (PRED ARG1 ARG2) in MT to the bookkeeping store." nil (assert-bookkeeping-binary-gaf pred arg1 arg2 mt))
2,649
Common Lisp
.lisp
51
47.294118
121
0.760186
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
bf68dd3255b570ba34307762f90815875837b846f67c4a2ac3ddc9ae35c7a13e
6,704
[ -1 ]
6,705
transform-list-utilities.lisp
white-flame_clyc/larkc-cycl/transform-list-utilities.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defparameter *default-recursion-limit* 212) (defparameter *default-transformation-max* nil) (defparameter *default-quiescent-transformation-max* 1024) (defun transform-pred-funcall (pred object) (possibly-cyc-api-funcall pred object)) (defun transform-transform-funcall (transform object) (possibly-cyc-api-funcall transform object)) (defun transform (object pred transform &optional (key #'identity)) "[Cyc] Recursively descends through OBJECT, destructively applying TRANSFORM when PRED succeeds. Make sure that the results of TRANSFORM will not succeed on PRED, otherwise it may 'infinitely' recurse. example: (transform '(1 \"2\" (3 4 \"5\")) #'stringp 'read-from-string) -> (1 2 (3 4 5))" (ntransform (copy-tree object) pred transform key)) (defun ntransform (object pred transform &optional (key #'identity) (recursion-limit *default-recursion-limit*) (transformation-max *default-transformation-max*)) "[Cyc] A destructive version of TRANSFORM. OBJECT: The object to be transformed. PRED: A predicate that returns true if an object is to be transformed by TRANSFORM. KEY: A function that maps an object to a value that is to be transformed. RECURSION-LIMIT: The maximum depth that the algorith mis allowed to recurse. Once this limit is exceeded, the transformation continues by means of an iterative algorithm. TRANSFORMATION-MAX: The maximum number of transformations to be performed before throwing :TRANSFORMATION-LIMIT-EXCEEDED. If this parameter is given NIL as a value, no limit is imposed on the number of transformations." (if transformation-max (missing-larkc 7713) (ntransform-recursive object pred transform key recursion-limit 0))) (defun ntransform-recursive (object pred transform key recursion-limit recursion-level) "[Cyc] A destructive recursive version of TRANSFORM. This function transforms as it iterates down the CDR of transformations and recurses as it transforms their CARs. When the recursion limit is reached, it switches to a purely iterative algorithm by calling NTRANSFORM-ITERATIVE." (declare (fixnum recursion-level recursion-limit)) (if (>= recursion-level recursion-limit) (missing-larkc 7700) (let* ((initial-transformed-object (ntransform-perform-transform object pred transform key)) (transformed-list-tail initial-transformed-object)) (until (atom transformed-list-tail) (rplaca transformed-list-tail (ntransform-recursive (car transformed-list-tail) pred transform key recursion-limit (1+ recursion-level))) (rplacd transformed-list-tail (ntransform-perform-transform (cdr transformed-list-tail) pred transform key))) initial-transformed-object))) (defun ntransform-perform-transform (object pred transform &optional (key #'identity)) (if (or (eq #'identity key) (eq 'identity key)) ;; identity-optimized version (let ((previous-transformation object)) (do ((transformation (if (transform-pred-funcall pred object) (copy-tree (transform-transform-funcall transform object)) object) (if (transform-pred-funcall pred transformation) (copy-tree (transform-transform-funcall transform transformation)) transformation))) ((eq previous-transformation transformation) transformation) (setf previous-transformation transformation))) ;; key-calling version (let ((previous-transformation object)) (do ((transformation (if (transform-pred-funcall pred object) (copy-tree (transform-transform-funcall transform (missing-larkc 7716))) object) (if (transform-pred-funcall pred transformation) (copy-tree (transform-transform-funcall transform (missing-larkc 7717))) transformation))) ((eq previous-transformation transformation) transformation) (setf previous-transformation transformation))))) (defun quiescent-transform (object pred transform &optional (key #'identity) (quiescence #'equal)) (quiescent-ntransform (copy-tree object) pred transform key quiescence)) (defun quiescent-ntransform (object pred transform &optional (key #'identity) (quiescence #'equal) (recursion-limit *default-recursion-limit*) (transformation-max *default-quiescent-transformation-max*)) "[Cyc] Calls QUIESCENT-NTRANSFORM-RECURSIVE to iteratively transfrom object and then its transformation using TRANSFORM so long as PRED succeeds and the application of QUIESCENCE to the transformation of the object fails. Upon finishign a series of transformations, QUIESCENT-NTRANSFORM-RECURSIVE is then recursively applied to the CAR of teh transformation while successive CDRs of the transformation are transfromed according to the same algorithm. If, in the process of transformation, the recursion limit RECURSION-LIMIT is reached, then QUIESCENT-NTRANSFORM-ITERATIVE is called to solve the subtransformation without recursion. RECURSION-LIMIT: The maximum depth that the algorithm is allowed to recurse. Once this limit is exceeded, the transformation continues by means of an iterative algorithm. TRANSFORMATION-MAX: The maximum number of transformations to be performed before throwing :TRANSFORMATION-LIMIT-EXCEEDED. If this parameter is given NIL as a value, no limit is imposed on the number of transformations." (if transformation-max (shy-quiescent-ntransform-recursive object pred transform key quiescence recursion-limit 0 transformation-max 0) (missing-larkc 7706))) (defun shy-quiescent-ntransform-recursive (object pred transform key quiescence recursion-limit recursion-level transformation-max transformation-count) "[Cyc] See documentation for QUIESCENT-NTRANSFORM." (if (>= recursion-level recursion-limit) (missing-larkc 7715) (multiple-value-bind (initial-transformed-object new-transformation-count) (shy-ntransform-perform-quiescent-transform object pred transform key quiescence transformation-max transformation-count) (let ((transformed-list-tail initial-transformed-object) (transformed-object nil)) (until (atom transformed-list-tail) (multiple-value-bind (obj count) (shy-quiescent-ntransform-recursive (car transformed-list-tail) pred transform key quiescence recursion-limit (1+ recursion-level) transformation-max new-transformation-count) (setf transformed-object obj) (setf new-transformation-count count)) (rplaca transformed-list-tail transformed-object) (multiple-value-bind (obj count) (shy-ntransform-perform-quiescent-transform (cdr transformed-list-tail) pred transform key quiescence transformation-max new-transformation-count) (setf transformed-object obj) (setf new-transformation-count count))) (values initial-transformed-object new-transformation-count))))) (defun shy-ntransform-perform-quiescent-transform (object pred transform key quiescence transformation-max transformation-count) ;; 4 versions, for optimizing default values of key & quiescence (if (or (eq #'identity key) (eq 'identity key)) (if (or (eq #'equal quiescence) (eq 'equal quiescence)) ;; key = identity, quiescence = equal (let ((previous-transformation object)) (do ((transformation (if (transform-pred-funcall pred object) (copy-tree (transform-transform-funcall transform object)) object) (if (transform-pred-funcall pred transformation) (copy-tree (transform-transform-funcall transform transformation)) transformation))) ((or (eq previous-transformation transformation) (equal previous-transformation transformation)) (values transformation transformation-count)) (incf transformation-count) (setf previous-transformation transformation))) ;; key = identity (let ((previous-transformation object)) (do ((transformation (if (transform-pred-funcall pred object) (copy-tree (transform-transform-funcall transform object)) object) (if (transform-pred-funcall pred object) (copy-tree (transform-transform-funcall transform transformation)) transformation))) ((or (eq previous-transformation transformation) (missing-larkc 7722)) (values transformation transformation-count)) (when (>= transformation-count transformation-max) (throw :transformation-limit-exceeded (list :transformation-limit-exceeded transformation-count transformation-max))) (incf transformation-count) (setf previous-transformation transformation)))) (if (or (eq #'equal quiescence) (eq 'equal quiescence)) ;; quiescence = equal (let ((previous-transformation object)) (do ((transformation (if (transform-pred-funcall pred object) (copy-tree (transform-transform-funcall transform (missing-larkc 7718))) object) (if (transform-pred-funcall pred transformation) (copy-tree (transform-transform-funcall transform (missing-larkc 7719))) transformation))) ((or (eq previous-transformation transformation) (equal previous-transformation transformation)) (values transformation transformation-count)) (when (>= transformation-count transformation-max) (throw :transformation-limit-exceeded (list :transformation-limit-exceeded transformation-count transformation-max))) (incf transformation-count) (setf previous-transformation transformation))) ;; No optimization (let ((previous-transformation object)) (do ((transformation (if (transform-pred-funcall pred object) (copy-tree (transform-transform-funcall transform (missing-larkc 7720))) object) (if (transform-pred-funcall pred transformation) (copy-tree (transform-transform-funcall transform (missing-larkc 7721))) transformation))) ((or (eq previous-transformation transformation) (missing-larkc 7723))) (when (>= transformation-count transformation-max) (throw :transformation-limit-exceeded (list :transformation-limit-exceeded transformation-count transformation-max))) (incf transformation-count) (setf previous-transformation transformation))))))
13,949
Common Lisp
.lisp
203
51.862069
635
0.628546
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
920b0f920b76696b522acdebe22b61be33bb07f4a8de0601c0b3aee47b04b648
6,705
[ -1 ]
6,706
iteration.lisp
white-flame_clyc/larkc-cycl/iteration.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO DESIGN - this will likely run faster if done/next/finalize are 3 functions returned from a single closure around STATE, although loses decoupling. ;; TODO DESIGN - finalizers seem to be missing-larkc even though they're referenced by name. Finalization is probably never called? (defstruct (iterator (:conc-name "IT-")) state done next finalize) (defun new-alist-iterator (alist) "[Cyc] Returns an iterator for ALIST. Values returned are tuples of the form (<key> <value>)." ;; cons-to-tuple is missing-larkc, so inlined something here. (new-indirect-iterator (new-list-iterator alist) (lambda (cons) (list (car cons) (cdr cons))))) (defun new-indirect-iterator (iterator &optional (transform #'identity) ;; TODO - missing-larkc function reference (finalize 'iterate-indirect-finalize)) "[Cyc] Return an iterator that transforms the values from another ITERATOR. TRANSFORM is funcalled on each result from ITERATOR." (new-iterator (make-iterator-indirect-state iterator transform) #'default-iterator-done-p #'iterate-indirect-next finalize)) (defun make-iterator-indirect-state (iterator transform) (list iterator transform)) (defun iterate-indirect-next (state) (destructuring-bind (current transform) state (multiple-value-bind (next valid) (iteration-next current) (if valid (progn (unless (eq #'identity transform) (setf next (funcall transform next))) (values next state nil)) (progn (rplaca state :done) (rplacd state nil) (values nil state t)))))) (defparameter *within-print-iterator* nil "[Cyc] Used to suppress initializing the lazy iterator while merely printing it.") (defun new-iterator (state done next &optional (finalize #'true)) "[Cyc] Return a new iterator for incrementally iterating over objects in STATE. STATE is a datastructure which is the initial state of the iteration. DONE must be a unary function which when called on STATE returns non-NIL iff the iteration is complete. NEXT must be a unary function which when called on STATE returns three values: [1] The next raw iteration item from the state [2] The resulting updated state [3] A non-NIL value if the iteration halted prematurely (and we are thus done) FINALIZE is a unary function which is applied to STATE when the iterator is destroyed. While it is not strictly necessary, by convention the output should be non-NIL if and only if the finalization was successful. NB: this function should be robust about finalizing an already-finalized iterator." (make-iterator :state state :done done :next next :finalize finalize)) (defun iteration-done (iterator) "[Cyc] Return NIL iff ITERATOR has not yet been exhausted." (funcall (it-done iterator) (it-state iterator))) (defun* iteration-next-funcall (next-func next-state) (:inline t) ;; This dispatched on next-func symbols to direct distant forward-referencing calls, ;; likely in an optimization attempt. ;; Simplified this to calling next-func directly, as it should be more performant ;; and eliminates the forward-references (funcall next-func next-state)) (defun iteration-next (iterator) "[Cyc] Return the next item in the iteration of ITERATOR. The second value returned is non-NIL iff the value returned is valid." (if (not (funcall (it-done iterator) (it-state iterator))) (multiple-value-bind (raw-item raw-state halted-prematurely) (iteration-next-funcall (it-next iterator) (it-state iterator)) (setf (it-state iterator) raw-state) (if (not halted-prematurely) (values raw-item t) (values nil nil))) (values nil nil))) (defun iteration-next-without-values (iterator &optional invalid-token) "[Cyc] Return the next item in the iteration of ITERATOR or INVALID-TOKEN if the return value is invalid. Unlike ITERATION-NEXT, only 1 value is returned." (if (not (funcall (it-done iterator) (it-state iterator))) (multiple-value-bind (raw-item raw-state halted-prematurely) (iteration-next-funcall (it-next iterator) (it-state iterator)) (setf (it-state iterator) raw-state) (if halted-prematurely invalid-token raw-item)) invalid-token)) ;; TODO - make macro (defun iteration-next-without-values-macro-helper (iterator &optional invalid-token) (iteration-next-without-values iterator invalid-token)) (defun iteration-finalize (iterator) (funcall (it-finalize iterator) (it-state iterator))) ;; TODO - this likely is what DO-ITERATOR does as well in macro form (defun map-iterator (function iterator) "[Cyc] Apply FUNCTION to each object in the iteration of ITERATOR." (loop do (multiple-value-bind (item valid) (iteration-next iterator) (unless valid (return nil)) (funcall function item)))) ;; singleton iterator (defun new-singleton-iterator (item) "[Cyc] Return an iterator that will just return ITEM and halt." (if item (new-iterator item #'null #'iterate-non-null-singleton-next) (new-list-iterator '(nil)))) (defun iterate-non-null-singleton-next (state) (values state nil)) ;; list iterators (defun list-iterator-p (object) "[Cyc] Return T iff OBJECT is a list iterator." (and (iterator-p object) (eq #'iterate-list-next (it-next object)))) (defun new-list-iterator (list) (new-iterator (make-iterator-list-state list) #'iterate-list-done #'iterate-list-next)) (defun get-list-iterator-list (iterator) "[Cyc] Returns the list of elements that are sequenced through by ITERATOR" (the list (it-state iterator))) (defun list-iterator-size (list-iterator) "[Cyc] Return the remaining number of objects to iterate in LIST-ITERATOR." (length (get-list-iterator-list list-iterator))) (defun make-iterator-list-state (list) list) (defun iterate-list-done (state) (null state)) (defun iterate-list-next (state) (values (car state) (cdr state))) ;; hash table iterators ;; TODO DESIGN - would me more efficient as (key . value) (defun new-hash-table-iterator (hash-table) "[Cyc] Returns an iterator for HASH-TABLE. Values returned are tuples of the form (<key> <value>)." (new-iterator (make-iterator-hash-table-state hash-table) #'iterator-hash-table-done #'iterator-hash-table-next)) (defun make-iterator-hash-table-state (hash-table) ;; The original grabbed all the keys, then called GETHASH to find values during iteration. ;; I don't think it's much more expensive to preemptively grab the keys and values, ;; and it's cumulatively expensive to constantly to GETHASH during iteration. ;; Thus, this degenerates to a list iterator. ;; But we'll keep the function identities unique so it won't pass LIST-ITERATOR-P. (let ((pairs nil)) (maphash (lambda (k v) (list k v)) hash-table) pairs)) (defun iterator-hash-table-done (state) (null state)) (defun iterator-hash-table-next (state) (values (car state) (cdr state))) ;; iterator iterators (defun new-iterator-iterator (iterators) "[Cyc] Returns an iterator that sequences through the iterators in ITERATORS." (cond ;; TODO - easy to implement ((null iterators) (missing-larkc 22987)) ((singleton? iterators) (car iterators)) (t (new-iterator (make-iterator-iterator-state iterators) #'iterator-iterator-done #'iterator-iterator-next ;; TODO - missing-larkc function reference 'iterator-iterator-finalize)))) (defun make-iterator-iterator-state (iterators) ;; TODO - this called check-type on each of them, but that's empty in LarKC iterators) (defun iterator-iterator-done (state) "[Cyc] Returns T IFF the iteartors are exhausted. State can be NIL when all of the iterators have been processed, or can be a singleton or can be a list of iterators." (cond ((consp state) (every #'iterator-done state)) ((null state) t) (t (iterator-done state)))) (defun iterator-iterator-next (state) (let ((working-state state) (next nil) (valid-next? nil) (premature-end? nil)) ;; Loop through states until we find one that's not done (until (or valid-next? premature-end?) (let ((current (car working-state))) (if (iterator-done current) (progn (pop working-state) (unless working-state (return)) (setf premature-end? (not working-state))) (multiple-value-bind (value valid?) (iteration-next current) (when valid? (setf next value) (setf valid-next? t)))))) (values next working-state premature-end?))) ;; filter iterator, without values (defun new-filter-iterator-without-values (input-iterator filter-method &optional filter-args invalid-token) "[Cyc] Return an iterator that filters each raw-value from another ITERATOR. RAW-VALUE is returned iff (apply FILTER-METHOD RAW-VALUE FILTER-ARGS) is non-NIL. Unlike NEW-FILTER-ITERATOR, the INPUT-ITERATOR is iterated under the assumption that INVALID-TOKEN is used to indicate an invalid value rather than a second value." (new-iterator (make-filter-iterator-without-values-state input-iterator filter-method filter-args invalid-token) #'default-iterator-done-p #'filter-iterator-without-values-next)) (defun make-filter-iterator-without-values-state (input-iterator filter-method filter-args invalid-token) (list input-iterator filter-method filter-args invalid-token)) (defun filter-iterator-without-values-next (state) (destructuring-bind (current filter-method filter-args invalid-token) state (let ((answer nil) (done nil) (invalid nil)) (while (not done) (let ((next (iteration-next-without-values current invalid-token))) (if (not (eq next invalid-token)) (when (apply filter-method next filter-args) (setf answer next) (setf done t)) (progn (rplaca state :done) (rplacd state nil) (setf done t) (setf invalid t))))) (values answer state invalid)))) (defun default-iterator-done-p (state) (eq :done (elt state 0)))
12,087
Common Lisp
.lisp
237
44.092827
298
0.696143
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
19ca06e64a335d432c600752191df5f1aa1f08a4bf10acd8373d0179811394c0
6,706
[ -1 ]
6,707
queues.lisp
white-flame_clyc/larkc-cycl/queues.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defstruct (queue (:conc-name "Q-")) (num 0 :type fixnum) elements last) (defun create-queue () "[Cyc] Return a new, empty queue." (clear-queue (make-queue))) (defun clear-queue (queue) "[Cyc] Clear QUEUE and return it." (setf (q-num queue) 0) (setf (q-elements queue) nil) (setf (q-last queue) nil)) (declaim (inline queue-empty-p)) (defun queue-empty-p (queue) "[Cyc] Return T iff QUEUE is empty." (null (q-elements queue))) (declaim (inline queue-size)) (defun queue-size (queue) "[Cyc] Return the number of elements in QUEUE." (q-num queue)) (defun enqueue (item queue) "[Cyc] Add ITEM to end of QUEUE. Returns QUEUE." (let ((new-cell (list item))) (if (queue-empty-p queue) (setf (q-elements queue) new-cell) (rplacd (q-last queue) new-cell)) (incf (q-num queue)) (setf (q-last queue) new-cell)) queue) (defun dequeue (queue) "[Cyc] Remove and return the first item in QUEUE." (unless (queue-empty-p queue) (decf (q-num queue)) ;; Manually pop to directly update the last cell (let* ((elements (q-elements queue)) (item (first elements)) (rest (rest elements))) (setf (q-elements queue) rest) (unless rest (setf (q-last queue) nil)) item))) (defun remqueue (item queue &optional (test :eql)) "[Cyc] Remove all occurrences of ITEM from QUEUE. Returns QUEUE." ;; Manually doing this to keep the count updated properly (do ((last (q-last queue)) (back nil) (next nil (rest next))) ((not next)) (if (funcall test (car next) item) (progn (when (eq next last) (setf (q-last queue) back)) (if (eq next (q-elements queue)) (setf (q-elements queue) (rest next)) (rplacd back (rest next)))) (setf back next))) queue) (declaim (inline queue-peek)) (defun queue-peek (queue) (car (q-elements queue))) (defconstant *cfasl-wide-opcode-queue* 131) (defstruct (priority-queue (:conc-name "P-QUEUE-")) (num 0 :type fixnum) max-size rank-func comp-func tree) (defun create-p-queue (max-size rank-func &optional (comp-func #'<)) "[Cyc] Create and return a new priority queue." (make-priority-queue :num 0 :max-size max-size :rank-func rank-func :comp-func comp-func :tree nil)) (declaim (inline p-queue-size)) (defun p-queue-size (priority-queue) "[Cyc] Return the number of elementsin PRIORITY-QUEUE." (p-queue-num priority-queue)) (declaim (inline p-queue-empty-p)) (defun p-queue-empty-p (priority-queue) "[Cyc] Return T iff PRIORITY-QUEUE is empty." (= 0 (p-queue-size priority-queue))) (defun p-queue-full-p (priority-queue) "[Cyc] Return T iff PRIORITY-QUEUE is full." (and (fixnump (p-queue-max-size priority-queue)) (= (p-queue-size priority-queue) (p-queue-max-size priority-queue)))) (defun p-queue-best (priority-queue) (let ((best (btree-find-best (p-queue-tree priority-queue)))) (when (btree-p best) (pq-collision-next (bt-state best))))) (defun p-enqueue (item priority-queue) (let ((bumped? (p-queue-full-p priority-queue))) (if bumped? (missing-larkc 29894) (let ((ans (btree-insert item (funcall (p-queue-rank-func priority-queue) item) (p-queue-tree priority-queue) (p-queue-comp-func priority-queue) #'pq-collision-enter))) (unless (eq ans (p-queue-tree priority-queue)) (setf (p-queue-tree priority-queue) ans)) (incf (p-queue-num priority-queue)) (values priority-queue bumped? nil))))) (defun p-dequeue (priority-queue &optional worst?) (unless (p-queue-empty-p priority-queue) (let* ((remove (if worst? (missing-larkc 29895) (p-queue-best priority-queue))) (ans (btree-remove remove (funcall (p-queue-rank-func priority-queue) remove) (p-queue-tree priority-queue) (p-queue-comp-func priority-queue) #'pq-collision-remove #'pq-collision-empty))) (unless (eq ans (p-queue-tree priority-queue)) (setf (p-queue-tree priority-queue) ans)) (decf (p-queue-num priority-queue)) remove))) (defun pq-collision-enter (item queue) "[Cyc] Returns the list within the queue implementation that results from entering a new item which has the same key as others on this queue list." (nadd-to-end item queue)) (defun pq-collision-next (queue) "[Cyc] Returns the next item within the queue implementation that is obtained from a list of same-named keys." (car queue)) (defun pq-collision-remove (item queue) "[Cyc] Returns the list within the queue implementation that results from removing an item which has the same key as others on this queue list." (delete-first item queue)) (defun pq-collision-empty (queue) "[Cyc] Returns T iff the queue implementation list is empty, in the case where the list would contain same-named keys for queue items." (null queue)) (defstruct lazy-priority-queue ordered-items new-items) (defstruct locked-queue lock queue) (defstruct locked-p-queue lock priority-queue)
6,862
Common Lisp
.lisp
167
34.497006
149
0.659046
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
36055b62c18deee9c339dca90202affea74b9e9f90316b5487600d5a987119f3
6,707
[ -1 ]
6,708
el-grammar.lisp
white-flame_clyc/larkc-cycl/el-grammar.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun el-non-formula-sentence-p (sentence) "[Cyc] Returns T iff SENTENCE is an EL sentence, but not an EL formula. currently (11/9/99) the only such animals are #$True, #$False, and EL variables." (and (el-formula-p sentence) (missing-larkc 6562))) (defun el-literal-p (object) "[Cyc] Like CYCL-LITERAL-P except it only permits EL constructs." (let ((*grammar-permits-hl?* nil)) (cycl-literal-p object)))
1,823
Common Lisp
.lisp
36
47.361111
81
0.765271
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
f462a8b5f71eb52fe3b3a8f57b90924f27ec83f1cf06bb61f6b02e5943cc2667
6,708
[ -1 ]
6,709
constants-high.lisp
white-flame_clyc/larkc-cycl/constants-high.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun create-constant (name &optional external-id) "[Cyc] Return a new constant named NAME with EXTERNAL-ID as the external ID." (kb-create-constant name (or external-id (make-constant-external-id)))) (defun remove-constant (constant) "[Cyc] Remove CONSTANT from the KB." (remove-everything-about-constant constant) (kb-remove-constant constant)) (defun remove-everything-about-constant (constant) "[Cyc] Remove all information (assertions, nats) about CONSTANT from the KB." (let ((*forts-being-removed* (cons constant *forts-being-removed*))) (when (reified-skolem-fn-in-any-mt? constant t t) (missing-larkc 13059)) (remove-dependent-narts constant) (unassert-all-bookkeeping-gafs-on-term constant) (remove-term-indices constant) (tms-remove-kb-hl-supports-mentioning-term constant) (clear-cardinality-estimates constant))) (defun find-constant (name) "[Cyc] Return the constant with NAME, or NIL if not present." (kb-lookup-constant-by-name name)) (defun constant-name (constant) "[Cyc] Return the name of CONSTANT or :UNNAMED." (kb-constant-name constant)) (defun constant-guid (constant) "[Cyc] Return the GUID of CONSTANT." (and (constant-handle-valid? constant) (kb-constant-guid constant))) (defun constant-merged-guid (constant) "[Cyc] Return the merged GUID of CONSTANT." (and (constant-handle-valid? constant) (kb-constant-merged-guid constant))) (defun find-constant-by-guid (guid) "[Cyc] Return the constant with ID, or NIL if not present." (kb-lookup-constant-by-guid guid)) (defun rename-constant (constant new-name) "[Cyc] Rename CONSTANT to have NEW-NAME as its name. The constant is returned." (kb-rename-constant constant new-name)) (defun constant-internal-id (constant) "[Cyc] Return the internal id of CONSTANT." (constant-suid constant)) (defun find-constant-by-internal-id (id) "[Cyc] Return the constant with internal ID, or NIL if not present." (find-constant-by-suid id)) (defun installed-constant-p (object) "[Cyc] Return T iff OBJECT is a constant that has its IDs installed." (valid-constant-handle? object)) (defun uninstalled-constant-p (object) "[Cyc] Return T iff OBJECT is a constant that does not have its IDs installed." (and (constant-p object) (not (installed-constant-p object)))) (defun new-constant-internal-id-threshold () "[Cyc] Return the internal ID where new constants started." (new-constant-suid-threshold)) (defun constant-external-id (constant) "[Cyc] Return the external id of CONSTANT." (constant-guid constant)) (defun find-constant-by-external-id (external-id) "[Cyc] Return the constant with EXTERNAL-ID, or NIL if not present." (find-constant-by-guid external-id)) (defun constant-external-id-p (object) "[Cyc] Return T iff OBJECT could be an external constant ID." (guid-p object)) (defun constant-external-id-< (constant1 constant2) "[Cyc] Return T iff CONSTANT1 has a smaller external id than CONSTANT2" (let ((guid-1 (constant-guid constant1)) (guid-2 (constant-guid constant2))) (cond ((and guid-1 guid-2) (guid< guid-1 guid-2)) ((not (or guid-1 guid-2)) nil) (t (null guid-1))))) (defun constant-info-from-guid-strings (guid-string-list) "[Cyc] Returns a list of constant info-items corresponding to the GUID-LIST. Each ifno item is a list of guid-string and name." (let ((constant-info-list nil)) (dolist (guid-string guid-string-list) (let ((constant (find-constant-by-external-id (string-to-guid guid-string)))) (push (and constant (list guid-string (constant-name constant))) constant-info-list))) (nreverse constant-info-list))) (defun make-constant-external-id () (make-constant-guid)) (defun make-consatnt-guid () (new-guid)) (deflexical *constant-legacy-guid-date* '(7 20 1969)) (defun constant-legacy-id-p (object) (integerp object)) (defparameter *constant-dump-id-table* nil) (defun find-constant-by-dump-id (dump-id) (find-constant-by-internal-id dump-id))
5,445
Common Lisp
.lisp
114
44.298246
130
0.744842
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
3fd37165dc5b3863c73dfaff4e00a85ae17154573e898c9179af09460c188052
6,709
[ -1 ]
6,710
kb-indexing-declarations.lisp
white-flame_clyc/larkc-cycl/kb-indexing-declarations.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (deflexical *default-intermediate-index-equal-test* #'eq) (defglobal *kb-indexing-declaration-store* (make-hash-table :test #'eq)) (defun* kb-indexing-declaration-store () (:inline t) *kb-indexing-declaration-store*) (defun* add-index-to-kb-indexing-declaration-store (index plist) (:inline t) (setf (gethash index *kb-indexing-declaration-store*) plist)) (defun* get-index-from-kb-indexing-declaration-store (index) (:inline t) (gethash index *kb-indexing-declaration-store*)) (defun find-index-by-top-level-key (top-level-key) "[Cyc] Returns the index with a top-level key of TOP-LEVEL-KEY." (let ((index (get-index-from-kb-indexing-declaration-store top-level-key))) (if (and index (eq top-level-key (get-index-prop index :top-level-key))) index (dohash (index plist (kb-indexing-declaration-store)) (when (eq top-level-key (get-index-prop index :top-level-key)) (return index)))))) (defun* get-index-key-prop (key-info indicator &optional default) (:inline t) (getf key-info indicator default)) (defun* get-index-prop (index indicator) (:inline t) (getf (get-index-from-kb-indexing-declaration-store index) indicator)) (defun* declare-index (index plist) (:inline t) "[Cyc] See below for an explanation of what fields go in the plist, what they mean, and a bunch of examples." (add-index-to-kb-indexing-declaration-store index plist)) (defun index-equality-test-for-keys (keys) "[Cyc] Return the test appropriate for distinguishing the last key in KEYS. KEYS: a list of keys, starting from the top level." (destructuring-bind (top-level-key . rest-keys) keys (let ((index (find-index-by-top-level-key top-level-key))) (must index "Could not find an index with top-level key ~s" top-level-key) (let* ((key-info-list (get-index-prop index :keys)) (levels-deep (length rest-keys)) (key-info-for-this-level (nth levels-deep key-info-list)) (equal-test (get-index-key-prop key-info-for-this-level :equal-test *default-intermediate-index-equal-test*))) equal-test))))
3,568
Common Lisp
.lisp
64
50.578125
111
0.724842
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
a68723785ec8f2bbf01239136c6a611ded0894a691be5390abf720b48e6a6f14
6,710
[ -1 ]
6,711
deduction-manager.lisp
white-flame_clyc/larkc-cycl/deduction-manager.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defglobal *deduction-content-manager* :uninitialized "[Cyc] The KB object manager for deductions.") (deflexical *deduction-lru-size-percentage* 8 "[Cyc] This is a guess based on *ASSERTION-LRU-SIZE-PERCENTAGE*.") (defun setup-deduction-content-tagle (size exact?) (setf *deduction-content-manager* (new-kb-object-manager "deduction" size *deduction-lru-size-percentage* #'load-deduction-def-from-cache exact? ))) (defun clear-deduction-content-table () (clear-kb-object-content-table *deduction-content-manager*)) (defun* cached-deduction-count () (:inline t) "[Cyc] Return the number of deductions whose content is cached in memory." (cached-kb-object-count *deduction-content-manager*)) (defun* deduction-content-completely-cached? () (:inline t) (= (deduction-count) (cached-deduction-count))) (defun* lookup-deduction-content (id) (:inline t) (lookup-kb-object-content *deduction-content-manager* id)) (defun* register-deduction-content (id deduction-content) (:inline t) "[Cyc] Note that ID will be used as the id for DEDUCTION-CONTENT." (register-kb-object-content *deduction-content-manager* id deduction-content)) (defun* deregister-deduction-content (id) (:inline t) "[Cyc] Note that ID is not in use as a NART id, i.e. points to no hl-formula." (deregister-kb-object-content *deduction-content-manager* id)) (defun* mark-deduction-content-as-muted (id) (:inline t) (mark-kb-object-content-as-muted *deduction-content-manager* id)) (defun swap-out-all-pristine-deductions () (swap-out-all-pristine-kb-objects-int *deduction-content-manager*)) (defun initialize-deduction-hl-store-cache () (initialize-kb-object-hl-store-cache *deduction-content-manager* "deduction" "deduction-index"))
3,274
Common Lisp
.lisp
57
52.175439
107
0.736595
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
3c268f0dc64af2e807724730b10b71a6cece35ab8e15540e646f134709b1e9de
6,711
[ -1 ]
6,712
kb-gp-mapping.lisp
white-flame_clyc/larkc-cycl/kb-gp-mapping.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defparameter *mapping-arg-swap* nil) (defun* dgaigp-binary? (predicate) (:inline t) (binary? predicate)) (defun gp-map-arg-index (function term arg predicate) "[Cyc] Like MAP-ARG-INDEX, except all spec-predicates of PREDICATE are relevant, and :true is assumed for TRUTH." (catch :mapping-done ;; TODO - pred macro, similar to mt macro? (let ((*relevant-pred-function* #'relevant-pred-is-spec-pred) (*pred* predicate)) (kmu-do-index-iteration (assertion gaf-arg (term arg predicate) (:gaf :true nil)) (funcall function assertion))) (when (dgaigp-binary? predicate) ;; TODO - pred macro (let ((*relevant-pred-function* #'relevant-pred-is-spec-inverse) (*pred* predicate)) (kmu-do-index-iteration (assertion gaf-arg (term (binary-arg-swap arg) predicate) (:gaf :true nil)) (let ((*mapping-arg-swap* (not *mapping-arg-swap*))) (funcall function assertion))))))) (defun num-spec-pred-index (pred &optional mt) "[Cyc] only use this where PRED is a predicate." (let ((count 0)) (possibly-in-mt (mt) (dolist (spec-pred (all-spec-preds pred)) (incf count (Num-predicate-extent-index spec-pred)))) count))
2,622
Common Lisp
.lisp
52
45.788462
115
0.726737
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
eebda8f179869314cb50b86e0d098b3c9abdd9eea0c862f802f1b6eaec4bf5b4
6,712
[ -1 ]
6,713
hl-interface-infrastructure.lisp
white-flame_clyc/larkc-cycl/hl-interface-infrastructure.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defvar *hl-store-modification-and-access* :local-local "[Cyc] Where HL store modification and access should be done. There are four valid values: :local-local (modify and access locally) :remote-remote (modify and access remotely) :both-local (modify and access locally, also modify remotely) :both-remote (modify and access remotely, also modify locally) :none-local (access locally, do not modify)") (defvar *override-hl-store-remote-access?* nil "[Cyc] A non-NIL value means that access will be done locally regardless of the valeu of *hl-store-modification-and-access*.") (defun hl-modify-local? () (member-eq? *hl-store-modification-and-access* '(:local-local :both-local :both-remote))) (defun hl-modify-remote? () (member-eq? *hl-store-modification-and-access* '(:remote-remote :both-local :both-remote))) (defun hl-modify-anywhere? () (member-eq? *hl-store-modification-and-access* '(:local-local :remote-remote :both-local :both-remote))) (defun hl-access-remote? () (and (not *override-hl-store-remote-access?*) (member-eq? *hl-store-modification-and-access* '(:remote-remote :both-remote)))) (defglobal *remote-hl-store-image* nil "[Cyc] The remote HL store image") (defglobal *remote-hl-store-connection-pool* (create-queue)) (deflexical *remote-hl-store-connection-pool-lock* (bt:make-lock "Remote HL Store Connection Pool Lock")) (deflexical *remote-hl-store-connection-pool-max-size* 9) (defun* define-hl-modifier-preamble () (:inline t) "[Cyc] Code to execute before the internals of the hl-modifier (or hl-creator)." (clear-hl-store-dependent-caches)) (defun* define-hl-modifier-postamble () (:inline t) "[Cyc] Code to execute before the internals of the hl-modifier (or hl-creator)." ;; probably should be "after" in the comment? (clear-hl-store-dependent-caches)) (defmacro define-hl-creator (name arglist documentation-string type-declarations &body body) ;; Implementation from assertions-interface kb-create-assertion. ;; Due to the way the args were listed in the java, this seems to subsume the defun, too `(defun ,name ,arglist ,documentation-string ,type-declarations (define-hl-modifier-preamble) ;; TODO - take care of &optional, &key, etc in a general utility (note-hl-modifier-invocation ',name ,@arglist) (when (hl-modify-anywhere?) (bt:with-lock-held (*hl-lock*) (prog1 (progn ,@body) (define-hl-modifier-postamble)))))) (defmacro define-hl-modifier (name arglist documentation-string type-declarations &body body) ;; Implementation from assertions-interface kb-remove-assertion. `(defun ,name ,arglist ,documentation-string ,type-declarations (define-hl-modifier-preamble) ;; TODO - take care of &optional, &key, etc in a general utility (note-hl-modifier-invocation ',name ,@arglist) (when (hl-modify-remote?) (missing-larkc 29510)) (when (hl-modify-local?) (let ((*override-hl-store-remote-access?* t)) (bt:with-lock-held (*hl-lock*) ,@body))))) (defparameter *hl-store-error-handling-mode* nil) (defglobal *hl-store-iterators* (make-hash-table)) (declaim (fixnum *next-hl-store-iterator-id*)) (defglobal *next-hl-store-iterator-id* 0) (defun* candidate-next-hl-store-iterator-id () (:inline t) (let* ((retval *next-hl-store-iterator-id*) (next (1+ retval))) (declare (fixnum retval next)) (setf *next-hl-store-iterator-id* (if (= most-positive-fixnum next) 0 next)) retval)) (defun new-hl-store-iterator-id () (loop for next-id = (candidate-next-hl-store-iterator-id) while (lookup-hl-store-iterator next-id) finally (return next-id))) ;; TODO - maybe just use a synchronized hashtable instead? (deflexical *hl-store-iterator-lock* (bt:make-lock "HL Store Iterator Lock")) (defun note-hl-store-iterator (iterator) (bt:with-lock-held (*hl-store-iterator-lock*) (let ((id (new-hl-store-iterator-id))) (setf (gethash id *hl-store-iterators*) iterator) id))) (defun lookup-hl-store-iterator (id) (gethash id *hl-store-iterators*)) (defun unnote-hl-store-iterator (id) (bt:with-lock-held (*hl-store-iterator-lock*) (remhash id *hl-store-iterators*))) ;; TODO DESIGN - this uses eval (defun new-hl-store-iterator-int (form) (let ((iterator (eval form))) (and (iterator-p iterator) (note-hl-store-iterator iterator)))) (defun hl-store-iterator-next-int (id) (let ((iterator (lookup-hl-store-iterator id))) (if iterator (multiple-value-bind (next valid?) (iteration-next iterator) (list next valid?)) (list nil nil)))) (defun hl-store-iterator-done-int (id) (let ((iterator (lookup-hl-store-iterator id))) (if iterator (iteration-done iterator) t))) (defun hl-store-iterator-destroy-int (id) (let ((iterator (lookup-hl-store-iterator id))) (if iterator (progn (unnote-hl-store-iterator id) (iteration-finalize iterator)) t))) (defun new-hl-store-iterator (form &optional (buffer-size 1)) (let ((id (if (hl-access-remote?) (missing-larkc 29558) (new-hl-store-iterator-int form)))) (if (= buffer-size 1) (create-hl-store-iterator id) (missing-larkc 29503)))) (defun create-hl-store-iterator (id) (new-iterator id #'hl-store-iterator-done? #'hl-store-iterator-next #'hl-store-iterator-destroy)) (defun hl-store-iterator-done? (id) (if (hl-access-remote?) (missing-larkc 29559) (hl-store-iterator-done-int id))) (defun hl-store-iterator-next (id) (destructuring-bind (next valid?) (if (hl-access-remote?) (missing-larkc 29560) (hl-store-iterator-next-int id)) (values next id (not valid?)))) (defun hl-store-iterator-destroy (id) (if (hl-access-remote?) (missing-larkc 29561) (hl-store-iterator-destroy-int id))) (defglobal *hl-transcript-stream* nil) (defun note-hl-modifier-invocation (name &optional (arg1 :unprovided) (arg2 :unprovided) (arg3 :unprovided) (arg4 :unprovided) (arg5 :unprovided)) (declare (ignore name arg1 arg2 arg3 arg4 arg5)) (when (streamp *hl-transcript-stream*) '(let ((hlop (missing-larkc 29566))) (cfasl-output-externalized hlop *hl-transcript-stream*)) (missing-larkc 29566)))
8,025
Common Lisp
.lisp
169
41.426036
130
0.686234
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
e95a428ce44c8e538685d742a5235945a97a5cb22e602d1e6f59e6c036cd5f93
6,713
[ -1 ]
6,714
cache-utilities.lisp
white-flame_clyc/larkc-cycl/cache-utilities.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; cachemtr = cache-metrics ;; mcache = metered-cache (defun* cache-strategy-gather-metrics (strategy) (:inline t) "[Cyc] Allocate a metrics object and then begin using it to gather metrics." (cache-strategy-object-gather-metrics strategy (new-cache-metrics))) (defun* cache-strategy-p (object) (:inline t) "[Cyc] Determine whether the object is a cache strategy or not." (cache-strategy-object-p object)) (defun* cache-strategy-note-cache-miss (strategy) (:inline t) "[Cyc] If metrics are being kept, then note the cache miss. Otherwise, the operation is a NO-OP." (when (cache-strategy-keeps-metrics-p strategy) (cache-metrics-note-miss (cache-strategy-get-metrics strategy))) strategy) (defun* cache-metrics-note-miss (metrics) (:inline t) "[Cyc] Update the metrics to reflect that the cache lookup resulted in a miss." (incf (cachemtr-miss-count metrics))) (defun* cache-strategy-note-reference (strategy object) (:inline t) "[Cyc] Inform the cache strategy tracking system that the object mentioned was referenced. Objects that are not currently being tracked will be ignored." (when (cache-strategy-tracked? strategy object) (cache-strategy-object-note-reference strategy object)) strategy) (defun* cache-strategy-tracked? (strategy object) (:inline t) "[Cyc] Determine whether this object is currently being tracked in the cache." (cache-strategy-object-tracked? strategy object)) (defgeneric cache-strategy-object-tracked? (strategy object) (:documentation "[Cyc] By default, we do not know whether the object is tracked.")) (defun* cache-strategy-mcache-object-note-reference (mcache object) (:inline t) (cache-set-without-values (mcache-cache mcache) object object)) (defun* cache-strategy-mcache-object-tracked? (mcache object) (:inline t) (cache-contains-key-p (mcache-cache mcache) object)) (defgeneric cache-strategy-object-note-reference (strategy object) (:documentation "[Cyc] By default, we do not know how to note a reference.")) (defun* cache-strategy-mcache-object-keeps-metrics-p (mcache) (:inline t) (cache-metrics-p (mcache-metrics mcache))) (defun* cache-strategy-mcache-object-get-metrics (mcache) (:inline t) (mcache-metrics mcache)) (defun cache-strategy-note-cache-hits (strategy several) "[Cyc] If metrics are being kept, then note the cache hit. Otherwise the operation is a NO-OP." (when (cache-strategy-keeps-metrics-p strategy) (let ((metrics (cache-strategy-get-metrics strategy))) (dotimes (i several) (cache-metrics-note-hit metrics)))) strategy) (defun* cache-strategy-note-cache-hit (strategy) (:inline t) "[Cyc] If metrics are being kept, then note the cache hit. Otherwise the operation is a NO-OP." (when (cache-strategy-keeps-metrics-p strategy) (cache-metrics-note-hit (cache-strategy-get-metrics strategy))) strategy) (defun* cache-strategy-get-metrics (strategy) (:inline t) "[Cyc] Return CACHE-METRICS-P or NIL if no metrics are being gathered." (and (cache-strategy-keeps-metrics-p strategy) (cache-strategy-object-get-metrics strategy))) (defgeneric cache-strategy-object-get-metrics (strategy) (:documentation "[Cyc] By default we do not know how to get the metrics.")) (defun* cache-metrics-note-hit (metrics) (:inline t) "[Cyc] Update the metrics to reflect that the cache lookup resulted in a hit." (incf (cachemtr-hit-count metrics)) metrics) (defun* cache-strategy-keeps-metrics-p (strategy) (:inline t) "[Cyc] Determine if the cache strategy is currently gathering metrics or not." (cache-strategy-object-keeps-metrics-p strategy)) (defgeneric cache-strategy-object-keeps-metrics-p (strategy) (:documentation "[Cyc] By default, we do not know whether the strategy is keeping metrics or not.")) (defun* cache-strategy-track (strategy object) (:inline t) "[Cyc] Track this object in the cache. If CACHE-STRATEGY-CACHE-FULL-P is TRUE, then select an object to untrack and return that no longer tracked object; otherwise return the newly tracked object." (cache-strategy-object-track strategy object)) (defgeneric cache-strategy-object-track (strategy object) (:documentation "[Cyc] By default, we do not know how to track an object.")) (defgeneric cache-strategy-object-p (object) (:documentation "[Cyc] By default, nothing is a cache strategy object.")) (defstruct (cache-metrics (:conc-name "CACHEMTR-")) hit-count miss-count) (defun new-cache-metrics () "[Cyc] Create a new empty cache metrics infrastructure." (let ((metrics (make-cache-metrics))) (reset-cache-metrics-counts metrics) metrics)) (defun reset-cache-metrics-counts (metrics &optional (hits 0) (misses 0)) "[Cyc] Resaet the counts in the cache metrics." (setf (cachemtr-hit-count metrics) hits) (setf (cachemtr-miss-count metrics) misses) metrics) (defconstant *cfasl-wide-opcode-cache-metrics* 129) ;; TODO DESIGN - this is a mess for dispatching through behavior. Put a slot for the metrics right on the cache objects, or even both metrics slots right in it. (defstruct (metered-cache (:conc-name "MCACHE-")) cache metrics) (defun cache-strategy-mcache-object-track (mcache object) (multiple-value-bind (key value dropped-p) (cache-set-return-dropped (mcache-cache mcache) object object) (declare (ignore value)) (if dropped-p key object))) (defun* new-metered-cache (cache) (:inline t) "[Cyc] Allocate the new metered cache, leaving the metrics slot empty for now." (make-metered-cache :cache cache)) (defun* new-metered-preallocated-cache (capacity &optional (test #'eql)) (:inline t) "[Cyc] Allocate a new metered cache for a pre-allocated cache of the specified capacity and test-type." (new-metered-cache (new-preallocated-cache capacity test))) (defun* cache-strategy-mcache-object-gather-metrics (mcache metrics) (:inline t) (setf (mcache-metrics mcache) metrics) mcache) (defstruct recording-cache-strategy-facade cache-strategy records timestamper) ;; Moved these below the metered-cache defstruct (defmethod cache-strategy-object-keeps-metrics-p ((strategy metered-cache)) (cache-strategy-mcache-object-keeps-metrics-p strategy)) (defmethod cache-strategy-object-tracked? ((strategy metered-cache) object) (cache-strategy-mcache-object-tracked? strategy object)) (defmethod cache-strategy-object-note-reference ((strategy metered-cache) object) (cache-strategy-mcache-object-note-reference strategy object)) (defmethod cache-strategy-object-get-metrics ((strategy metered-cache)) (cache-strategy-mcache-object-get-metrics strategy)) (defmethod cache-strategy-object-track ((strategy metered-cache) object) (cache-strategy-mcache-object-track strategy object)) (defmethod cache-strategy-object-p ((object metered-cache)) "[Cyc] METERED-CACHE-P has a cache strategy implementation." t) (defmethod cache-strategy-object-gather-metrics ((strategy metered-cache) metrics) (cache-strategy-mcache-object-gather-metrics strategy metrics))
8,401
Common Lisp
.lisp
152
52.25
199
0.765986
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
cd2e3fb12dea8b53374f2c66fb3209e65205ac40cdec53a695db499c0b70c714
6,714
[ -1 ]
6,715
deductions-low.lisp
white-flame_clyc/larkc-cycl/deductions-low.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO - uses of deduction-id indicate going from object -> id -> manager lookup, which is roundabout and inefficient. (defstruct (deduction-content (:conc-name "D-CONTENT-")) tv assertion supports) (defun create-deduction-content (id assertion supports) (let ((deduction-content (make-deduction-content :tv :unknown :assertion assertion :supports supports))) (register-deduction-content id deduction-content) deduction-content)) (defun destroy-deduction-content (id) (when-let ((deduction-content (lookup-deduction-content id))) (deregister-deduction-content id) (setf (d-content-tv deduction-content) (setf (d-content-assertion deduction-content) (setf (d-content-supports deduction-content) nil))) t)) (defun* lookup-deduction-tv (id) (:inline t) (d-content-tv (lookup-deduction-content id))) (defun* lookup-deduction-assertion (id) (:inline t) (d-content-assertion (lookup-deduction-content id))) (defun* lookup-deduction-supports (id) (:inline t) (d-content-supports (lookup-deduction-content id))) (defun* se-deduction-tv (id new-tv) (:inline t) (setf (d-content-tv (lookup-deduction-content id)) new-tv) (mark-deduction-content-as-muted id)) (defun load-deduction-content (deduction stream) (let* ((id (deduction-id deduction)) (tv (cfasl-input stream)) (assertion (cfasl-input stream)) (supports (cfasl-input stream))) (load-deduction-content-int id assertion supports tv)) deduction) (defun load-deduction-content-int (id assertion supports tv) (let ((deduction-content (create-deduction-content id assertion supports))) (setf (d-content-tv deduction-content) tv) id)) (defun kb-create-deduction-kb-store (assertion supports truth) (let* ((internal-id (make-deduction-id)) (deduction (make-deduction-shell internal-id))) (kb-create-deduction-int deduction internal-id assertion supports truth) internal-id)) (defun kb-create-deduction-int (deduction internal-id assertion supports truth) (let ((tv (tv-from-truth-strength truth :default))) (create-deduction-content internal-id assertion supports) (reset-deduction-tv deduction tv) (when (assertion-p assertion) (add-new-assertion-argument assertion deduction)) (add-deduction-dependents deduction))) (defun add-deduction-dependents (deduction) (dolist (support (deduction-supports-internal deduction)) (cond ((assertion-p support) (add-assertion-dependent support deduction)) ((kb-hl-support-p support) (kb-hl-support-add-dependent support deduction))))) (defun kb-remove-deduction-internal (deduction) (let ((id (deduction-id deduction))) (destroy-deduction-content id) (deregister-deduction-id id)) (free-deduction deduction)) (defun remove-deduction-dependents (deduction) (dolist (support (deduction-supports-internal deduction)) (cond ((valid-assertion? support) (remove-assertion-dependent support deduction)) ((valid-kb-hl-support? support) (kb-hl-support-remove-dependent support deduction))))) (defun* reset-deduction-tv (deduction new-tv) (:inline t) "[Cyc] Primitively change the tv of DEDUCTION to NEW-TV." (set-deduction-tv (deduction-id deduction) new-tv)) (defun kb-set-deduction-strength-internal (deduction new-strength) (let* ((truth (argument-truth deduction)) (new-tv (tv-from-truth-strength truth new-strength))) (reset-deduction-tv deduction new-tv))) (defun find-deduction-internal (assertion supports truth) (cond ((assertion-p assertion) (dolist (argument (assertion-arguments assertion)) (when (and (deduction-p argument) (deduction-matches-specification argument assertion supports truth)) (return argument)))) ((kb-hl-support-p assertion) (missing-larkc 11006)))) (defun deduction-matches-specification (deduction assertion supports &optional (truth :true)) (and (equal assertion (deduction-assertion deduction)) (eq truth (argument-truth deduction)) (deduction-supports-equal supports (deduction-supports deduction)))) (defun* deduction-assertion-internal (deduction) (:inline t) (lookup-deduction-assertion (deduction-id deduction))) (defun* deduction-tv (deduction) (:inline t) "[Cyc] Return the tv of DEDUCTION." (lookup-deduction-tv (deduction-id deduction))) (defun* deduction-supports-internal (deduction) (:inline t) (lookup-deduction-supports (deduction-id deduction))) (defun* deduction-truth-internal (deduction) (:inline t) (tv-truth (deduction-tv deduction))) (defun* deduction-strength-internal (deduction) (:inline t) (tv-strength (deduction-tv deduction)))
6,270
Common Lisp
.lisp
122
45.696721
119
0.724132
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
70b1677e11db13fe16ed503792d325480dfe99a5cdbbec85d795d87021e19fdb
6,715
[ -1 ]
6,716
eval-in-api.lisp
white-flame_clyc/larkc-cycl/eval-in-api.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO DESIGN - setting this to T is not supported (defvar *eval-in-api?* nil "[Cyc] Process all API commands using a SubL interpreter which validates API function calls.") (defun cyc-api-eval (api-request) "[Cyc] Evaluate API-REQUEST under the evaluation assumptions of the CYC-API server" (if *eval-in-api?* (missing-larkc 10828) (eval-in-api-subl-eval api-request))) (defun possibly-cyc-eval (api-request) "[Cyc] Call EVAL on API-REQUEST. Functions defined via the Cyc API are also supported." (if *eval-in-api?* (missing-larkc 10829) (eval api-request))) (defun possibly-cyc-api-function-spec-p (object) "[Cyc] Return T iff OBJECT is suitable for FUNCALL. Functions defined via the Cyc API are also supported." (or (function-spec-p object) (and (symbolp object) (api-function-p object)))) (defun possibly-cyc-api-funcall (func &rest args) "[Cyc] Funcall FUNC on ARGS. Functions defined via the Cyc API are also supported." ;; Note that the original had fixed arity funcall-1, funcall-2, etc (if (function-spec-p func) (apply func args) (cyc-api-eval (cons func (mapcar #'quotify args))))) (defglobal *eval-in-api-mutable-global* nil) (defun register-api-mutable-global (var) (push var *eval-in-api-mutable-global*) var) (defglobal *eval-in-api-immutable-global* nil) (defun register-api-immutable-global (var) (push var *eval-in-api-immutable-global*) var) (defparameter *eval-in-api-env* nil "[Cyc] The association list of API variables and bound values.") (defglobal *api-special-verify-table* (make-hash-table :test #'eq)) (defun register-api-special-verify (operator handler) (setf (gethash operator *api-special-verify-table*) handler) operator) (defglobal *api-function-table* (make-hash-table :test #'eq)) (defun api-function-p (operator) (gethash operator *api-function-table*)) (defglobal *api-macro-table* (make-hash-table :test #'eq)) (defglobal *subl-eval-method* 'eval) (defun eval-in-api-subl-eval (form) "[Cyc] Trampoline to EVAL from within EVAL-IN-API" ;; TODO - this is defined in Eval.Java, but nothing seems to use it. Probably configures how full SubL runs EVAL, especially if there are EVAL forms inside FORM. ;;(let ((*evaluator-method* *subl-eval-method*))) (funcall *subl-eval-method* form)) (defparameter *eval-in-api-traced-fns* nil "[Cyc] The lsit of functions to be traced.") (defparameter *eval-in-api-trace-log* nil "[Cyc] The log of trace events.") (defun initialize-eval-in-api-env () nil) (defparameter *eval-in-api-level* -1 "[Cyc] Indicates top level evaluation when value equals 0.") (defparameter *eval-in-api-function-level* -1 "[Cyc] Indicates function level for diagnostic trace output.") (defparameter *eval-in-api-macro-stack* nil "[Cyc] The stack of macros that we're currently evalling in the context of.") (defparameter *verify-in-api-verbose-mode?* nil) (defparameter *verify-in-api-bound-symbols* nil "[Cyc] A list of the symbols introduced in the form being verified.") (defparameter *verify-in-api-fbound-symbols* nil "[Cyc] A list of the function symbols introduced in the form being verified.") (defparameter *verify-in-api-macro-stack* nil "[Cyc] The stack of macros that we're currently verifying in the context of.") (deflexical *api-user-variables* nil "[Cyc] The dictionary of persistent api user variables and values.")
4,814
Common Lisp
.lisp
99
45.606061
164
0.750428
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
299d1087f2e9b47fed7189cd02a95e73809b76046dc29469310b09128cd03d24
6,716
[ -1 ]
6,717
constants-interface.lisp
white-flame_clyc/larkc-cycl/constants-interface.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun kb-create-constant (name external-id) "[Cyc] Return a new constant named NAME with EXTERNAL-ID. If NAME is :UNNAMED, returns a constant with no name." (define-hl-modifier-preamble) (note-hl-modifier-invocation 'kb-create-constant name external-id) (when (hl-modify-anywhere?) (bt:with-lock-held (*hl-lock*) (prog1 (if (hl-modify-remote?) (missing-larkc 32155) (kb-create-constant-local name external-id)) (define-hl-modifier-postamble))))) (defun kb-create-constant-local (name external-id) (find-constant-by-internal-id (kb-create-constant-kb-store name external-id))) (defun kb-remove-constant (constant) "[Cyc] Remove CONSTANT from the KB." (let ((result nil)) (define-hl-modifier-preamble) (note-hl-modifier-invocation 'kb-remove-constant constant) (when (hl-modify-remote?) (setf result (missing-larkc 29543))) (if (hl-modify-local?) (let ((*override-hl-store-remote-access?* t)) (bt:with-lock-held (*hl-lock*) (kb-remove-constant-internal constant))) result))) (defun kb-lookup-constant-by-name (name) "[Cyc] Return the constant named NAME, if it exists. Return NIL otherwise." (if (hl-access-remote?) (missing-larkc 29544) (constant-shell-from-name name))) (defun kb-constant-name (constant) "[Cyc] Return the name for CONSTANT." (if (hl-access-remote?) (missing-larkc 29545) (constant-name-internal constant))) (defun kb-lookup-constant-by-guid (guid) "[Cyc] Return the constant with GUID, if it exists. Return NIL otherwise." (if (hl-access-remote?) (missing-larkc 29546) (lookup-constant-by-guid guid))) (defun kb-constant-guid (constant) "[Cyc] Return the external ID for CONSTANT." (if (hl-access-remote?) (missing-larkc 29548) (constant-merged-guid-internal constant))) (defun kb-rename-constant (constant new-name) "[Cyc] Rename CONSTANT to have NEW-NAME as its name. The constant is returned." (let ((result nil)) (define-hl-modifier-preamble) (note-hl-modifier-invocation 'kb-rename-constant constant new-name) (when (hl-modify-remote?) (setf result (missing-larkc 29549))) (if (hl-modify-local?) (let ((*override-hl-store-remote-access?* t)) (bt:with-lock-held (*hl-lock*) ;; TODO - this was stored to an unused variable, "old_name" (constant-name constant) (kb-rename-constant-internal constant new-name))) result)))
3,926
Common Lisp
.lisp
86
40.55814
82
0.713386
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
f12a393cce7f8fd7e6f6b42776ca8234f4ba1f67a14609d5108949bd8389a80e
6,717
[ -1 ]
6,718
tcp-server-utilities.lisp
white-flame_clyc/larkc-cycl/tcp-server-utilities.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO - all the missing-larkc in this file should be easily implementable. ;; TODO - this originally SubL file has functionality overlap with port mappings that the originally Java tcp.lisp file has. Combine the two. (deflexical *tcp-server-lock* (bt:make-lock "TCP Server Lock")) (defparameter *remote-address* nil "[Cyc] Within a TCP server handler, this is bound to an integer representing the socket's remote machine IP address.") (defparameter *remote-hostname* nil "[Cyc] WIthin a TCP server handler, this is bound to a string representing the socket's remote machine hostname") (defun tcp-port-p (object) "[Cyc] Return T iff OBJECT is a valid integer for a TCP port." (and (fixnump object) (eq object (logand 65535 object)))) (defun enable-tcp-server (type port) "[Cyc] Enable a new TCP server of TYPE bound to PORT. TYPE must have already been declared via DEFINE-TCP-SERVER. Any TCP server currently bound to PORT is first disabled." (when (> (disable-tcp-server port) 0) (sleep 1)) (let ((tcp-server (new-tcp-server type port))) (register-tcp-server tcp-server) tcp-server)) (defun disable-tcp-server (designator) "[Cyc] Disable all TCP servers specified by DESIGNATOR. Returns the total number of servers disabled. If DESIGNATOR is a TCP-SERVER-P, disable that server. If DESIGNATOR is a TCP-PORT-P, disable the server at that port. Otherwise, disable all servers with DESIGNATOR as their type." (cond ((tcp-server-p designator) (missing-larkc 31593)) ((tcp-port-p designator) (alexandria:if-let ((tcp-server (find-tcp-server-by-port designator))) (disable-tcp-server tcp-server) 0)) (t (missing-larkc 31597)))) (defun validate-all-tcp-servers () (missing-larkc 31596)) (defstruct (tcp-server (:conc-name "TCPS-")) type ;; NIL if disabled (port nil :type (or null fixnum)) process) (defun* tcp-server-port (tcp-server) (:inline t) "[Cyc] Return the port of TCP-SERVER, or NIL if disabled." (tcps-port tcp-server)) (defun new-tcp-server (type port) (let ((handler (tcp-server-type-handler type))) (make-tcp-server :type type :port port :process (start-tcp-server-process type port handler)))) (defglobal *all-tcp-servers* nil) (defun find-tcp-server-by-port (port) (find port *all-tcp-servers* :key #'tcp-server-port)) (defun all-tcp-servers () "[Cyc] Return a list of all TCP servers that are currently enabled." (copy-list *all-tcp-servers*)) (defun register-tcp-server (tcp-server) (bt:with-lock-held (*tcp-server-lock*) (push tcp-server *all-tcp-servers*))) (defglobal *tcp-server-type-table* nil) (defun register-tcp-server-type (type handler &optional (mode :text)) "[Cyc] Register that TCP servers of TYPE use HANDLER with MODE." (deregister-tcp-server-type type) (bt:with-lock-held (*tcp-server-lock*) (push (list type handler mode) *tcp-server-type-table*))) (defun deregister-tcp-server-type (type) (bt:with-lock-held (*tcp-server-lock*) (deletef type *tcp-server-type-table* :key #'first))) (defun tcp-server-type-handler (type) (second (find type *tcp-server-type-table* :key #'first))) (defun start-tcp-server-process (type port handler) "[Cyc] Method for starting a new TCP server of TYPE at PORT which has HANDLER." (declare (ignore type)) (start-tcp-server port handler))
4,829
Common Lisp
.lisp
98
45.234694
142
0.731983
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
659fd7f8d5808b7d89e6e1836e79fb7b4d2f4f4fb3a9fd02021f12b8ed66a49a
6,718
[ -1 ]
6,719
constant-index-manager.lisp
white-flame_clyc/larkc-cycl/constant-index-manager.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defglobal *constant-index-manager* :uninitialized "[Cyc] The KB object manager for constant indices.") (deflexical *constant-index-lru-size-percentage* 16 "[Cyc] Based on arete experiments, only 16% of all constants are touched during normal inference, so we'll make a conservative guess that every one of those touched the constant's index.") (defun setup-constant-index-table (size exact?) (setf *constant-index-manager* (new-kb-object-manager "constant-index" size *constant-index-lru-size-percentage* #'load-constant-index-from-cache exact?))) (defun* cached-constant-index-count () (:inline t) "[Cyc] Return the number of constant-indices whose content is cached in memory." (cached-kb-object-count *constant-index-manager*)) (defun* lookup-constant-index (id) (:inline t) (lookup-kb-object-content *constant-index-manager* id)) (defun register-constant-index (id constant-index) "[Cyc] Note that ID will be used as the id for CONSTANT-INDEX." (register-kb-object-content *constant-index-manager* id constant-index)) (defun deregister-constant-index (id) (deregister-kb-object-content *constant-index-manager* id)) (deflexical *permanently-cached-constant-indices* (list #$isa #$genls) "[Cyc] We never want to swap out the indices of these constants.") (defun mark-constant-index-as-permanently-cached (id) "[Cyc] Firstly make sure it's swapped in. Then make sure it won't ever get swapped out." (lookup-constant-index id) (mark-constant-index-as-muted id)) (defun swap-out-all-pristine-constant-indices () (swap-out-all-pristine-kb-objects-int *constant-index-manager*)) (defun initialize-constant-index-hl-store-cache () (prog1 (initialize-kb-object-hl-store-cache *constant-index-manager* "indices" "indices-index") (dolist (constant *permanently-cached-constant-indices*) (mark-constant-index-as-permanently-cached (constant-suid constant)))))
3,675
Common Lisp
.lisp
62
50.435484
190
0.693445
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
acc76c1092c8308ab2da0f0a7720e1d37a8057cbe4068b291f1419a0bacb1502
6,719
[ -1 ]
6,720
assertions-low.lisp
white-flame_clyc/larkc-cycl/assertions-low.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defstruct (assertion-content (:conc-name "AS-CONTENT-")) formula-data mt (flags 0 :type (or null fixnum)) arguments plist) (deflexical *default-assertion-flags* 0) (defun create-assertion-content (mt) (make-assertion-content :formula-data nil :mt mt :flags *default-assertion-flags* :arguments nil :plist nil)) (defun destroy-assertion-content (id) (when-let ((assertion-content (lookup-assertion-content id))) (deregister-assertion-content id) ;; The flags field is omitted as as a fixnum it's not a pointer. (setf (as-content-formula-data assertion-content) (setf (as-content-mt assertion-content) (setf (as-content-arguments assertion-content) (setf (as-content-plist assertion-content) nil)))))) ;; TODO - all these readers dereference the ID (macrolet ((define-reader (field) `(defun* ,(symbolicate 'lookup-assertion- field) (id) (:inline t) (when-let ((contents (lookup-assertion id))) (,(symbolicate 'as-content- field) contents))))) (define-reader formula-data) (define-reader mt) (define-reader flags) (define-reader arguments) (define-reader plist)) (macrolet ((define-writer (field) (let ((data-var (symbolicate 'new- field))) `(defun* ,(symbolicate 'set-assertion- field) (id ,data-var) (:inline t) (setf (,(symbolicate 'as-content- field) (lookup-assertion-content id)) ,data-var) (mark-assertion-content-as-muted id))))) (define-writer formula-data) (define-writer mt) (define-writer flags) (define-writer arguments) (define-writer plist)) (defun load-assertion-content (assertion stream) ;; Relying on left-to-right parameter evaluation order, guaranteed by 3.1.2.1.2.3 (load-assertion-content-int (assertion-id assertion) (cfasl-input stream) (cfasl-input stream) (cfasl-input stream) (cfasl-input stream) (cfasl-input stream))) (defun load-assertion-content-int (id formula-data mt flags arguments plist) ;; TODO - would have liked this to bypass create-assertion-content to use make- keywords easier (let ((assertion-content (create-assertion-content mt))) (setf (as-content-formula-data assertion-content) formula-data) (setf (as-content-flags assertion-content) flags) (setf (as-content-arguments assertion-content) arguments) (setf (as-content-plist assertion-content) plist) (register-assertion-content id assertion-content))) (defun assertion-cnf-internal (assertion) (let ((hl-cnf (assertion-hl-cnf assertion))) (if (clause-struc-p hl-cnf) (clause-struc-cnf hl-cnf) hl-cnf))) (defun possibly-assertion-cnf-internal (assertion) (and (valid-assertion-with-content? assertion) (assertion-cnf-internal assertion))) ;; TODO - and this is where we look up info by assertion ID for each field accessor. That seems kind of nuts. Cache the assertion-content struct on the assertion handle itself. (defun* assertion-mt-internal (assertion) (:inline t) (lookup-assertion-mt (assertion-id assertion))) (defun assertion-gaf-hl-formula-internal (assertion) (when (assertion-gaf-p assertion) (let ((formula-data (assertion-formula-data assertion))) (if (clause-struc-p formula-data) (cnf-to-gaf-formula (clause-struc-cnf formula-data)) formula-data)))) (defun assertion-cons-internal (assertion) (if (assertion-gaf-p assertion) (assertion-gaf-hl-formula assertion) (assertion-cnf-internal assertion))) (defun assertion-direction-internal (assertion) (decode-direction (assertion-flags-direction-code (assertion-flags assertion)))) (defun assertion-truth-internal (assertion) (tv-strength (assertion-tv assertion))) (defun assertion-tv (assertion) "[Cyc] Return the HL TV of ASSERTION." (decode-tv (assertion-flags-tv-decode (assertion-flags assertion)))) (defun* assertion-variable-names-internal (assertion) (:inline t) "[Cyc] Return the list of names for the variables in ASSERTION." (get-assertion-prop assertion :variable-names)) (defun asserted-by-internal (assertion) (and (asserted-assertion? assertion) (assert-info-who (assertion-assert-info assertion)))) (defun asserted-when-internal (assertion) (and (asserted-assertion? assertion) (assert-info-when (assertion-assert-info assertion)))) (defun asserted-why-internal (assertion) (and (asserted-assertion? assertion) (assert-info-why (assertion-assert-info assertion)))) (defun asserted-second-internal (assertion) (and (asserted-assertion? assertion) (assert-info-second (assertion-assert-info assertion)))) ;; TODO - assertion lookup by id (defun* assertion-arguments-internal (assertion) (:inline t) (lookup-assertion-arguments (assertion-id assertion))) (defun* assertion-dependents-internal (assertion) (:inline t) (get-assertion-prop assertion :dependents)) ;; TODO - assertion lookup by id (defun assertion-formula-data (assertion) "[Cyc] Return the HL structure used to implement the formula for ASSERTION. This will either be a clause struc containing a cnf, a cnf, or a gaf formula." ;; Or an ATM machine. (lookup-assertion-formula-data (assertion-id assertion))) ;; TODO - assertion lookup by id (defun reset-assertion-formula-data (assertion new-formula-data) "[Cyc] Primitively sets the HL structure used to implement the formula for ASSERTION. This should either be a clause struc containing a cnf, a cnf, or a gaf formula." (set-assertion-formula-data (assertion-id assertion) new-formula-data)) (defun assertion-hl-cnf (assertion) "[Cyc] Return the HL structure used to implement the CNF clause for ASSERTION. This will either be a clause struc containing a cnf, or a cnf. GAF formulas are expanded into CNFs." (let ((formula-data (assertion-formula-data assertion))) (if (or (clause-struc-p formula-data) (not formula-data) (not (assertion-gaf-p assertion))) formula-data (gaf-formula-to-cnf formula-data)))) (defun update-assertion-formula-data (assertion new-formula-data) "[Cyc] Primitively change the formula data of ASSERTION to NEW-FORMULA-DATA, and update the GAF flag. Assumes that NEW-FORMULA-DATA is either a CNF clause, a gaf formula, a clause-struc, or NIL." (cond ((clause-struc-p new-formula-data) (missing-larkc 32000)) ((not new-formula-data) (annihilate-assertion-formula-data assertion)) ((cnf-p new-formula-data) (reset-assertion-cnf assertion new-formula-data)) ((el-formula-p new-formula-data) (reset-assertion-gaf-formula assertion new-formula-data)) (t (error "Unexpected formula-data type: ~s" new-formula-data)))) (defun assertion-clause-struc (assertion) "[Cyc] If ASSERTION has a clause struc as its HL CNF implementation, return it. Otherwise, return NIL." (let ((formula-data (assertion-formula-data assertion))) (when (clause-struc-p formula-data) formula-data))) (defun reset-assertion-cnf (assertion new-cnf) "[Cyc] Primitively change the formula data of ASSERTION to NEW-CNF, and update the GAF flag. Shrinks NEW-CNF to a gaf formula if possible." (let ((gaf? (determine-cnf-gaf-p new-cnf))) (reset-assertion-formula-data assertion (if gaf? (cnf-to-gaf-formula new-cnf) new-cnf)) (set-assertion-gaf-p assertion gaf?))) (defun reset-assertion-gaf-formula (assertion new-gaf-formula) "[Cyc] Primitively change the formula data of ASSERTION to NEW-GAF-FORMULA, and set the GAF flag to T. Assumes the NEW-GAF-FORMULA is a valid gaf formula." (reset-assertion-formula-data assertion new-gaf-formula) (set-assertion-gaf-p assertion t)) (defun annihilate-assertion-formula-data (assertion) "[Cyc] Primitivly change the formula data of ASSERTION to NIL, and update the GAF flag to T (why not?)." (reset-assertion-formula assertion nil) (set-assertion-gaf-p assertion t)) ;; TODO - assertion lookup by id (defun* assertion-flags (assertion) (:inline t) "[Cyc] Return the bit-flags for ASSERTION." (lookup-assertion-flags (assertion-id assertion))) ;; TODO - assertion lookup by id (defun reset-assertion-flags (assertion new-flags) ;; TODO - equality check before write. It could be faster in RAM-only scenarios to write always, but cache effects might dominate. (let ((flags (assertion-flags assertion))) (unless (eql flags new-flags) (set-assertion-flags (assertion-id assertion) new-flags)))) ;; All this is gaf flag stuff. ;; TODO - fixnum declarations for speedup (defun* set-assertion-flags-gaf-code (flags code) (:inline t) (dpb code (byte 1 0) flags)) (defun* assertion-flags-direction-code (flags) (:inline t) (ldb (byte 2 1) flags)) (defun* assertion-flags-tv-code (flags) (:inline t) (ldb (byte 3 3) flags)) (defun* set-assertion-flags-tv-code (flags code) (:inline t) (dpb code (byte 3 3) flags)) (defun* assertion-flags-gaf-p (assertion) (:inline t) "[Cyc] Return T iff ASSERTION is a GAF according to its internal flag bits." (oddp (assertion-flags assertion))) (defun set-assertion-flags-gaf-p (assertion gaf-p) "[Cyc] Primitively set the gaf flag of ASSERTION." ;; TODO - this checked the return value of ENCODE-BOOLEAN for non-NILness which makes no sense (reset-assertion-flags assertion (set-assertion-flags-gaf-code (assertion-flags assertion) (encode-boolean gaf-p)))) (defglobal *rule-set* nil "[Cyc] When non-NIL, a cache of all the rule assertions in the KB.") (defglobal *prefer-rule-set-over-flags?* nil "[Cyc] When non-NIL, the rule-set cache is used to compute GAF vs Rule rather than using the bit in the flags.") ;; TODO - eliminate hash table size estimates (deflexical *estimated-assertions-per-rule* 60) (defun setup-rule-set (estimated-assertion-size) (let ((estimated-rule-count (ceiling (/ estimated-assertion-size *estimated-assertions-per-rule*)))) (setf *rule-set* (new-set #'eq estimated-rule-count)))) (defun assertion-gaf-p (assertion) (if *prefer-rule-set-over-flags?* (when *rule-set* ;; TODO - why use this instead of the flags? (not (set-member? assertion *rule-set*))) (assertion-flags-gaf-p assertion))) (defun set-assertion-gaf-p (assertion gaf?) "[Cyc] Primitively set the gaf flag of ASSERTION." (when *rule-set* (if gaf? (set-remove assertion *rule-set*) (set-add assertion *rule-set*))) (set-assertion-flags-gaf-p assertion gaf?)) (defun* determine-cnf-gaf-p (cnf) (:inline t) "[Cyc] Return the recomputed value for the gaf flag of ASSERTION." (gaf-cnf? cnf)) (defun load-rule-set-from-stream (stream) (setf *rule-set* (cfasl-input stream)) (set-size *rule-set*)) (defun* gaf-formula-to-cnf (gaf) (:inline t) "[Cyc] Converts a gaf formula to a CNF clause." (make-gaf-cnf gaf)) (defun* cnf-to-gaf-formula (cnf) (:inline t) "[Cyc] Converts a CNF representation of a gaf formula to a gaf formula." (gaf-cnf-literal cnf)) (defun kb-set-assertion-direction-internal (assertion new-direction) (if (gaf-assertion? assertion) (reset-assertion-direction assertion new-direction) (progn (remove-assertion-indices assertion) (reset-assertion-direction assertion new-direction) (add-assertion-indices assertion)))) (defun reset-assertion-tv (assertion new-tv) "[Cyc] Primitively change the HL TV of ASSERTION to NEW-TV." (when-let ((tv-code (encode-tv new-tv))) (reset-assertion assertion (set-assertion-flags-tv-code (assertion-flags assertion) tv-code)))) (defun reset-assertion-truth (assertion new-truth) (let* ((existing-strength (assertion-strength assertion)) (new-tv (tv-from-truth-strength new-truth existing-strength))) (reset-assertion-tv assertion new-tv))) (defun reset-assertion-strength (assertion new-strength) (let* ((existing-truth (assertion-truth assertion)) (new-tv (tv-from-truth-strength existing-truth new-strength))) (reset-assertion-tv assertion new-tv))) ;; TODO - assertion lookup by id (defun assertion-plist (assertion) (lookup-assertion-plist (assertion-id assertion))) ;; TODO - assertion lookup by id (defun* reset-assertion-plist (assertion plist) (:inline t) (set-assertion-plist (assertion-id assertion) plist)) (defun* get-assertion-prop (assertion indicator &optional default) (:inline t) (getf (assertion-plist assertion) indicator default)) (defun set-assertion-prop (assertion indicator value) (reset-assertion-plist assertion (putf (assertion-plist assertion) indicator value))) (defun rem-assertion-prop (assertion indicator) (let ((old-plist (assertion-plist assertion))) (reset-assertion-plist assertion (remf old-plist indicator)))) (defun reset-assertion-variable-names (assertion new-variable-names) "[Cyc] Primitively change the variable names for ASSERTION to NEW-VARIABLE-NAMES." ;; TODO - check that NEW-VARIABLE-NAMES is a proper list of all strings, but type checks are diabled (if new-variable-names (set-assertion-prop assertion :variable-names new-variable-names) (rem-assertion-prop assertion :variable-names))) (defun* assertion-index (assertion) (:inline t) "[Cyc] Return the indexing structure for ASSERTION." (assertion-indexing-store-get assertion)) (defun reset-assertion-index (assertion new-index) "[Cyc] Primitively change the indexing structure for ASSERTION to NEW-INDEX." (if (eq new-index (new-simple-index)) ;; TODO - this is probably an optimization that we can ignore and safely continue. (missing-larkc 31913) (assertion-indexing-store-set assertion new-index))) (defun* asertion-assert-info (assertion) (:inline t) "[Cyc] Return the assert timestamping info for ASSERTION." (get-assertion-prop assertion :assert-info)) (defun reset-assertion-assert-info (assertion new-info) (if new-info (set-assertion-prop assertion :assert-info new-info) (rem-assertion-prop assertion :assert-info))) (defun asserted-assertion-timestamped? (assertion) (when (asserted-assertion? assertion) (assertion-assert-info assertion))) ;; Cheap way to make accessors (defstruct (assert-info (:type list) (:constructor nil)) who when why second) (defun make-assert-info (&optional who when why second) ;; TODO - this might be more effective as a macro, unless NILs are passed in. (cond (second (list who when why second)) (why (list who when why)) (when (list who when)) (who (list who)))) ;; HACK - faster, simpler versions, but they assume the list format. (defun set-assertion-asserted-by (assertion assertor) (list* assertor (cdr (assertion-assert-info assertion)))) (defun set-assertion-asserted-when (assertion universal-date) (let ((ai (copy-list (assertion-assert-info assertion)))) (setf (assert-info-when ai) universal-date) ai)) (defun set-assertion-asserted-why (assertion reason) (let ((ai (copy-list (assertion-assert-info assertion)))) (setf (assert-info-why ai) reason) ai)) (defun set-assertion-asserted-second (assertion universal-second) (let ((ai (copy-list (assertion-assert-info assertion)))) (setf (assert-info-second ai) universal-second))) (defun valid-assertion-with-content? (assertion) "[Cyc] Does ASSERTION have content?" (let ((id (assertion-id assertion))) (ignore-errors (lookup-assertion-content id)))) (defun kb-create-assertion-kb-store (cnf mt) (let ((assertion (find-assertion-internal cnf mt))) (if assertion (assertion-id assertion) (let ((internal-id (make-assertion-id))) (kb-create-assertion-int (make-assertion-shell internal-id) internal-id cnf mt) internal-id)))) (defun kb-create-assertion-int (assertion internal-id cnf mt) (let ((assertion-content (create-assertion-content mt))) (register-assertion-content internal-id assertion-content) (reset-assertion-tv assertion :unknown) (connect-assertion assertion (find-cnf-formula-data-hook cnf)))) (defun find-cnf-formula-data-hook (cnf) (if (gaf-cnf? cnf) (find-gaf-formula-hook (gaf-cnf-literal cnf)) (find-hl-cnf-hook cnf))) (defun find-hl-cnf-hook (cnf) (let ((assertion (find-assertion-any-mt cnf))) (if assertion (or (assertion-clause-struc assertion) assertion) cnf))) (defun find-gaf-formula-hook (gaf) (let ((assertion (find-gaf-any-mt gaf))) (if assertion (or (assertion-clause-struc assertion) assertion) gaf))) (defun connect-assertion (assertion formula-data-hook) "[Cyc] Connect ASSERTION to FORMULA-DATA-HOOK and all its relevant indexes." (connect-assertion-formula-data assertion formula-data-hook) (add-assertion-indices assertion)) (defun connect-assertion-formula-data (assertion formula-data-hook) (let ((formula-data formula-data-hook)) (cond ((clause-struc-p formula-data-hook) (missing-larkc 11315)) ((assertion-p formula-data-hook) (missing-larkc 11343)) ((or (cnf-p formula-data-hook) (el-formula-p formula-data-hook) nil)) (t (error "Unexpected formula data hook: ~s" formula-data-hook))) (update-assertion-formula-data assertion formula-data))) (defun kb-remove-assertion-internal (assertion) (let ((id (assertion-id assertion))) (disconnect-assertion assertion) (destroy-assertion-content id) (deregister-assertion-id id)) (free-assertion assertion)) (defun disconnect-assertion (assertion) "[Cyc] Disconnect ASSERTION from all its connections." (remove-assertion-indices assertion) (disconnect-assertion-formula-data assertion)) (defun disconnect-assertion-formula-data (assertion) (when (assertion-clause-struc assertion) (missing-larkc 11355)) (annihilate-assertion-formula-data assertion)) (defun add-new-assertion-argument (assertion new-argument) (set-assertion-arguments (assertion-id assertion) (cons new-argument (assertion-arguments assertion)))) (defun remove-assertion-argument (assertion argument) (setf (assertion-arguments (assertion-id assertion)) (delete-first argument (assertion-arguments assertion)))) (defun reset-assertion-dependents (assertion new-dependents) "[Cyc] Primitively set the dependent arguments of ASSERTION to NEW-DEPENDENTS." (if new-dependents (set-assertion-prop assertion :dependents new-dependents) (rem-assertion-prop assertion :dependents))) (defun add-assertion-dependent (assertion argument) "[Cyc] Add ARGUMENT as an argument depending on ASSERTION. Return ASSERTION." (reset-assertion-dependents assertion (cons argument (assertion-dependents assertion))) assertion) (defun remove-assertion-dependent (assertion argument) "[Cyc] Remove ARGUMENT as an argument depending on ASSERTION. Return ASSERTION." (reset-assertion-dependents assertion (delete-first argument (assertion-dependents assertion))) assertion) (defparameter *dependent-deduction-table* nil) (defparameter *dependent-assertion-table* nil)
21,065
Common Lisp
.lisp
415
45.062651
197
0.71256
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
1ee43a085e5f305e97685b4aa51694998c85d9038973860ed19d05bf73b0d04f
6,720
[ -1 ]
6,721
unrepresented-term-index-manager.lisp
white-flame_clyc/larkc-cycl/unrepresented-term-index-manager.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defglobal *unrepresented-term-index-manager* :uninitialized "[Cyc] The KB object manager for unrepresented-term indices.") (deflexical *unrepresented-term-index-lru-size-percentage* 10 "[Cyc] Wild guess.") (defun setup-unrepresented-term-index-table (size exact?) (setf *unrepresented-term-index-manager* (new-kb-object-manager "unrepresented-term-index" size *unrepresented-term-index-lru-size-percentage* #'load-unrepresented-term-index-from-cache exact?))) (defun* clear-unrepresented-term-index-table () (:inline t) (clear-kb-object-content-table *unrepresented-term-index-manager*)) (defun* cached-unrepresented-term-index-count () (:inline t) "[Cyc] Return the number of unrepresented-term-indices whose content is cached in memory." (cached-kb-object-count *unrepresented-term-index-manager*)) (defun* lookup-unrepresented-term-index (id) (:inline t) (lookup-kb-object-content *unrepresented-term-index-manager* id)) (defun* register-unrepresented-term-index (id unrepresented-term-index) (:inline t) "[Cyc] Note that ID will be used as the id for UNREPRESENTED-TERM-INDEX." (register-kb-object-content *unrepresented-term-index-manager* id unrepresented-term-index)) (defun* deregister-unrepresented-term-index (id) (:inline t) "[Cyc] Note that ID is not in use as an UNREPRESENTED-TERM-INDEX id." (deregister-kb-object-content *unrepresented-term-index-manager* id)) (defun* mark-unrepresented-term-index-as-muted (id) (:inline t) (mark-kb-object-content-as-muted *unrepresented-term-index-manager* id)) (defun* swap-out-all-pristine-unrepresented-term-indices () (:inline t) (swap-out-all-pristine-kb-objects-int *unrepresented-term-index-manager*)) (defun initialize-unrepresented-term-index-hl-store-cache () (initialize-kb-object-hl-store-cache *unrepresented-term-index-manager* "unrepresented-term-indices" "unrepresented-term-indices-index"))
3,508
Common Lisp
.lisp
56
56.053571
118
0.732555
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
2ca7709f0cc8d5178ff1ab64fd0be321a9c4a302358a4d6f6d1afcddd2669b3b
6,721
[ -1 ]
6,722
deck.lisp
white-flame_clyc/larkc-cycl/deck.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; No macros declared (defstruct deck type data) (defun create-deck (type) "[Cyc] Return a new, empty deck." (make-deck :type type :data (case type (:queue (create-queue)) (:stack (create-stack))))) (defun clear-deck (deck) "[Cyc] Clear DECK and return it." (setf (deck-data deck) (case (deck-type deck) (:queue (create-queue)) (:stack (create-stack)))) deck) (defun deck-empty-p (deck) "[Cyc] Return T iff DECK is empty." (case (deck-type deck) (:queue (queue-empty-p (deck-data deck))) (:stack (stack-empty-p (deck-data deck))))) (defun deck-push (elt deck) "[Cyc] Add an element ELT to DECK. Returns DECK." (case (deck-type deck) (:queue (enqueue elt (deck-data deck))) (:stack (stack-push elt (deck-data deck)))) deck) (defun deck-pop (deck) "[Cyc] Remove and return the next accessible element from DECK." (case (deck-type deck) (:queue (dequeue (deck-data deck))) (:stack (stack-pop (deck-data deck)))))
2,475
Common Lisp
.lisp
59
36.966102
77
0.704107
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
d01270222625fc56839ec054e56df5b96d4c6d2ccbd74330cae708ed228b9354
6,722
[ -1 ]
6,723
stacks.lisp
white-flame_clyc/larkc-cycl/stacks.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defstruct stack (num 0 :type fixnum) (elements nil :type list)) (defun create-stack () "[Cyc] Return a new, empty stack." (make-stack)) (defun clear-stack (stack) "[Cyc] Clear STACK and return it." (setf (stack-num stack) 0) (setf (stack-elements stack) nil) stack) (defun stack-empty-p (stack) "[Cyc] Return T iff STACK is empty." (null (stack-elements stack))) (defun stack-push (item stack) "[Cyc] Add ITEM to the top of STACK. Returns STACK." (incf (stack-num stack)) (push item (stack-elements stack)) stack) (defun stack-pop (stack) "[Cyc] Remove and return the top item in STACK." (when (stack-elements stack) (decf (stack-num stack)) (pop (stack-elements stack)))) (defun stack-peek (stack) "[Cyc] Return the top item in STACK, without removing it." (when (stack-elements stack) (car (stack-elements stack)))) ;; rest of it seems missing-larkc (defstruct locked-stack lock stack) (defmacro do-stack-elements ((item-var stack &key done) &body body) ;; TODO - assuming that DONE is a early-exit predicate. Could also be a return value form. (when done (warn "do-stack-elements DONE keyword used: ~s" done)) `(do ((,item-var ,stack (cdr ,item-var))) ((or ,done (null ,item-var))) ,@body))
2,671
Common Lisp
.lisp
65
37.861538
92
0.738252
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
ebf2c99932878bb8e378f4119c5740f2c413897f171576b2ebe39b999b0c5dd4
6,723
[ -1 ]
6,724
api-control-vars.lisp
white-flame_clyc/larkc-cycl/api-control-vars.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defparameter *cfasl-constant-handle-func* nil "[Cyc] Fucntion used to determine constant handles during CFASL output. If nIL, the default used is CONSTANT-INTERNAL-ID") (defparameter *cfasl-constant-handle-lookup-func* nil "[Cyc] Function used to look up constants from their handles during CFASL input. If NIL, the default used is FIND-CONSTANT-BY-INTERNAL-ID") (defparameter *cfasl-nart-handle-func* nil "[Cyc] Function used to determine NART handles during CFASL output. If NIL, the default used is NART-ID.") (defparameter *cfasl-nart-handle-lookup-func* nil "[Cyc] Function used to look up NARTs from their handles during CFASL input. If NIL, the default used is FIND-NART-BY-ID") (defparameter *cfasl-assertion-handle-func* nil "[Cyc] Function used to determine assertion handles during CFASL output. If NIL, the default used is ASSERTION-ID") (defparameter *cfasl-assertion-handle-lookup-func* nil "[Cyc] Function used to look up assertions from their handles during CFASL input. If NIL, the default used is FIND-ASSERTION-BY-ID") (defparameter *cfasl-deduction-handle-func* nil "[Cyc] Function used to determine deduction handles during CFASL output. If NIL, the default used is DEDUCTION-ID") (defparameter *cfasl-deduction-handle-lookup-func* nil "[Cyc] Function used to look up deductions from their handles during CFASL input. If NIL, the default used is FIND-DEDUCTION-BY-ID") (defparameter *cfasl-kb-hl-support-handle-func* nil "[Cyc] Function used to determine KB HL supports during CFASL output. If NIL, the default used is KB-HL-SUPPORT-ID") (defparameter *cfasl-kb-hl-support-handle-lookup-func* nil "[Cyc] Function used to look up KB HL supports from their handles during CFASL input. If NIL, the default used is FIND-KB-HL-SUPPORT-BY-ID") (defparameter *cfasl-clause-struc-handle-func* nil "[Cyc] Function used to determine clause-struc handles during CFASL output. If NIL, the default used is CLAUSE-STRUC-ID") (defparameter *cfasl-clause-struc-handle-lookup-func* nil "[Cyc] Function used to look up clause-strucs from their handles during CFASL input. If NIL, the default used is FIND-CLAUSE-STRUC-BY-ID") (defvar *the-cyclist* nil) (defparameter *use-local-queue?* t) (defparameter *default-ke-purpose* nil "[Cyc] The purpose to use for KE by default. NIL = General Cyc KE.") (defparameter *ke-purpose* *default-ke-purpose* "[Cyc] This variable constains current KE purpose for asserting formulas to the system. NIL means that the KB purpose is generic extension of Cyc's knowledge.") (defparameter *generate-readable-fi-results* t)
3,983
Common Lisp
.lisp
71
53.774648
89
0.783548
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
4879ea1cb7428dda6880e44ef3bdaba50dfe0225c14c8bb70ff10d2e34d48b73
6,724
[ -1 ]
6,725
map-utilities.lisp
white-flame_clyc/larkc-cycl/map-utilities.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO DESIGN - These utilities abstract Dictionary & hashtable. But since we eliminated dictionary and only work on hashtables, this is moot. Deprecate all of this and wrap into hash-table-utilities. ;; TODO - add file-level deprecation to the FILE form. (symbol-mapping map-p hash-table-p map-size hash-table-count map-empty-p hash-table-empty-p map-get-without-values map-get) ;; Stuff that doesn't have a direction function that exactly matches the params (defun* map-put (map key value) (:inline t) (setf (gethash key map) value)) (defun* map-get (map key default) (:inline t) (gethash key map default)) (defun* map-remove (map key) (:inline t) (remhash key map))
2,125
Common Lisp
.lisp
40
49.025
202
0.757649
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
4063504fc808fae2bfba5afe274516a62fdc3629287bde299beea4ee36b52028
6,725
[ -1 ]
6,726
cfasl-compression.lisp
white-flame_clyc/larkc-cycl/cfasl-compression.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defconstant *cfasl-opcode-open-compressed-block* 54) (defconstant *cfasl-opcode-compression-pair* 55) (defconstant *cfasl-opcode-compression-key* 56) (defconstant *cfasl-opcode-close-compressed-block* 57) (defglobal *cfasl-decompression-index* (make-hash-table :test #'eq) "[Cyc] A dictionary mapping streams to a stack of decompression tables, the topmost of which is the active one.") (defglobal *cfasl-compression-not-found* (make-symbol "NOT-FOUND")) (defparameter *cfasl-output-compression-options* nil) (defparameter *cfasl-output-compression-table* nil) (defparameter *cfasl-outputcompression-code-isg* nil) (defparameter *within-cfasl-compression-analysis?* nil) (deflexical *cfasl-compression-options-properties* '(:all? :analyze :not :verbose?) "[Cyc] The valid properties for the CFASL compression options property list.") (defun cfasl-compress-object? (object) (declare (ignore object)) (cond ((not *cfasl-output-compression-table*) nil) ((missing-larkc 12990))))
2,394
Common Lisp
.lisp
45
50.266667
117
0.77945
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
1e1725216ce143669541d83da955369c1729475f678b64fff28519de642fab0a
6,726
[ -1 ]
6,727
hash-table-utilities.lisp
white-flame_clyc/larkc-cycl/hash-table-utilities.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defconstant *valid-hash-test-symbols* '(eq eql equal equalp) "[Cyc] All function symbols which are permitted tests for hashtable-based algorithms.") (defconstant *valid-hash-test-functions* (list #'eq #'eql #'equal #'equalp) "[Cyc] All functions which are permitted test for hashtable-based algorithms.") (defun valid-hash-test-symbols () *valid-hash-test-symbols*) (defun hash-test-to-symbol (test) "[Cyc] Return the symbol form of TEST, which is a valid hash-test function." (check-type test 'valid-hash-test-p) (if (symbolp test) test (find test *valid-hash-test-symbols* :key #'symbol-function))) (defun hash-table-empty-p (table) "[Cyc] Return T iff TABLE is an empty hashtable" (zerop (hash-table-count table))) (defun rehash (table) "[Cyc] Rehash every KEY VALUE pair in the hashtable TABLE." ;; Relying on CL doing a good job on its own table) (defun push-hash (key item table) (push item (gethash key table))) (defun pop-hash (key table) "[Cyc] Pops off the first element of the value of KEY in TABLE. More precisely, returns the first element of the value of KEY in TABLE, and sets that value to be the rest of itself." (pop (gethash key table))) (defun delete-hash (key item table &optional (test #'eql) (test-key #'identity)) (setf (gethash key table) (delete item (gethash key table) :test test :key test-key))) (defun hash-table-keys (hash-table) "[Cyc] Return a list of all the keys of HASH-TABLE." (loop for key being the hash-key of hash-table collect key)) (defun hash-table-values (hash-table) (loop for val being the hash-value of hash-table collect val))
3,051
Common Lisp
.lisp
61
46.655738
184
0.750169
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
0e29733339ff43119edf0e3912e7cf7947910ffc639729b9184370a0932cdf9a
6,727
[ -1 ]
6,728
czer-vars.lisp
white-flame_clyc/larkc-cycl/czer-vars.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defparameter *required-arg-preds* '(#$requiredArg1Pred #$requiredArg2Pred)) (deflexical *arg-positions* '(1 2 3 4 5) "[Cyc] Integers denoting the most common arg positions of fixed-arity CycL relations.") (defparameter *accumulating-semantic-violations?* nil "[Cyc] Suppresses resetting *arg-type-violations*.") (defparameter *semantic-violations* nil "[Cyc] Descriptions of how a relational expression is not semantically valid.") (defparameter *assertion-key* 'assertion-formula "[Cyc] Which function to use when accessing the formula for an assertion.") (defparameter *nart-key* 'nart-hl-formula "[Cyc] Which function to use when accessing the formula for a nart.") (defparameter *rf-key* 'rf-formula "[Cyc] Which function to use when accessing the formula for a reified formula (the genl of nart and assertion).") (deflexical *implication-operators* (list #$implies)) (deflexical *logical-operators* (list #$not #$or #$xor #$and #$equiv #$implies #$exceptFor #$exceptWhen #$forAll #$thereExists #$thereExistExactly #$thereExistAtLeast #$thereExistAtMost)) (deflexical *skolem-function-functions* (list #$SkolemFunctionFn #$SkolemFuncNFn) "[Cyc] Cyc constants that denote functions whose ranges are skolem functions.") (deflexical *arg-isa-binary-preds* (list #$arg1Isa #$arg2Isa #$arg3Isa #$arg4Isa #$arg5Isa #$arg6Isa #$argsIsa)) (deflexical *arg-isa-ternary-preds* (list #$argIsa #$argAndRestIsa)) (deflexical *arg-quoted-isa-binary-preds* (list #$arg1QuotedIsa #$arg2QuotedIsa #$arg3QuotedIsa #$arg4QuotedIsa #$arg5QuotedIsa #$arg6QuotedIsa #$argsQuotedIsa)) (deflexical *arg-quoted-isa-ternary-preds* (list #$argQuotedIsa #$argAndRestQuotedIsa)) (deflexical *arg-genl-binary-preds* (list #$arg1Genl #$arg2Genl #$argsGenl #$arg3Genl #$arg4Genl #$arg5Genl #$arg6Genl)) (deflexical *arg-genl-ternary-preds* (list #$argGenl #$argAndRestGenl)) (deflexical *arg-format-binary-preds* (list #$arg1Format #$arg2Format #$arg3Format #$arg4Format #$arg5Format #$arg6Format)) (deflexical *arg-format-ternary-preds* (list #$argFormat)) (deflexical *meta-arg-type* #$CycLAssertion "[Cyc] Arg-type for meta predicates.") (deflexical *possibly-meta-arg-type* #$CycLIndexedTerm "[Cyc] Arg-type for meta predicates.") (defparameter *variables-that-cannot-be-sequence-variables* nil "[Cyc] A dynamic stack of variables that are currently not permitted to be used as sequence variables (e.g. because they're scoped).") (defparameter *el-supports-dot-syntax?* t "[Cyc] Are sequence variables permitted?") (deflexical *el-supports-variable-arity-skolems?* t) (defparameter *el-supports-contractions?* nil "[Cyc] Is support for contractions (inverse #$expansions) enabled?") (defvar *inside-quote* nil "[Cyc] Variable to keep track if we are inside a quote form.") (defparameter *new-canonicalizer?* nil "[Cyc] Whether to use the code for the new canonicalizer.") (defparameter *within-canonicalizer?* nil "[Cyc] Transient state variable; is T during the execution of canonicalizing functions.") (defparameter *form-of-clausal-form* nil "[Cyc] Canonicalizer state variable [:cnf :dnf].") (defparameter *must-enforce-semantics?* nil) (defparameter *el-trace-level* 0 "[Cyc] Controls tracing level for canonicalizer [0..5].") (defparameter *canon-verbose?* nil "[Cyc] Controls whether the formula is printed after each step of canonicalization. Only set to T for debugging purposes.") ;; TODO - resolve this to #'el-var when dealing with dependencies (defparameter *var?* 'el-var? "[Cyc] Default predicate to identify variables.") (defparameter *subordinate-fi-ops?* nil) (defparameter *cry?* t "[Cyc] Flag to break on error conditions.") (defparameter *minimal-skolem-arity?* nil "[Cyc] Should the canonicalizer include only free vars referenced in existentially quantified formulas in argument lists of the resulting skolem functions?") (defparameter *skolemize-during-asks?* nil "[Cyc] Should the canonicalizer translate existentially quantified vars into skolem functions during asks?") (defparameter *drop-all-existentials?* nil "[Cyc] Should the canonicalizer, when canonicalizing existentials, simply drop them (like it does by default during asks)? This setting, if true, overrides the combination of *WITHIN-ASK* and *SKOLEMIZE-DURING-ASKS?*, but does not override the case of *TURN-EXISTENTIALS-INTO-SKOLEMS?* being false, which will cause no existential handling at all to be done.") (defparameter *leave-skolem-constants-alone?* nil "[Cyc] Should the canonicalizer, when canonicalizing existentials that are not in the scope of any other variable, simply drop them (like it does by default during asks)? This setting, if true, overrides the combination of *WITHIN-ASK* and *SKOLEMIZE-DURING-ASKS?*, but does not override the case of *TURN-EXISTENTIALS-INTO-SKOLEMS?* being false, which will cause no existential handling at all to be done.") (defparameter *forbid-quantified-sequence-variables?* :assert-only "[Cyc ]Whether to enforce criterion Q2 in the Sequence Variable Specification, namely: Q2: Within asserts, sequence variables can only be universally quantified; using existentially quantified variables as sequence variables is not permitted. If T, Q2 is enforced. If NIL, Q2 is not enforced. If :assert-only, Q2 is enforced iff (within-assert?).") (defparameter *use-skolem-constants?* nil "[Cyc] Should the canonicalizer create and reference skolem constants instead of zero-arity skolem functions?") (defparameter *canonicalize-gaf-commutative-terms?* t "[Cyc] Should commutative terms of gafs be sorted?") (defparameter *canon-var-function* :default "[Cyc] The function that the canonicalizer uses internally to check whether something is a variable. :default means that it will use the default function cyc-var? (this is slightly more efficient than just making the default be #'cyc-var?)") (defparameter *canonical-variable-type* :kb-var "[Cyc] Determines the type of variables produced by the canonicalzer [:el-var :kb-var].") (defparameter *standardize-variables-memory* nil "[Cyc] Stores the variable rename mappings formed while standardizing variables during canonicalization.") (defparameter *distributing-meta-knowledge?* nil "[Cyc] Is distributing meta-knowledge over multiple assertions permitted?") (defparameter *distribute-meta-over-common-el?* t "[Cyc] Should meta-knowledge distribute over multiple assertions when those assertions all share a common el formula?") (defparameter *find-uncanonical-decontextualized-assertions?* t "[Cyc] If a decontextualized assertion is in the wrong mt, should the canonicalizer, if asked to look up that assertion, find it? If T, it will find it. If NIL, it will treat it like any other uncanonical assertion and fail to find it.") (defparameter *canonicalize-el-template-vars-during-queries?* t "[Cyc] Should EL variables in EL template args be canonicalized into HL variables during asks? If T, then queries like (expansion genls (implies (isa ?OBJ :ARG1) (isa ?OBJ :ARG2))) will not be interpreted as a boolean query, and will return ((?OBJ . ?OBJ)) instead of ((T . T)). If it is set to nil, then queries like (expansion genls ?WHAT) will be interpreted as a boolean query, and will return NIL instead of the expansion of genls.") (defparameter *robust-assertion-lookup* nil "[Cyc] Controls whether, upon failing to find an assertion, a more thorough (and more time-consuming) lookup is performed. You can set this to T or NIL if you want to control its behavior.") (defparameter *robust-nart-lookup* :default "[Cyc] Controls whether, upon failing to find a nart, a more thorough (and more time-consuming) lookup is performed. You can set this to T or NIL if you want to control its behavior.") (defparameter *recanonicalizing-candidate-nat?* nil "[Cyc] Dynamic variable set while recanonicalizing a nat for robust nart lookup.") (defparameter *el-var-blist* nil "[Cyc] Stores the variable rename mappings formed while standardizing variables during uncanonicalization.") (defparameter *gathering-quantified-fn-terms?* nil "[Cyc] Control var used to collect non-ground reifiable fn terms.") (defparameter *expand-el-relations?* t "[Cyc] Should #$ELRelations be automatically expanded by the precanonicalizer?") (defparameter *canonicalize-all-sentence-args?* nil "[Cyc] Should all sentence args (of literals or denotational functions) be canonicalized into their el version?") (defparameter *canonicalize-tensed-literals?* t "[Cyc] Should tensed literals be canonicalized into their time quantified version?") (defparameter *add-term-of-unit-lits?* t) (defparameter *turn-existentials-into-skolems?* t "[Cyc] If you set this to NIL, the canonicalizer will be severely crippled. Beware!") (defparameter *reify-skolems?* t) (defparameter *create-narts-regardless-of-whether-within-assert?* nil) (defparameter *canonicalize-functions?* t) (defparameter *canonicalize-terms?* t) (defparameter *canonicalize-literals?* t) (defparameter *canonicalize-disjunction-as-enumeration?* nil "[Cyc] Whether to canonicalize a disjunction over a common predicate as an #$elementOf expression.") (defparameter *canonicalize-variables?* t) (defparameter *implicitify-universals?* t "[Cyc] Whether to eliminate universals which could be removed and still maintain the logical equivalence of the sentence if they are viewed as implicitly encapsulating it.") (defparameter *assume-free-vars-are-existentially-bound?* nil "[Cyc] Whether the clausifier will assume that free variables are existentially bound, as opposed to the default which is universally bound. This ought to be the mode in which the clausifier is run for queries.") (defparameter *encapsulate-var-formula?* t "[Cyc] Translate variables appearing as logical operators into encapsulated literals?") (defparameter *encapsulate-intensional-formula?* t "[Cyc] Translate intensional (e.g., negated universally quantified) formulas into encapsulated negative literals?") (defparameter *czer-quiescence-iteration-limit* 10 "[Cyc] If an expression fails to quiesce after 10 iterations, give up and deem it ill-formed.") (defparameter *clause-el-var-names* nil) (defparameter *el-symbol-suffix-table* nil "dynamic table of uniquifying el var suffixes") (defparameter *within-negation?* nil "[Cyc] Is canonicalization occuring within scope of a negation?") (deflexical *hl-pred-order* (list #$isa #$genls) "[Cyc] Preferred order of preds wrt canonicalization.") (defparameter *control?* nil "[Cyc] Temp: used to control canonicalizer to include (= nil) or exclude (= t) experimental code.") (defparameter *control-1* nil "[Cyc] Temp: used to control canonicalizer to include (= nil) or exclude (= t) experimental code.") (defparameter *control-2* nil "[Cyc] Temp: used to control canonicalizer to include (= nil) or exclude (= t) experimental code.") (defparameter *control-3* nil "[Cyc] Temp: used to control canonicalizer to include (= nil) or exclude (= t) experimental code.") (defparameter *control-4* nil "[Cyc] Temp: used to control canonicalizer to include (= nil) or exclude (= t) experimental code.") (defparameter *control-5* nil "[Cyc] Temp: used to control canonicalizer to include (= nil) or exclude (= t) experimental code.") (defparameter *control-6* nil "[Cyc] Temp: used to control canonicalizer to include (= nil) or exclude (= t) experimental code.") (defparameter *control-eca?* nil "[Cyc] Temp: used to control canonicalizer to include (= nil) or exclude (= t) experimental code.") (defparameter *czer-memoization-state* nil "[Cyc] Dynamically bound to a memoization state for the canonicalizer.") (defparameter *use-czer-fort-types?* t "[Cyc] Whether to use czer-fort-types at all.") (defparameter *use-czer-fort-types-globally?* t "[Cyc] Whether to always use czer-fort types. If NIL, they will only be used within the canonicalizer. If *use-czer-fort-types?* is NIL, this variable doesn't matter.") (deflexical *canonicalizer-directive-predicates* (list #$canonicalizerDirectiveForArg #$canonicalizerDirectiveForAllArgs #$canonicalizerDirectiveForArgAndRest) "[Cyc] The set of predicates which specify #$CanonicalizerDirectives. Not to be confused with the set of all instances of #$CanonicalizerDirectivePredicate, which is much broader.") (defparameter *ununiquify-el-vars?* nil "[Cyc] Whether the uncanonicalizer should remove uniquifying numerical suffixes on EL variables.") (defparameter *unremove-universals?* t "[Cyc] Whether the uncanonicalizer should insert #$forAlls around unquantified variables.") (defparameter *uncanonicalize-tensed-literals?* t "[Cyc] Whether the uncanonicalizer should rephrase sentences in terms of #$was, #$willBe, etc.") (defparameter *recanonicalizing?* nil "[Cyc] Is an existing assertion being recanonicalized?") (defparameter *recanonicalizing-candidate-assertion-stack* nil "[Cyc] Used for recursion detection") (defparameter *noting-ill-formed-meta-args?* nil "[Cyc] Whether el-meta should set the value of *RECAN-ILL-FORMED-META-ARGS?*") (defparameter *recan-ill-formed-meta-args?* nil "[Cyc] Bound by el-meta when called from the recanonicalizer, so that the recanonicalizer can correctly analyze problems with finding meta assertions (which may be due to uncanonicality).") (defparameter *simplify-sentence?* t) (defparameter *simplify-literal?* t) (defparameter *simplify-implication?* t) (defparameter *simplify-non-wff-literal?* t "[Cyc] If T, non-wff literals will be reduced to #$False.") (defparameter *try-to-simplify-non-wff-into-wff?* t "[Cyc] If T, non-wffs will be simplified to see if they become wff. This usually only happens with sequence variables.") (defparameter *trying-to-simplify-non-wff-into-wff?* nil "[Cyc] Transient state variable, t iff we're in the middle of trying to simplify a non-wff into a wff.") (defparameter *simplify-using-semantics?* t "[Cyc] If NIL, simplify-cycl-sentence will only perform syntactic simplifications.") (defparameter *simplify-redundancies?* nil "[Cyc] If T, simplify-cycl-sentence will look for redundant literals and remove them.") (defparameter *simplify-transitive-redundancies?* nil "[Cyc] If T, simplify-transitive-redundancies will look for transitive redundancies and remove them.") (defparameter *simplify-sequence-vars-using-kb-arity?* t "[Cyc] If T, simplify-sequence-vars will use arity information from the KB to eliminate sequence variables or convert them to term variables when possible. (It will always use the arity of logical operators to simplify.)") (defparameter *sequence-variable-split-limit* 5 "[Cyc] The maximum number of term variables that a sequence variable can be split into if we're using the arity information to simplify. If 0 or 1, no splitting will be performed, except that EL relations will always be split, no matter what the split limit is.") (defparameter *simplify-equal-symbols-literal?* nil "[Cyc] If T, the simplifier will simplify #$equalSymbols literals with one variable argument and one bound argument by substituting the binding throughout the conjunction. WARNING: this may cause scoping problems and has not been fully tested.") (defparameter *simplify-true-sentence-away?* nil "[Cyc] If T, the simplifier will be more zealous in simplifying #$trueSentence literals away. WARNING: This may cause inference problems and has not been fully tested.") (defglobal *skolem-axiom-table* (make-hash-table :size 2048 :test #'equal) "[Cyc] Table of definitions of known skolems.") (defparameter *infer-skolem-result-isa-via-arg-constraints?* t "[Cyc] In the absence of explicit #$isa pos-lits, use applicable arg-isa constraints to infer the #$resultIsa of a skolem?") (defparameter *interpolate-singleton-arg-isa?* nil "[Cyc] Should skolem arg-isa constraints be interpolated into a singleton set?") (defparameter *clothe-naked-skolems?* nil "[Cyc] Should newly-created skolems have #$termDependsOn assertions asserted about them. If NIL, we assume that the caller will assert the definitional assertions of the newly-created skolems. If T, the czer will assert #$termDependsOn assertions in lieu of having actual definitional assertions. This is for use in testing code that calls canonicalize-assert directly.") (defparameter *preds-of-computed-skolem-gafs* (list #$isa #$arity #$arityMin #$arityMax #$resultIsa #$resultGenl #$resultIsaArg #$resultGenlArg #$arg1Isa #$arg2Isa #$arg3Isa #$arg4Isa #$arg5Isa #$arg6Isa) "[Cyc] Predicates for gafs that reference skolem functions that may be computed and asserted by the canonicalizer and may be manually edited.") (deflexical *preds-of-editable-skolem-gafs* (append (list #$isa #$arity #$arityMin #$arityMax #$resultIsa #$resultGenl #$resultIsaArg #$resultGenlArg #$resultQuotedIsa #$evaluationResultQuotedIsa) *arg-isa-binary-preds* *arg-isa-ternary-preds* *arg-quoted-isa-binary-preds* *arg-quoted-isa-ternary-preds* (list #$myCreator #$myCreationTime #$myCreationSecond #$comment #$sharedNotes #$skolemizeForward)) "[Cyc] Predicates for gafs that reference skolem functions that may be computed and asserted by the canonicalizer, or the interface time-stamper, or may be manually edited.") (defparameter *empty-skolems* nil "[Cyc] Skolems having no defining assertions encountered while reinitializing *skolem-axiom-table*.") (defparameter *mal-skolems* nil "[Cyc] Skolems diagnosed as having problems while reinitializing *skolem-axiom-table*.") (defparameter *express-as-rule-macro?* nil) (defparameter *express-as-genls?* nil) (defparameter *express-as-arg-isa?* nil) (defparameter *express-as-arg-genl?* nil) (defparameter *express-as-genl-predicates?* nil) (defparameter *express-as-genl-inverse?* nil) (defparameter *express-as-inter-arg-isa?* nil) (defparameter *express-as-disjoint-with?* nil) (defparameter *express-as-negation-predicates?* nil) (defparameter *express-as-negation-inverse?* nil) (defparameter *express-as-reflexive?* nil) (defparameter *express-as-symmetric?* nil) (defparameter *express-as-transitive?* nil) (defparameter *express-as-irreflexive?* nil) (defparameter *express-as-asymmetric?* nil) (defparameter *express-as-relation-type?* nil) (defparameter *express-as-required-arg-pred?* nil) (defparameter *tense-czer-mode* :default) (deflexical *valid-tense-czer-modes* (list :default :query :assert)) (defun valid-tense-czer-mode-p (mode) (member-eq? mode *valid-tense-czer-modes*))
23,453
Common Lisp
.lisp
341
56.40176
344
0.658507
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
18981474e61c9e51e5e78f7b8db3a573a0e25a40bcc76d85917dca073f2136a6
6,728
[ -1 ]
6,729
nart-index-manager.lisp
white-flame_clyc/larkc-cycl/nart-index-manager.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO - very similar in form to constant-index-manager. there's also unrepresented-term-index-manager, nart-hl-formula-manager (defglobal *nart-index-manager* :uninitialized "[Cyc] The KB object manager for nart indices.") (deflexical *nart-index-lru-size-percentage* 20 "[Cyc] Based on arete experiments, only 20% of all narts are touched during normal inference, so we'll make a conservative guess that every one of those touched the nart's index.") (defun setup-nart-index-table (size exact?) (setf *nart-index-manager* (new-kb-object-manager "nart-index" size *nart-index-lru-size-percentage* #'load-nart-index-from-cache exact?))) (defun swap-out-all-pristine-nart-indices () (swap-out-all-pristine-kb-objects-int *nart-index-manager*)) (defun initialize-nart-index-hl-store-cache () (initialize-kb-object-hl-store-cache *nart-index-manager* "nat-indices" "nat-indices-index"))
2,586
Common Lisp
.lisp
44
49.454545
184
0.689286
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
120e25b87be54747cf6c58318176dae08fe63d2754a0b7c845d60ad0c7f97505
6,729
[ -1 ]
6,730
obsolete.lisp
white-flame_clyc/larkc-cycl/obsolete.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO - mark everything as deprecated. Presumably things in this file are still referenced. (defun cycl-system-number () "[Cyc] Obsolete -- use CYC-REVISION-NUMBERS." (or (first (cyc-revision-numbers)) 0)) (defun cycl-patch-number () "[Cyc] Obsolete -- use CYC-REVISION-NUMBERS." (or (second (cyc-revision-numbers)) 0)) (defun reifiable-nat? (term &optional (var? #'cyc-var?) mt) (reifiable-naut? term var? mt)) (defun cnat-p (object &optional (var? #'cyc-var?)) (closed-naut? object var?))
1,919
Common Lisp
.lisp
40
44.725
94
0.757135
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
853eaad6b25169d14a2cd2effbd9e234afd8ae24c40d360763849c3b143d6f25
6,730
[ -1 ]
6,731
fort-types-interface.lisp
white-flame_clyc/larkc-cycl/fort-types-interface.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; No macros declared in this file, should be pretty complete. (defun fort-has-type? (fort type &optional mt) (when (fort-p fort) ;; TODO - this is very obviously a macro expansion that encompasses these bindings (let ((*mt* (update-inference-mt-relevance-mt mt)) (*relevant-mt-function* (update-inference-mt-relevance-function mt)) (*relevant-mts* (update-inference-mt-relevance-function mt)) (*sbhl-justification-search-p* nil) (*sbhl-apply-unwind-function-p* nil) (*suspend-sbhl-cache-use?* nil)) (sbhl-predicate-relation-p (get-sbhl-module #$isa) fort type mt)))) (defun isa-quantifier? (term &optional mt) "[Cyc] Is TERM a quantifier?" (if (fort-p term) (quantifier-p term) (or (isa? term #$Quantifier mt) (quiet-sufficient-defns-admit? #$Quantifier term mt)))) (defun fort-has-type-in-any-mt? (fort type) (with-all-mts (fort-has-type? fort #$Collection))) (defun collection-in-any-mt? (fort) "[Cyc] Is FORT a collection in any mt?" (with-all-mts (fort-has-type? fort #$Collection))) (defun collection? (fort) "[Cyc] Is FORT a collection?" (collection-in-any-mt? fort)) (defun collection-p (fort) "[Cyc] Is FORT a collection?" (collection-in-any-mt? fort)) (defun isa-collection? (term &optional mt) "[Cyc] Is TERM a collection?" (if (fort-p term) (collection? term) (or (isa? term #$Collection mt) (missing-larkc 5373)))) (defun predicate-in-any-mt? (fort) "[Cyc] Is FORT a predicate in any mt?" (with-all-mts (fort-has-type? fort #$Predicate))) (defun predicate? (fort) "[Cyc] Is FORT a predicate?" (predicate-in-any-mt? fort)) (defun predicate-p (fort) "[Cyc] Is FORT a predicate?" (predicate-in-any-mt? fort)) (defun isa-predicate? (term &optional mt) "[Cyc] Is TERM a predicate?" (if (fort-p term) (predicate-p term) (or (isa? term #$Predicate mt) (missing-larkc 5375)))) (defun function-in-any-mt? (fort) "[Cyc] Is FORT in the *FORTS-TYPED-FUNCTION-DENOTATIONAL*" (with-all-mts (fort-has-type fort #$Function-Denotational))) (defun functor? (fort) "[Cyc] Is FORT a non-predicate function?" (non-predicate-function? fort)) (defun non-predicate-function? (fort) "[Cyc] Is FORT a non-predicate function?" (function-in-any-mt? fort)) (defun function? (fort) "[Cyc] Is FORT a non-predicate function?" (non-predicate-function? fort)) (defun mt-in-any-mt? (fort) "[Cyc] Return T iff FORT is a microtheory in any mt. Note Currently (2/00) we assume that microtheories must be defined as such in the *MT-MT*." (with-all-mts (fort-has-type fort #$Microtheory))) (defun mt? (fort) "[Cyc] Is FORT a microtheory?" (mt-in-any-mt? fort)) (defun isa-mt? (term &optional mt) "[Cyc] Is TERM a microtheory?" (cond ((fort-p term) (mt? term)) ((hlmt-naut-p term) (hlmt? term)) (t (or (isa? term #$Microtheory) (missing-larkc 5377))))) (defun relation-p (fort) "[Cyc] Is FORT a relation?" (fort-has-type-in-any-mt? fort #$Relation)) (defun sentential-relation-p (fort) "[Cyc] Is FORT a sentential relation?" (or (logical-connective-p fort) (quantifier-p fort))) (defun anti-symmetric-binary-predicate-p (fort) "[Cyc] Is FORT an anti-symmetric binary predicate?" (fort-has-type-in-any-mt? fort #$AntiSymmetricBinaryPredicate)) (defun anti-transitive-binary-predicate-p (fort) "[Cyc] Is FORT an anti-transitive binary predicate?" (fort-has-type-in-any-mt? fort #$AntiTransitiveBinaryPredicate)) (defun asymmetric-binary-predicate-p (fort) "[Cyc] Is FORT an asymmetric binary predicate?" (fort-has-type-in-any-mt? fort #$AsymmetricBinaryPredicate)) (defun bookkeeping-predicate-p (fort) "[Cyc] Is FORT a bookkeeping predicate?" (fort-has-type-in-any-mt? fort #$BookkeepingPredicate)) (defun broad-microtheory-p (fort) "[Cyc] Is FORT a broad microtheory?" (fort-has-type-in-any-mt? fort #$BroadMicrotheory)) (defun commutative-relation? (relation) "[Cyc] Return T iff RELATION is a commutative relation." (commutative-relation-p relation)) (defun commutative-relation-p (fort) "[Cyc] Is FORT a commutative relation?" (fort-has-type-in-any-mt? fort #$CommutativeRelation)) (defun commutative-predicate-p (fort) "[Cyc] Is FORT a commutative predicate?" (and (commutative-relation-p fort) (predicate-p fort))) (defun distributing-meta-knowledge-predicate-p (fort) "[Cyc] Is FORT a distributing meta knowledge predicate?" (fort-has-type-in-any-mt? fort #$DistributingMetaKnowledgePredicate)) (defun el-relation-p (fort) "[Cyc] Is FORT an EL relation?" (fort-has-type-in-any-mt? fort #$ELRelation)) (defun isa-el-relation? (term &optional mt) "[Cyc] Is TERM an EL relation?" (if (fort-p term) (el-relation-p term) (or (isa? term #$ELRelation mt) (missing-larkc 5395)))) (defun evaluatable-function-p (fort) "[Cyc] Is FORT an evaluatable function?" (fort-has-type-in-any-mt? fort #$EvaluatableFunction)) (defun evaluatable-predicate-p (fort &optional mt) "[Cyc] Is FORT an evaluatable predicate?" (fort-has-type? fort #$EvaluatablePredicate mt)) (defun irreflexive-binary-predicate-p (fort) "[Cyc] Is FORT an irreflexive binary predicate?" (fort-has-type-in-any-mt? fort #$IrreflexiveBinaryPredicate)) (defun logical-connective-p (fort) "[Cyc] Is FORT a logical connective?" (fort-has-type-in-ny-mt? fort #$LogicalConnective)) (defun isa-logical-connective? (term &optional mt) "[Cyc] Is TERM a logical connective?" (if (fort-p term) (logical-connective-p term) (or (isa? term #$LogicalConnective mt) (missing-larkc 5400)))) (defun microtheory-designating-relation-p (fort) "[Cyc] Is FORT a microtheory designating relation?" (fort-has-type-in-any-mt? fort #$MicrotheoryDesignatingRelation)) (defun partially-commutative-relation-p (fort) "[Cyc] Is FORT a partially commutative relation?" (fort-has-type-in-any-mt? fort #$PartiallyCommutativeRelation)) (defun partially-commutative-predicate-p (fort) "[Cyc] Is FORT a partially commutative predicate?" (isa? fort #$PartiallyCommutativePredicate *anect-mt*)) (defun quantifier-p (fort) "[Cyc] Is FORT a quantifier?" (fort-has-type-in-any-mt? fort #$Quantifier)) (defun reflexive-binary-predicate-p (fort) "[Cyc] Is FORT a reflexive binary predicate?" (fort-has-type-in-any-mt? fort #$ReflexiveBinaryPredicate)) (defun reifiable-function-p (fort) "[Cyc] Is FORT a reifiable function?" (fort-has-type-in-any-mt? fort #$ReifiableFunction)) (defun isa-reifiable-function? (term &optional mt) (if (fort-p term) (reifiable-function-p term) (or (isa? term #$ReifiableFunction mt) (missing-larkc 5407)))) (defun scoping-relation-p (fort) "[Cyc] Is FORT a scoping relation?" (fort-has-type-in-any-mt? fort #$ScopingRelation)) (defun isa-scoping-relation? (term &optional mt) "[Cyc] Is TERM a scoping relation?" (if (fort-p term) (scoping-relation-p term) (or (isa? term #$ScopingRelation mt) (missing-larkc 5409)))) (defun sibling-disjoint-collection-p (fort) "[Cyc] Is FORT a sibling disjoint collection?" (fort-has-type-in-any-mt? fort #$SiblingDisjointCollectionType)) (defun skolem-function-p (fort) "[Cyc] Is FORT a skolem function?" (fort-has-typein-any-mt? fort #$SkolemFunction)) (defun symmetric-binary-predicate-p (fort) "[Cyc] Is FORT a symmetric binary predicate?" (fort-has-type-in-any-mt? fort #$SymmetricBinaryPredicate)) (defun transitive-binary-predicate-p (fort) "[Cyc] Is FORT a transitive binary predicate?" (fort-has-type-in-any-mt? fort #$TransitiveBinaryPredicate)) (defun variable-arity-relation-p (fort) "[Cyc] Is FORT a variable arity relation?" (fort-has-type-in-any-mt? fort #$VariableArityRelation)) (defun isa-variable-arity-relation? (term &optional mt) "[Cyc] Is TERM a variable arity relation?" (if (fort-p term) (variable-arity-relation-p term) (or (isa? term #$VariableArityRelation mt) (missing-larkc 5414)))) (defun bounded-existential-quantifier-p (object) (with-all-mts (fort-has-type? object #$ExistentialQuantifier-Bounded))) (defun evaluatable-relation-contextualized-p (fort) "[Cyc] Is FORT a contextualized evaluatable relation?" (fort-has-type-in-any-mt? fort #$EvaluatableRelation-Contextualized)) (deflexical *proprietary-constant?-caching-state* nil)
9,885
Common Lisp
.lisp
229
39.384279
91
0.718492
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
d9f0ea2c9ebd9f1ccb3a593888592ee8b02ba3a7f9f04e9783919b8352c2da45
6,731
[ -1 ]
6,732
at-vars.lisp
white-flame_clyc/larkc-cycl/at-vars.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; AT = arg-type? ;; For all variable declarations, note-state-variable-documentation registers the docstring, and the variable symbol name is pushnew'd to a state variable list. Wrapping this into a macro, although none seemed to be defined in this file. (defmacro def-state-var (name val varlist &body (&optional docstring (definer 'defparameter))) `(progn (,definer ,name ,val ,docstring) (note-state-variable-documentation ',name ,docstring) (pushnew ',name ,varlist))) (defmacro def-at-state-var (name val &body (&optional docstring (definer 'defparameter))) `(def-state-var ,name ,val *at-state-variables* ,docstring ,definer)) (defmacro def-defn-state-var (name val &body (&optional docstring (definer 'defparameter))) `(def-state-var ,name ,val *defn-state-variables* ,docstring ,definer)) (def-at-state-var *semantic-dnf-hl-filtering-enabled* nil "[Cyc] Should the inference engine use arg-type tests in order to filter-out non-wff inferences?") (def-at-state-var *at-check-fn-symbol?* t "[Cyc] Require function symbols be instances of #$Function-Denotational?") (def-at-state-var *at-check-arg-genls?* t "[Cyc] Enforce #$argGenl constraints?") (def-at-state-var *at-check-arg-isa?* t "[Cyc] Enforce argIsa constraints?") (def-at-state-var *at-check-arg-quoted-isa?* t "[Cyc] Enforce argQuotedIsa constraints?") (def-at-state-var *at-check-arg-not-isa?* t "[Cyc] Enforce argNotIsa constraints?") (def-at-state-var *at-check-arg-types?* t "[Cyc] Enforce arg-typing constraints?") (def-at-state-var *at-possibly-check-defining-mts?* nil "[Cyc] Is #$definingMt constraint enforcement available?") (def-at-state-var *at-check-defining-mts?* t "[Cyc] Enforce #$definingMt constraints?") (defun* at-check-defining-mts-p () (:inline t) (and *at-check-defining-mts?* *at-possibly-check-defining-mts?*)) (def-at-state-var *at-check-inter-arg-isa?* t "[Cyc] Enforce #$interArgIsa constraints?") (def-at-state-var *at-check-inter-arg-not-isa?* t "[Cyc] Enforce #$interArgNotIsa constraints?") (def-at-state-var *at-check-inter-arg-genl?* nil "[Cyc] Enforce #$interArgGenl constraints?") (def-at-state-var *at-check-non-constant-inter-arg-isa?* t "[Cyc] Enforce interArgIsa constraints for non-constants?") (def-at-state-var *at-check-non-constant-inter-arg-genl?* t "[Cyc] Enforce interArgGenl constraints for non-constants?") (def-at-state-var *at-check-non-constant-inter-arg-format?* t "[Cyc] Enforce interArgFormat1-2 (and similar) constraints for non-constants?") (def-at-state-var *at-check-not-isa-disjoint?* t "[Cyc] Enforce #$argIsa constraints for non-constants?") (def-at-state-var *at-check-not-quoted-isa-disjoint?* t "[Cyc] Enforce #$argQuotedIsa constraints for non-constants?") (def-at-state-var *at-check-not-genls-disjoint?* t "[Cyc] Enforce #$argGenl constraints for non-constants?") (def-at-state-var *at-check-not-mdw?* t "[Cyc] Enforce :NOT-DISJOINT constraints using mdw module?") (def-at-state-var *at-check-not-sdc?* t "[Cyc] Enforce :NOT-DISJOINT constraints using sdc module?") (def-at-state-var *at-check-arg-format?* t "[Cyc] Enforce #$argformat constraints?") (def-at-state-var *at-check-sef?* t "[Cyc] Enforce #$singleEntryFormatInArgs #$argformat constraints?") (def-at-state-var *at-check-relator-constraints?* t "[Cyc] Enforce asymmetric-predicate and similar constraints?") (def-at-state-var *at-ensure-consistency?* nil "[Cyc] Enforce consistency at constraint standard (:not-isa-disjoint et al) in addition to entails standard (:isa et al)?") (def-at-state-var *at-pred-constraints* (list :asymmetric-predicate :anti-symmetric-predicate :irreflexive-predicate :anti-transitive-predicate :negation-preds :negation-inverses)) (def-at-state-var *at-predicate-violations* nil "[Cyc] Relevant at predicate violations.") (def-at-state-var *at-check-inter-assert-format-w/o-arg-index?* t "[Cyc] Enforce inter-assert formats even when pred is only index?") (def-at-state-var *at-check-inter-assert-format-w/o-arg-index-gaf-count-threshold* 100 "[Cyc] Max number of relevant gafs to permit enforcing inter-assert formats when pred is only index?") (def-at-state-var *fag-search-limit* nil "[Cyc] Max number of relevant gafs to permit using find-accessible-gaf?") (def-at-state-var *at-gaf-search-limit* 100 "[Cyc] Default max number of relevant gafs to permit enforcing at constraints using find-accessible-gaf (e.g., negation-preds et al)?") (def-at-state-var *at-check-inter-arg-format?* t "[Cyc] Enforce #$interArgFormat1-2 (and similar) constraints?") (def-at-state-var *at-check-inter-arg-different?* t "[Cyc] Enforce #$interArgDifferent (and similar) constraints?") (def-at-state-var *at-check-genl-preds?* t "[Cyc] Enforce arg-constraints of genlPreds?") (def-at-state-var *at-check-genl-inverses?* t "[Cyc] Enforce arg-constraints of genlInverse?") (def-at-state-var *at-include-isa-literal-constraints* t "[Cyc] Include explicit #$isa literals when computing type constraints?") (def-at-state-var *at-include-genl-literal-constraints* t "[Cyc] Include explicit #$genls literals when computing type constraints?") (def-at-state-var *gather-at-constraints?* nil "[Cyc] Collect applicable at constraints?") (def-at-state-var *gather-at-assertions?* nil "[Cyc] Collect applicable at assertions?") (def-at-state-var *gather-at-format-violations?* nil "[Cyc] Collect relevant at format violations?") (def-at-state-var *gather-at-different-violations?* nil "[Cyc] Collect relevant at different violations?") (def-at-state-var *gather-at-predicate-violations?* nil "[Cyc] Collect relevant at predicate violations (e.g., asymmetry, negationPreds)?") (def-at-state-var *at-format-violations* nil "[Cyc] Relevant at format violations.") (def-at-state-var *at-different-violations* nil "[Cyc] Relevant at different violations.") (def-at-state-var *within-at-suggestion?* nil "[Cyc] Is at module currently trying to formula a suggested fix?") (def-at-state-var *within-at-mapping?* nil "[Cyc] Is at module currently executing a mapping search?.") (def-at-state-var *at-break-on-failure?* nil "[Cyc] Break when an at violation is encountered?") (def-at-state-var *accumulating-at-violations?* nil "[Cyc] Continue at checks even after constraint failure?") (def-at-state-var *noting-at-violations?* nil "[Cyc] Should arg-type violations be recorded for presentation?") (def-at-state-var *at-trace-level* 1 "[Cyc] Controls extent of tracing, warnings, etc., for the arg-type module [0 .. 5].") (def-at-state-var *at-test-level* 3 "[Cyc] Controls extent of testing for the arg-type module [0 .. 5].") (def-at-state-var *appraising-disjunct?* nil "[Cyc] Is the formula being considered by the arg-type module a disjoined sub-formula?") (def-at-state-var *within-decontextualized?* nil "[Cyc] Is the formula being considered by arg-type module a decontextualized literal?") (def-at-state-var *within-disjunction?* nil "[Cyc] Is the subformula being canonicalized within a disjunction?") (def-at-state-var *within-conjunction?* nil "[Cyc] Is the subformula being canonicalized within a conjunction?") (def-at-state-var *within-negated-disjunction?* nil "[Cyc] Is the subformula being canonicalized within both negation and disjunction?") (def-at-state-var *within-negated-conjunction?* nil "[Cyc] Is the subformula being canonicalized within both negation and conjunction?") (def-at-state-var *within-function?* nil "[Cyc] Is the formula being canonicalized referenced within a function expression?") (def-at-state-var *within-predicate?* nil "[Cyc] Is the formula being canonicalized referenced within a predicate?") (def-at-state-var *within-tou-gaf?* nil "[Cyc] Is the formula being canonicalized a termOfUnit gaf?") (defun* within-tou-gaf? () (:inline t) "[Cyc] Return T iff the formula being canonicalized isa a termOfUnit gaf." *within-tou-gaf?*) (def-at-state-var *relax-arg-constraints-for-disjunctions?* t "[Cyc] Should arg-type constraints be weakened (possibly-true vs provably-true) within disjuncts?") (def-at-state-var *at-relax-arg-constraints-for-opaque-expansion-nats?* t "[Cyc] Within expansions should arg-type constraints be forgiven for expandable nats?") (def-at-state-var *at-admit-consistent-nauts?* t "[Cyc] Should the arg-type module admit unreified function terms that are consistent (i.e., possibly-true vs provably-true) wrt arg-type constraints?") (def-at-state-var *at-admit-consistent-narts?* t "[Cyc] Should the arg-type module admit reified function terms that are consistent (i.e., possibly-true vs provably-true) wrt arg-type constraints?") (def-at-state-var *at-result* nil "[Cyc] Accumulates results of current at query") (def-at-state-var *at-some-arg-isa?* nil "[Cyc] Is any arg-isa constraint found during at arg-isa analysis for a given arg, relation and argnum?") (def-at-state-var *at-some-arg-isa-required?* nil "[Cyc] Must there be some arg-isa constraint applicable to an arg for a given arg, relation, argnum to be wf?") (defun* at-some-arg-isa-required? () (:inline t) "[Cyc] Returns boolean, must there be some arg-isa constraint applicable to an arg for a given arg, relation, argnum to be WF?" *at-some-arg-isa-required?*) (def-at-state-var *at-consider-multiargs-at-pred?* t "[Cyc] During arg-type analysis do we consider multi-arg (argsIsa) constraints for specified args (arg1).") (defun consider-multiargs-at-pred? () "[Cyc] Returns boolean, during arg-type analysis do we consider multi-arg (argsIsa) constraints for specified args (arg1)?" *at-consider-multiargs-at-pred?*) (def-at-state-var *at-isa-constraints* (make-hash-table) "[Cyc] Accumulates applicable at isa constraints.") (def-at-state-var *at-genl-constraints* (make-hash-table) "[Cyc] Accumulates applicable at genl constraints.") (def-at-state-var *at-format-constraints* (make-hash-table) "[Cyc] Accumulates applicable at format constraints.") (def-at-state-var *at-different-constraints* (make-hash-table) "[Cyc] Accumulates applicable at different constraints.") (def-at-state-var *at-isa-assertions* (make-hash-table) "[Cyc] Accumulates applicable at isa assertions.") (def-at-state-var *at-genl-assertions* (make-hash-table) "[Cyc] Accumulates applicable at genl assertions.") (def-at-state-var *at-format-assertions* (make-hash-table) "[Cyc] Accumulates applicable at format assertions.") (def-at-state-var *at-different-assertions* (make-hash-table) "[Cyc] Accumulates applicable at different assertions.") (def-at-state-var *at-mode* nil "[Cyc] The type of at test currently being applied (e.g., :arg-genls).") (def-at-state-var *at-constraint-type* nil "[Cyc] The type of at constraint currently being applied (e.g., :isa :genls).") (def-at-state-var *at-arg-type* nil "[Cyc] Type of arg being considered within arg-type search [:naut :weak-fort :strong-fort].") (def-at-state-var *at-base-fn* nil "[Cyc] Fn applied to each applicable arg-constraint assertion during at search.") (def-at-state-var *at-formula* nil "[Cyc] The formula being appraised.") (def-at-state-var *at-pred* nil "[Cyc] The current at-module constraint pred (e.g., #$interArgIsa1-2).") (def-at-state-var *at-inverse* nil "[Cyc] The inverse of the current at-module constraint pred (e.g., #$interArgIsa2-1).") (def-at-state-var *at-reln* nil "[Cyc] The relation whose args are currently being appraised.") (def-at-state-var *at-arg* nil "[Cyc] The particular arg that is currently being appraised.") (def-at-state-var *at-argnum* nil "[Cyc] The position of the arg that is currently being appraised.") (def-at-state-var *at-arg1* nil "[Cyc] The 1st arg of the literal or function-term that is currently being appraised.") (def-at-state-var *at-arg2* nil "[Cyc] The 2nd arg of the literal or function-term that is currently being appraised.") (def-at-state-var *at-ind-argnum* nil "[Cyc] The position of the independent arg that is constraining the dependent arg.") (def-at-state-var *at-ind-arg* nil "[Cyc] The independent arg that is constraining the dependent arg being appraised.") (def-at-state-var *at-ind-isa* nil "[Cyc] The isa of the independent arg that is constraining the dependent arg.") (def-at-state-var *at-ind-genl* nil "[Cyc] The genl of the independent arg that is constraining the dependent arg.") (def-at-state-var *at-arg-isa* nil "[Cyc] The isa of the dependent arg that is being appraised.") (def-at-state-var *at-source* nil "[Cyc] The constant indexing the current at constraint (e.g., may be a genlPred of *at-reln*).") (def-at-state-var *at-mapping-genl-inverses?* nil "[Cyc] Dynamic state variable: are we looking at inverses instead of genlPreds?") (def-at-state-var *at-search-genl-preds?* t "[Cyc] Consider genlPreds during current at search?") (def-at-state-var *at-search-genl-inverses?* t "[Cyc] Consider genlInverses during current at search?") (defun* at-searching-genl-preds? () (:inline t) *at-search-genl-preds?*) (defun* at-searching-genl-inverses? () (:inline t) *at-search-genl-inverses?*) (def-at-state-var *at-profile-term* nil "[Cyc] The term (var, constant, ...) that is being profiled during this at analysis.") (def-at-state-var *at-constraint-gaf* nil "[Cyc] The arg-type constraint assertion currently being considered.") (def-at-state-var *include-at-constraint-gaf?* t "[Cyc] Boolean: Should errors reference the arg-type constraint assertion currently being considered.") (def-at-state-var *at-var-isa* nil "[Cyc] The accumulating inter-reference isa constraints applicable to a given variable in a formula.") (def-at-state-var *at-var-genl* nil "[Cyc] The accumulating inter-reference genl constraints applicable to a given variable in a formula.") (def-at-state-var *at-var-types-standard* :not-disjoint "[Cyc] The standard for acceptable arg-type constraints applicable to variables.") (def-at-state-var *at-assume-conjuncts-independent?* t "[Cyc] Whether arg-type checking for variables in a conjunction should assume that each of the conjuncts is independent. This is true, for example, during assert, but false, for example, when wff-checking the results of some parsers.") (def-at-state-var *current-at-violation* nil "[Cyc] Description of most recent violation of applicable arg-type constraints.") (def-at-state-var *at-violations* nil "[Cyc] Descriptions of how a relational expresion is not valid wrt arg-type constraints.") (def-at-state-var *at-disjoins-space* nil "[Cyc] SBHL space used for marking disjoins of arg types.") (def-at-state-var *at-isa-space* nil "[Cyc] SBHL space used for marking all-isa of arg.") (def-at-state-var *at-genls-space* nil "[Cyc] SBHL space used for marking all-genls of arg.") (def-defn-state-var *at-defns-available?* t "[Cyc] Make defns available for at queries?") (def-defn-state-var *at-apply-necessary-defns?* t "[Cyc] Enforce all applicable necessary defns during defn query?") (def-defn-state-var *sort-suf-defn-assertions?* t "[Cyc] Are the cached suf-defn assertions sorted to promote some optimality criteria?") (def-defn-state-var *sort-suf-function-assertions?* nil "[Cyc] Are the cached suf-function assertions sorted to promote some optimality criteria?") (def-defn-state-var *at-collection-specific-defns* nil "[Cyc] Defns which reference (defn-collection) and so cannot be cached in defn-fn-histories." defvar) (def-defn-state-var *defn-trace-level* 1 "[Cyc] Controls extent of tracing, warnings, etc., for the arg-type module [0 .. 5].") (def-defn-state-var *defn-test-level* 3 "[Cyc] Controls extent of testing for the arg-type module [0 .. 5].") (def-defn-state-var *defn-meters?* nil "[Cyc] Activate metering of functions within defn module?") ;; TODO - these are defvar instead of deparameter? will these tables be dynamically bound? (def-defn-state-var *suf-defn-cache* (make-hash-table) nil defvar) (def-defn-state-var *suf-quoted-defn-cache* (make-hash-table) nil defvar) (def-defn-state-var *defn-meter-caches* nil "[Cyc] List of caches used for metering functions in defn module.") (def-defn-state-var *defn-collection* nil "[Cyc] The collection with which the current defn is associated.") (def-defn-state-var *permitting-denotational-terms-admitted-by-defn-via-isa?* t "[Cyc] Should defns admit a denotation term that #$isa the *defn-collection* ?") (defun permitting-denotational-terms-admitted-by-defn-via-isa? () *permitting-denotational-terms-admitted-by-defn-via-isa?*) (def-defn-state-var *at-defn* nil "[Cyc] Current defn-assertion being considered.") (def-defn-state-var *at-defns* nil "[Cyc] Current defn-assertions being considered.") (def-defn-state-var *suf-function-cache* (make-hash-table) nil defvar) (def-defn-state-var *suf-quoted-function-cache* (make-hash-table) nil defvar) (def-defn-state-var *at-function* nil "[Cyc] Current sufficient-function assertion being considered.") (def-defn-state-var *at-functions* nil "[Cyc] Current sufficient-function assertions being considered.") (def-defn-state-var *defn-fn-history-default-size* 32 "[Cyc] The initial size of each nested defn-function cache.") (def-defn-state-var *defn-col-history-default-size* 64 "[Cyc] The initial size of each nested defn-collection cache.") (def-defn-state-var *defn-col-history* :uninitialized "[Cyc] The cache used (by the current defn invocation) to prevent multiple calls to a single defn collection.") (def-defn-state-var *quoted-defn-col-history* :uninitialized "[Cyc] The cache used (by the current quoted defn invocation) to prevent multiple calls to a single defn collection.") (def-defn-state-var *defn-fn-history* :uninitialized "[Cyc] The cache used (by the current defn invocation) to prevent multiple calls to a single defn function.") (def-defn-state-var *quoted-defn-fn-history* :uninitialized "[Cyc] The cache used (by the current quoted defn invocation) to prevent multiple calls to a single defn function.") (def-defn-state-var *defn-stack* :uninitialized "[Cyc] A stack of defns being called, to prevent infinite recursion. The key for the hashtable is the collection-defn function, and the value is a list of arguments. It's a list because it's fine to recurse on a defn with a different argument.")
19,921
Common Lisp
.lisp
327
58.015291
247
0.742355
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
31accf1ddc6fbd85aaf0cbffc05bd581c0f3ba6b2415d721cecc995e90e4b98d
6,732
[ -1 ]
6,733
hlmt.lisp
white-flame_clyc/larkc-cycl/hlmt.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defvar *hlmts-supported?* t "[Cyc] Whether we allow non-atomic unreified MTs.") (defun* hlmts-supported? () (:inline t) *hlmts-supported?*) (defun disable-hlmts () (setf *hlmts-supported?* nil)) (deflexical *default-monad-mt* #$UniversalVocabularyMt) (deflexical *default-temporal-mt-time-parameter* #$Null-TimeParameter) (deflexical *default-atemporal-time-parameter* #$Null-TimeParameter) (deflexical *default-atemporal-genlmt-time-parameter* #$TimePoint) (deflexical *default-atemporal-specmt-time-parameter* #$Null-TimeParameter) (deflexical *default-mt-time-interval* #$Always-TimeInterval) (deflexical *default-mt-time-parameter* #$Null-TimeParameter) (deflexical *mt-space-function* #$MtSpace) (deflexical *temporal-dimension-functions* (list #$MtTimeWithGranularityDimFn #$MtTimeDimFn)) (deflexical *mt-dimension-types* (list :monad :time) "[Cyc] The identifiers used to specify different types of slices of MT space. This is an ordered list, and describes the canonical ordering of dimensions.") (deflexical *mt-dimension-functions* (list #$MtDim #$MtTimeDimFn #$MtTimeWithGranularityDimFn) "[Cyc] The functions which carve out slices of MT space.") (deflexical *context-space-functions* (cons *mt-space-function* *mt-dimension-functions*) "[Cyc] The functions which are valid arg0s for a HLMT.") (deflexical *anytime-psc* #$AnytimePSC) (deflexical *anytime-during-psc-fn* #$AnytimeDuringPSCFn) (deflexical *unindexed-hlmt-syntax-constants* (list #$MtSpace #$MtDim #$MtTimeDimFn #$MtTimeWithGranularityDimFn #$mtTimeIndex #$mtTimeParameter #$mtMonad #$Always-TimeInterval #$Null-TimeParameter #$TimePoint) "[Cyc] Constants which are part of HLMT syntax and which therefore are not fully indexed, for pragmatic reasons.") (defun* possibly-mt-p (object) (:inline t) (possibly-hlmt-p object)) (defun* possibly-hlmt-p (object) (:inline t) (or (possibly-fo-naut-p object) (hlmt-p object))) (defun* fort-or-chlmt-p (object) (:inline t) "[Cyc] Whether OBJECT is a fort-p or closed-hlmt-p." (or (fort-p object) (closed-hlmt-p object))) (defun* chlmt-p (object) (:inline t) "[Cyc] Shorthand for closed-hlmt-p." (closed-hlmt-p object)) (defun* closed-hlmt-p (object) (:inline t) "[Cyc] Return T iff OBJECT is an HLMT, and is closed." (ret (cand (hlmt-p object) (cycl-ground-expression-p object)))) (defun hlmt-p (object) "[Cyc] Returns T if OBJECT might be an HLMT, that is, an HL representation of a microtheory. Hence it must be closed. NOTE: Returns true iff OBJECT actually is an HLMT." (if *hlmts-supported?* (hlmt-p-time object) (hlmt-p-no-time object))) (defun hlmt-p-no-time (object) (or (valid-fort? object) (mt-union-naut-p object))) (defun possibly-hlmt-naut-p (object) (when (possibly-naut-p object) (let ((functor (naut-functor object))) (or (missing-larkc 12260))))) (defun hlmt-naut-p (object) (and (possibly-hlmt-naut-p object) (or (missing-larkc 12292)))) (defun mt-space-naut-p (object) (and (possibly-naut-p object) (missing-larkc 12303))) (defun mt-union-naut-p (object) (and (possibly-naut-p object) (mt-union-function-p (naut-functor object)))) (defun* mt-union-function-p (object) (:inline t) (eq object #$MtUnionFn)) (defun hlmt? (object) "[Cyc] Like HLMT-P but also does fort-types checks that the relevant bits have fort-types of microtheories, and arity checks on all the dimensions." (and (cycl-represented-term-p object) (hlmt?-int object))) (defun hlmt?-int (object) (if *hlmts-supported?* (missing-larkc 12280) (hlmt?-no-time object))) (defun hlmt?-no-time (object) (and (hlmt-p object) (or (monad-mt? object) (mt-union-naut? object)))) (defun mt-union-naut? (object) (and (possibly-naut-p object) (mt-union-function-p (naut-functor object)) (missing-larkc 12311))) (defun hlmt-equal (object0 object1) "[Cyc] Return whether OBJECT0 is equal to OBJECT1." (if *hlmts-supported?* (equal object0 object1) (eq object0 object1))) (defun hlmt-equal? (object0 object1) "[Cyc] Return whether OBJECT0 is equal to OBJECT1 insofar as all of their dimensions are equal. What constitutes equality for a given dimension is dependent on that dimension." (cond ((hlmt-equal object0 object1) t) ((and (monad-mt-p object0) (monad-mt-p object1)) nil) (t (missing-larkc 12276)))) (defun get-hlmt-dimension (dim hlmt) "[Cyc] Returns the dimension of HLMT specified by DIM." (let ((mt nil) (found? nil)) ;; TODO - this probably was a large macro expansion but the branches ended up missing-larkc (if (monad-mt-p hlmt) (unless found? (let ((dim-var :monad) (mt-var hlmt)) (when (eq dim dim-var) (setf mt mt-var) (setf found? t)))) (missing-larkc 12293)) mt)) (defun reduce-hlmt (hlmt &optional (minimize-mt-union-mts? t)) "[Cyc] Removes default values from HLMT, for more compact storage. NOTE: Result is destructible." (block nil (setf hlmt (transform-mt-union-nauts hlmt minimize-mt-union-mts?)) (let ((monad (hlmt-monad-mt hlmt))) (when (any-or-all-mts-relevant-to-mt? monad) (return monad)) (when (eq monad hlmt) (return hlmt))) (let ((substantial-dimensions nil)) (cond ((monad-mt-p hlmt) (missing-larkc 12270)) ((missing-larkc 12294)))))) (defun transform-mt-union-nauts (hlmt minimize-mt-union-mts?) (cond ((mt-union-naut-p hlmt) (missing-larkc 12338)) ((consp hlmt) (cons (transform-mt-union-nauts (car hlmt) minimize-mt-union-mts?) (transform-mt-union-nauts (cdr hlmt) minimize-mt-union-mts?))) (t hlmt))) (defun valid-hlmt-p (hlmt &optional robust) (when (hlmt-p hlmt) (if robust (cond ((monad-mt-p hlmt) (missing-larkc 12345)) ((missing-larkc 12295))) (valid-monad-mt-p (hlmt-monad-mt hlmt))))) (defun monad-mt-p (object) (or (and (fort-p object) (not (anytime-psc-p object))) (and (mt-union-naut-p object) (every-in-list #'monad-mt-p (missing-larkc 12315))))) (defun valid-monad-mt-p (mt) (or (not mt) (and (valid-fort? mt) (mt? mt)))) (defun monad-mt? (object) (or (and (fort-p object) (mt? object)) (and (mt-union-naut-p object) (every-in-list #'monad-mt? (missing-larkc 12316))))) (defun hlmt-monad-mt (hlmt) (or (hlmt-monad-mt-without-default hlmt) *default-monad-mt*)) (defun hlmt-monad-mt-without-default (hlmt) "[Cyc] Returns nil or monad-mt-p" (if (hlmt-naut-p hlmt) (get-hlmt-dimension :monad hlmt) hlmt)) (deflexical *temporal-dimension-predicates* (list #$mtTimeIndex #$mtTimeParameter)) (defun* anytime-psc-p (object) (:inline t) (eq object *anytime-psc*)) (defun* hlmt-temporal-mt (hlmt) (:inline t) (get-hlmt-dimension :time hlmt))
9,124
Common Lisp
.lisp
204
36.75
179
0.642599
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
b28c2658f0e6a129cac383a3a1ea67fe702853c1f3bb423e37b649154cb523a4
6,733
[ -1 ]
6,734
ghl-search-vars.lisp
white-flame_clyc/larkc-cycl/ghl-search-vars.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (deflexical *ghl-search-property-defaults* '((:direction . :forward) (:tv . :true-def) (:order . :breadth-first))) (defun ghl-search-property-default (property) (cdr (assoc property *ghl-search-property-defaults* :test #'eq))) (defstruct ghl-search graphl-search predicates tv) (defun new-ghl-search (plist) (let ((ghl-search (make-ghl-search)) (graphl-search (new-graphl-search nil))) (set-ghl-graphl-search ghl-search graphl-search) (set-ghl-search-properties ghl-search plist) ghl-search)) (defun destroy-ghl-search (graph-search) (destroy-graphl-search (ghl-search-graphl-search graph-search)) (setf (ghl-search-graphl-search graph-search) :free) (setf (ghl-search-predicates graph-search) :free) (setf (ghl-search-tv graph-search) :free)) ;; Renamed getters (symbol-mapping ghl-graphl-search ghl-search-graphl-search ghl-relevant-predicates ghl-search-predicates ghl-tv ghl-search-tv) ;; Getters that read through the graphl-search reference (defun ghl-result (search) (graphl-result (ghl-graphl-search search))) (defun ghl-space (search) (graphl-space (ghl-graphl-search search))) (defun ghl-direction (search) (graphl-direction (ghl-graphl-search search))) (defun ghl-compute-justify? (search) (graphl-compute-justify? (ghl-graphl-search search))) (defun ghl-goal (search) (graphl-search-goal (ghl-graphl-search search))) (defun ghl-goal-fn (search) (graphl-search-goal-fn (ghl-graphl-search search))) (defun ghl-depth-first-search-p (search) (graphl-depth-first-search-p (ghl-graphl-search search))) (defun set-ghl-search-properties (search plist) (dolist (cons *ghl-search-property-defaults*) (let ((prop (car cons)) (value (cdr cons))) (when value (set-ghl-search-property search prop value)))) (do-plist (prop val plist) (set-ghl-search-property search prop val))) (defun set-ghl-search-property (search property value) (unless value (setf value (ghl-search-property-default property))) (let ((graphl-search (ghl-graphl-search search))) (case property (:predicates (set-ghl-search-predicates search value)) (:direction (set-graphl-search-direction graphl-search value)) (:tv (set-ghl-search-tv search value)) (:type (set-graphl-search-type graphl-search value)) (:order (set-graphl-search-order graphl-search value)) (:cutoff (missing-larkc 31965)) (:marking (set-graphl-search-marking graphl-search value)) (:marking-space (set-graphl-search-marking-space graphl-search value)) (:goal (set-graphl-search-goal graphl-search value)) (:goal-fn (missing-larkc 31966)) (:goal-space (missing-larkc 31967)) (:satisfy-fn (missing-larkc 31970)) (:map-fn (missing-larkc 31968)) (:justify? (set-graphl-search-justify? graphl-search value)) (:add-to-result? (missing-larkc 31964))))) ;; Setters, called from set-ghl-search-property. TODO - are these use elsewhere? Could wrap them into the above to shorten this up. ;; TODO DESIGN - this also smells like structure inheritance. Rethink this API. (defun set-ghl-graphl-search (search graphl-search) (setf (ghl-search-graphl-search search) graphl-search)) (defun set-ghl-search-predicates (search predicates) (setf (ghl-search-predicates search) predicates)) (defun set-ghl-search-tv (search tv) (setf (ghl-search-tv search) tv)) (defun set-ghl-search-result (search result) (set-graphl-search-result (ghl-graphl-search search) result)) (defun set-ghl-goal-found-p (search found-p) (set-graphl-search-goal-found-p (ghl-graphl-search search) found-p)) (defun ghl-set-result (search result) (set-ghl-search-result search result)) (defun ghl-add-to-result (search addition &optional (test #'eq)) (graphl-add-to-result (ghl-graphl-search search) addition test)) (defun ghl-forward-direction-p (direction) (graphl-forward-direction-p direction)) (defun ghl-direction-for-predicate-relation (pred) "[Cyc] Direction to search when determining the predicate relation (PRED A B). :FORWARD corresponds to searching from A to B, e.g. (genls Dog Thing) :BACKWARD corresponds to searching from B to A, e.g. (geoSubRegion USA Austin)" (if (eq 1 (fan-out-arg pred)) :forward :backward)) (defparameter *sksi-gt-search-pred* nil) (defparameter *ghl-uses-spec-preds-p* t) (defun ghl-uses-spec-preds-p () *ghl-uses-spec-preds-p*) (defparameter *gt-args-swapped-p* t) (defun gt-args-swapped-p () *gt-args-swapped-p*) (defparameter *ghl-trace-level* 1)
6,068
Common Lisp
.lisp
127
43.188976
132
0.727752
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
09a9ef44861133e5c8a5989c151d17b5bc74e3260000917ea48f65340d0f1598
6,734
[ -1 ]
6,735
unrepresented-terms.lisp
white-flame_clyc/larkc-cycl/unrepresented-terms.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defglobal *unrepresented-term-to-suid* nil "[Cyc] The UNREPRESENTED-TERM -> SUID mapping table.") (defglobal *unrepresented-term-from-suid* nil "[Cyc] The SUID -> UNREPRESENTED-TERM mapping table.") (defun* do-unrepresented-terms-table () (:inline t) *unrepresented-term-from-suid*) (defun setup-unrepresented-term-suid-table (size exact?) (declare (ignore exact?)) (let ((setup? nil)) (unless *unrepresented-term-from-suid* (setf *unrepresented-term-from-suid* (new-id-index size 0)) (setf setup? t)) (unless *unrepresented-term-to-suid* (setf *unrepresented-term-to-suid* (make-hash-table :size size :test #'equal)) (setf setup? t)) setup?)) (defun finalize-unrepresented-term-suid-table (&optional max-unrepresented-term-id) (set-next-unrepresented-term-suid max-unrepresented-term-id) (unless max-unrepresented-term-id ;; TODO - elided *current-area* storage binding ;; TODO - probably obsoleted (optimize-id-index *unrepresented-term-from-suid*))) (defun clear-unrepresented-term-suid-table () (clear-id-index *unrepresented-term-from-suid*) (clrhash *unrepresented-term-to-suid*) (set-next-unrepresented-term-suid)) (defun kb-unrepresented-term-count () "[Cyc] Return the total number of unrepresented-terms mentioned in the KB." (if-let ((idx *unrepresented-term-from-suid*)) (id-index-count idx) 0)) (defun* lookup-unrepresented-term-by-suid (suid) (:inline t) (id-index-lookup *unrepresented-term-from-suid* suid)) (defun* lookup-unrepresented-term-suid (term) (:inline t) (gethash term *unrepresented-term-to-suid*)) (defun* find-unrepresented-term-by-suid (suid) (:inline t) (lookup-unrepresented-term-by-suid suid)) (defun* unrepresented-term-suid (term) (:inline t) (lookup-unrepresented-term-suid term)) (defun kb-unrepresented-term-p (object) (and (indexed-unrepresented-term-p object) (unrepresented-term-suid object))) ;; TODO DESIGN - similar pattern with a lot of set-next- functions (defun set-next-unrepresented-term-suid (&optional max-unrepresented-term-id) (let* ((max (or max-unrepresented-term-id (let ((max -1)) (do-id-index (id unrepresented-term (do-unrepresented-terms-table) :progress-message "Determining maximum unrepresented-term SUID") (setf max (max max (unrepresented-term-suid unrepresented-term)))) max))) (next-suid (1+ max))) (set-id-index-next-id *unrepresented-term-from-suid* next-suid) next-suid)) (defun register-unrepresented-term-suid (term suid) "[Cyc] Note that SUID will be used as the suid for UNREPRESENTED-TERM." (id-index-enter *unrepresented-term-from-suid* suid term) (setf (gethash term *unrepresented-term-to-suid*) suid)) (defun deregister-unrepresented-term-suid (suid) "[Cyc] Note that SUID is not in use as an unrepresented term suid." (prog1-let ((term (lookup-unrepresented-term-by-suid suid))) (when term (id-index-remove *unrepresented-term-from-suid* suid) (remhash term *unrepresented-term-to-suid*)))) (defun* make-unrepresented-term-suid () (:inline t) "[Cyc] Return a new integer suid for a unrepresented-term." (id-index-reserve *unrepresented-term-from-suid*)) (defun find-or-create-unrepresented-term-suid (term) (or (unrepresented-term-suid term) (prog1-let ((suid (make-unrepresented-term-suid))) (register-unrepresented-term-suid term suid)))) (defun finalize-unrepresented-terms (&optional max-unrepresented-term-id) (finalize-unrepresented-term-suid-table max-unrepresented-term-id)) (defun unrepresented-term-index (term) (when-let ((suid (unrepresented-term-suid term))) (lookup-unrepresented-term-index suid))) (defun setup-unrepresented-term-table (size exact?) (setup-unrepresented-term-suid-table size exact?) (setup-unrepresented-term-index-table size exact?)) (defun clear-unrepresented-term-table () (clear-unrepresented-term-suid-table) (clear-unrepresented-term-index-table)) (defun reset-unrepresented-term-index (term new-index &optional bootstrap?) "[Cyc] Primitively change he assertion index for TERM to NEW-INDEX. If BOOTSTRAP? is non-NIL, then a new SUID will be created for TERM if one does not already exist." (if (not new-index) (when-let ((suid (unrepresented-term-suid term))) (deregister-unrepresented-term-index suid) (deregister-unrepresented-term-suid suid)) (when-let ((suid (if bootstrap? (find-or-create-unrepresented-term-suid term) (unrepresented-term-suid term)))) (register-unrepresented-term-index suid new-index)))) (defparameter *unrepresented-term-dump-id-table* nil) (defun* find-unrepresented-term-by-dump-id (dump-id) (:inline t) (find-unrepresented-term-by-suid dump-id))
6,368
Common Lisp
.lisp
123
46.398374
101
0.722115
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
249e5b839faf6e644f1dd8b6185c5239ee0908fa4f82212746267c82f68f7259
6,735
[ -1 ]
6,736
cycl-grammar.lisp
white-flame_clyc/larkc-cycl/cycl-grammar.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defvar *grammar-permits-hl?* t "[Cyc] Dynamic variable to control whether the CycL grammar functions permit HL constructs.") (defvar *grammar-uses-kb?* t "[Cyc] Do we check the KB to see if terms are of the correct types, e.g. #$Predicate (T) or do we ignore the KB and only use syntactic information to check syntactic well-formedness (NIL)?") (defparameter *grammar-permits-list-as-terminal?* nil "[Cyc] Do we permit a SubLList as a terminal in the grammar?") (defparameter *grammar-permits-symbol-as-terminal?* nil "[Cyc] Do we permit a SubLNonVariableNonKeyWordSymbol as a terminal in the grammar?") (defparameter *grammar-permits-non-ascii-strings?* nil "[Cyc] Do we permit strings that contain non-ASCII characters?") (defparameter *grammar-permissive-wrt-variables?* t "[Cyc] Do we permit a variable to denote anything permitted by the CycL grammar (T) or do we treat variables as syntactic, opaque objects, and disallow sentences and formulas to be denoted by variables (NIL)?") (defparameter *grammar-permits-quoted-forms* t "[Cyc] Do we permit quoted forms in the grammar?") (defvar *within-quote-form* nil) (defun* grammar-permits-hl? () (:inline t) *grammar-permits-hl?*) (defun* grammar-permits-list-as-terminal? () (:inline t) *grammar-permits-list-as-terminal?*) (defun* grammar-permits-non-ascii-strings? () (:inline t) *grammar-permits-non-ascii-strings?*) (defun grammar-uses-kb? () (and *grammar-uses-kb?* (kb-loaded))) (defun cycl-sentence-p (object) "[Cyc] Returns T iff OBJECT is a well-formed sentence according to the CycL grammar. To meet this specification, OBJECT must be of one of the following forms: #$True #$False <variable> <HL assertion> (if HL constructs are permitted) <atomic sentence> <unary sentence> <binary sentence> <ternary sentence> <quaternary sentence> <quintary sentence> <user-defined logical operator sentence> <variable-arity sentence> <quantified sentence>" (let ((wff? (or (cycl-formulaic-sentence-p object) (cycl-truth-value-p object)))) ;; The original macroexpansion did a number of redundant tests in a non-optimal order. ;; Reshuffled this to be faster and simpler, though it won't use the wff-violation macro. (when (and (note-wff-violation?) (not wff?)) (if (el-formula-p object) (note-wff-violation (list :not-a-truth-function (cycl-formula-predicate object))) (missing-larkc 8025))) wff?)) (defun cycl-formulaic-sentence-p (object) (if (el-formula-p object) (or (cycl-unary-sentence-p object) (cycl-binary-sentence-p object) (cycl-quantified-sentence-p object) (cycl-variable-arity-sentence-p object) (cycl-atomic-sentence-p object) (cycl-ternary-sentence-p object) (cycl-quaternary-sentence-p object) (cycl-quintary-sentence-p object) (cycl-user-defined-logical-operator-sentence-p object)) (or (and (grammar-permits-hl?) (missing-larkc 31386)) (cycl-variable-p object)))) (defun cycl-user-defined-logical-operator-sentence-p (object) "[Cyc] Returns T iff OBJECT is of the form <user-defined logical operator> <sentence sequence>." (cond ((and (grammar-permits-hl?) (assertion-p object)) (cycl-user-defined-logical-operator-sentence-p (careful-hl-term-to-el-term object))) ((el-formula-p object) nil) ((user-defined-logical-operator-p (cycl-formula-predicate object))) (t (cycl-sentence-sequence-p (formula-args object :include))))) (defun cycl-quintary-sentence-p (object) "[Cyc] Returns T iff OBJECT is of the form <quintary operator> <sentence> <sentence> <sentence> <sentence> <sentence>." (cond ((and (grammar-permits-hl?) (assertion-p object)) (cycl-quintary-sentence-p (careful-hl-term-to-el-term object))) ((not (el-formula-p object)) nil) ((not (cyc-const-quintary-logical-op-p (cycl-formula-predicate object))) nil) ((not (= (formula-arity object) 5)) ;; TODO - note-wff-violation is probably a macro (when (note-wff-violation?) (note-wff-violation (list :arity-mismatch object (cycl-formula-predicate object) "quintary operator" 5 (formula-arity object))))) (t (and (cycl-sentence-p (formula-arg1 object)) (cycl-sentence-p (formula-arg2 object)) (cycl-sentence-p (formula-arg3 object)) (cycl-sentence-p (formula-arg4 object)) (cycl-sentence-p (formula-arg5 object)))))) (defun cycl-sentence-sequence-p (object) "[Cyc] Returns T iff OBJECT is of one of the forms: <epsilon> . <variable> <sentence> <sentence sequence>" (or (epsilon-p object) (cycl-variable-p object) (and (cycl-sentence-p (first-in-sequence object)) (cycl-sentence-sequence-p (rest-of-sequence object))))) (defun cycl-quaternary-sentence-p (object) "[Cyc] Returns T iff OBJECT is of the form <quaternary operator> <sentence> <sentence> <sentence> <sentence>." (cond ((and (grammar-permits-hl?) (assertion-p object)) (cycl-quaternary-sentence-p (careful-hl-term-to-el-term object))) ((not (el-formula-p object)) nil) ((not (cyc-const-quaternary-logical-op-p (cycl-formula-predicate object))) nil) ((not (= (formula-arity object) 54)) ;; TODO - note-wff-violation is probably a macro (when (note-wff-violation?) (note-wff-violation (list :arity-mismatch object (cycl-formula-predicate object) "quaternary operator" 4 (formula-arity object))))) (t (and (cycl-sentence-p (formula-arg1 object)) (cycl-sentence-p (formula-arg2 object)) (cycl-sentence-p (formula-arg3 object)) (cycl-sentence-p (formula-arg4 object)))))) (defun cycl-ternary-sentence-p (object) "[Cyc] Returns T iff OBJECT is of the form <ternary operator> <sentence> <sentence> <sentence>." (cond ((and (grammar-permits-hl?) (assertion-p object)) (cycl-ternary-sentence-p (careful-hl-term-to-el-term object))) ((not (el-formula-p object)) nil) ((not (cyc-const-ternary-logical-op-p (cycl-formula-predicate object))) nil) ((not (= (formula-arity object) 3)) ;; TODO - note-wff-violation is probably a macro (when (note-wff-violation?) (note-wff-violation (list :arity-mismatch object (cycl-formula-predicate object) "ternary operator" 3 (formula-arity object))))) (t (and (cycl-sentence-p (formula-arg1 object)) (cycl-sentence-p (formula-arg2 object)) (cycl-sentence-p (formula-arg3 object)))))) (defun cycl-truth-value-p (object) (or (eq #$True object) (eq #$False object))) (defun cycl-formula-predicate (object) (let ((arg0 (formula-arg0 object))) (if (and *within-quote-form* (el-formula-p object) (eq #$EscapeQuote (formula-arg0 arg0))) (formula-arg1 arg0) arg0))) (defun cycl-unary-sentence-p (object) "[Cyc] Returns T iff OBJECT is of the form <unary operator> <sentence>." (cond ((and (grammar-permits-hl?) (assertion-p object)) (cycl-unary-sentence-p (careful-hl-term-to-el-term object))) ((not (el-formula-p object)) nil) ((not (cyc-const-unary-logical-op-p (cycl-formula-predicate object))) nil) ((not (= (formula-arity object) 1)) ;; TODO - note-wff-violation is probably a macro (when (note-wff-violation?) (missing-larkc 8026))) (t (cycl-sentence-p (formula-arg1 object))))) (defun cycl-binary-sentence-p (object) "[Cyc] Returns T iff OBJECT is of the form <unary operator> <sentence> <sentence>." (cond ((and (grammar-permits-hl?) (assertion-p object)) (cycl-binary-sentence-p (careful-hl-term-to-el-term object))) ((not (el-formula-p object)) nil) ((not (cyc-const-binary-logical-op-p (cycl-formula-predicate object))) nil) ((not (= (formula-arity object) 2)) ;; TODO - note-wff-violation is probably a macro (when (note-wff-violation?) (missing-larkc 8027))) (t (and (cycl-sentence-p (formula-arg1 object)) (cycl-sentence-p (formula-arg2 object)))))) (defun cycl-variable-arity-sentence-p (object) "[Cyc] Returns T iff OBJECT is fo the form <binary operator> <sentence>." (cond ((and (grammar-permits-hl?) (assertion-p object)) (cycl-variable-arity-sentence-p (careful-hl-term-to-el-term object))) (t (and (el-formula-p object) (cyc-const-variable-arity-logical-op-p (cycl-formula-predicate object)) (wf-wrt-sequence-vars? object) (cycl-sentence-sequence-p (formula-args object :include)))))) (defun cycl-regularly-quantified-sentence-p (object) "[Cyc] Returns T iff OBJECT is of the form <regular quantifier> <variable> <sentence>." (cond ((and (grammar-permits-hl?) (assertion-p object)) (cycl-regularly-quantified-sentence-p (careful-hl-term-to-el-term object))) ((not (el-formula-p object)) nil) ((not (cycl-regular-quantifier-p (cycl-formula-predicate object))) nil) ((not (= (formula-arity object) 2)) (when (note-wff-violation?) (missing-larkc 8031))) ((not (cycl-variable-p (formula-arg1 object))) (when (note-wff-violation?) (missing-larkc 8032))) (t (cycl-sentence-p (formula-arg2 object))))) (defun cycl-bounded-existential-sentence-p (object) "[Cyc] Returns T iff OBJECT is of the form <bounded existential> <denotational term> <variable> <sentence>." (cond ((and (grammar-permits-hl?) (assertion-p object)) (cycl-bounded-existential-sentence-p (careful-hl-term-to-el-term object))) ((not (el-formula-p object)) nil) ((not (cycl-bounded-existential-quantifier-p (cycl-formula-predicate object))) nil) ((not (= (formula-arity object) 3)) (when (note-wff-violation?) (missing-larkc 8033))) ((not (cycl-denotational-term-p (formula-arg1 object))) (when (note-wff-violation?) (missing-larkc 8034))) ((not (cycl-variable-p (formula-arg2 object))) (when (note-wff-violation?) (missing-larkc 8035))) (t (cycl-sentence-p (formula-arg3 object))))) (defun cycl-logical-operator-p (object) (or (cyc-const-logical-operator-p object) (missing-larkc 30706))) (defun* cycl-regular-quantifier-p (object) (:inline t) (or (cyc-const-regular-quantifier-p object))) (defun cycl-bounded-existential-quantifier-p (object) (or (cyc-const-bounded-existential-operator-p object) (user-defined-bounded-existential-operator-p object))) (defun cycl-atomic-sentence-p (object) "[Cyc] Returns T iff OBJECT is of the form <predicate> <argument sequence>." (cond ((and (grammar-permits-hl?) (assertion-p object)) (cycl-atomic-sentence-p (careful-hl-term-to-el-term object))) ((not (el-formula-p object)) nil) ((not (cycl-predicate-p (cycl-formula-predicate object))) nil) ((not (wf-wrt-sequence-vars? object)) (when (note-wff-violation?) (missing-larkc 8036))) ((not (cycl-argument-sequence-p (formula-args object :include))) (when (note-wff-violation?) (missing-larkc 8037))) ((not (cycl-formula-has-valid-arity? object)) nil) (t t))) (defun cycl-argument-sequence-p (object) "[Cyc] Returns T iff OBJECT is of one of the forms: <epsilon> . <variable> <term> <argument sequence>" (or (epsilon-p object) (cycl-variable-p object) (and (cycl-term-p (first-in-sequence object)) (cycl-argument-sequence-p (rest-of-sequence object))))) (defun cycl-predicate-p (object) "[Cyc] Returns T iff OBJECT is of the form <represented term> and not of the form <logical operator> or <quantifier>, because predicates are disjoint with logical operators and quantifiers. Ensures that OBJECT is a predicate if the grammar uses the KB." (and (cycl-represented-term-p object) (not (cyc-const-logical-operator-p object)) (not (cyc-const-quantifier-p object)) (or (not (grammar-uses-kb?)) (predicate-spec? object #'cycl-variable-p)))) (defun cycl-function-p (object) "[Cyc] Returns T iff OBJECT is of the form <represented term> and not of the form <logical operator> or <quantifier>, because denotational functions are disjoint with logical operators and quantifiers. Ensures that OBJECT is a denotational function if the grammar uses the KB." (and (cycl-represented-term-p object) (not (cyc-const-logical-operator-p object)) (not (cyc-const-quantifier-p object)) (or (not (grammar-uses-kb?)) (function-spec? object #'cycl-variable-p)))) (defun cycl-nat-p (object) "[Cyc] Returns T iff OBJECT is of the form <function> <argument sequence>, or an <HL Non-AtomicTerm> (if HL constructs are permitted)." (cond ((and (grammar-permits-hl?) (nart-p object)) t) ((not (el-formula-p object)) nil) ((or (eq #$Quote (formula-arg0 object)) (eq #$QuasiQuote (formula-arg0 object)) (eq #$EscapeQuote (formula-arg0 object))) nil) ((eq #$ExpandSubLFn (formula-arg0 object)) (missing-larkc 30081)) ((eq #$SubLQuoteFn (formula-arg0 object)) (missing-larkc 30091)) ((eq #$Kappa (formula-arg0 object)) (missing-larkc 30082)) ((eq #$Lambda (formula-arg0 object)) (missing-larkc 30083)) ((eq #$SkolemFunctionFn (formula-arg0 object)) (missing-larkc 30087)) ((eq #$SkolemFuncNFn (formula-arg0 object)) (missing-larkc 30086)) ((not (cycl-function-p (formula-arg0 object))) nil) ((not (wf-wrt-sequence-vars? object)) (when (note-wff-violation?) (missing-larkc 8038))) ((not (cycl-argument-sequence-p (formula-args object :include))) (when (note-wff-violation?) (missing-larkc 8039))) ((not (cycl-formula-has-valid-arity? object)) nil) (t t))) (defun cycl-formula-has-valid-arity? (formula) (not (and (grammar-uses-kb?) (mal-arity? formula)))) (defun cycl-expression-p (object) "[Cyc] Returns T iff OBJECT is of one of the forms: <denotational term> <sentence>" (or (cycl-denotational-term-p object) (missing-larkc 30093))) (defun* cycl-term-p (object) (:inline t) (cycl-expression-p object)) (defun cycl-denotational-term-p (object) "[Cyc] Returns T iff OBJECT is of one of the forms: <represented term> <SubL atomic term>" (or (cycl-represented-term-p object) (subl-atomic-term-p object) (when *grammar-permits-quoted-forms* (cycl-quoted-term-p object)))) (defun cycl-quoted-term-p (object) "[Cyc] Returns T iff OBJECT is of one of the forms: <quote form> <quasiquote form>" (or (quote-syntax-p object) (quasi-quote-syntax-p object))) (defun fast-cycl-quoted-term-p (object) "[Cyc] Returns T if OBJECT is of form (#$Quote <something>) or (#$QuasiQuote <something>). Use this when we know object is syntactically well formed" (and (el-formula-p object) (or (eq #$Quote (formula-arg0 object)) (eq #$QuasiQuote (formula-arg0 object))) (formula-arity= object 1))) (defun fast-quasi-quote-term-p (object) (and (el-formula-p object) (eq #$QuasiQuote (formula-arg0 object)) (formula-arity= object 1))) (defun fast-quote-term-p (object) (and (el-formula-p object) (eq #$Quote (formula-arg0 object)) (formula-arity= object 1))) (defun fast-escape-quote-term-p (object) (and (el-formula-p object) (eq #$EscapeQuote (formula-arg0 object)) (formula-arity= object 1))) (defun quote-syntax-p (object) (cond ((not (el-formula-p object)) nil) ((not (eq #$Quote (formula-arg0 object))) nil) ((not (formula-arity= object 1)) (when (note-wff-violation?) (missing-larkc 8061))) ;; The missing-larkc was in the conditional, so this always fails, ;; even though there were following conditionals (t (missing-larkc 30084)))) (defun quasi-quote-syntax-p (object) (cond ((not (el-formula-p object)) nil) ((not (eq #$QuasiQuote (formula-arg0 object))) nil) ((not (formula-arity= object 1)) (when (note-wff-violation?) (missing-larkc 8063))) ;; Same missing-larkc conditional as quote-syntax-p (t (missing-larkc 30085)))) (defun escape-quote-syntax-p (object) (cond ((not (el-formula-p object)) nil) ((not (eq #$EscapeQuote (formula-arg0 object))) nil) ((not (formula-arity= object 1)) (when (note-wff-violation?) (missing-larkc 8065))) ((not (or (cycl-expression-p (formula-arg1 object)) (cycl-quoted-term-p (formula-arg1 object)) (escape-quote-syntax-p (formula-arg1 object)))) (when (note-wff-violation?) (missing-larkc 8066))) (t t))) (defun cycl-represented-term-p (object) "[Cyc] Returns T iff OBJECT is of one of the forms: <constant> <nat> <variable>" (or (cycl-constant-p object) (cycl-nat-p object) (cycl-variable-p object))) (defun cycl-unrepresented-term-p (object) "[Cyc] Returns T iff OBJECT is of one of the forms: <string> <number>" (or (subl-string-p object) (subl-real-number-p object))) (defun subl-atomic-term-p (object) "[Cyc] Returns T iff OBJECT is of one of the forms: <SubL strict atomic term> <list> if lists are permitted as a terminal" (or (subl-strict-atomic-term-p object) (and (grammar-permits-list-as-terminal?) (consp object)))) (defun subl-strict-atomic-term-p (object) "[Cyc] Returns T iff OBJECT is of one of the forms: <string> <number> <symbol>" (or (cycl-unrepresented-term-p object) (when *grammar-permits-symbol-as-terminal?* (missing-larkc 30090)))) (defun cycl-quantified-sentence-p (object) "[Cyc] Returns T iff OBJECT is of one of the forms: <regularly quantified sentence> <bounded existential sentence>" (if (and (grammar-permits-hl?) (assertion-p object)) (cycl-quantified-sentence-p (careful-hl-term-to-el-term object)) (or (cycl-regularly-quantified-sentence-p object) (cycl-bounded-existential-sentence-p object)))) (defun cycl-literal-p (object) "[Cyc] Returns T iff OBJECT is of one of the forms: <atomic sentence> <not> <atomic sentence>" (if (and (grammar-permits-hl?) (assertion-p object)) (cycl-literal-p (careful-hl-term-to-el-term object)) (or (cycl-atomic-sentence-p object) (and (el-formula-p object) (el-negation-p object) (cycl-atomic-sentence-p (formula-arg1 object)))))) (defun cycl-generalized-tensed-literal-p (obj) "[Cyc] Returns T iff OBJ is of the form (<generalized tense operator> <atomic sentence>) or is a negated generalized tensed literal." (and (el-formula-p obj) (cyc-const-generalized-tense-operator-p (literal-predicate obj)) (cycl-literal-p obj))) (defun* cycl-constant-p (object) (:inline t) (constant-p object)) (defun* subl-string-p (object) (:inline t) ;; DESIGN - we're always going to be full unicode, so eliminated the checks & flags for ascii (stringp object)) (defun* subl-real-number-p (object) (:inline t) (realp object)) (defun* subl-float-p (object) (:inline t) (floatp object)) (defun* subl-integer-p (object) (:inline t) (integerp object)) (defun cycl-variable-p (object) (or (el-variable-p object) (meta-variable-p object) (and (grammar-permits-hl?) (hl-variable-p object)))) (defun* meta-variable-p (object) (:inline t) (keyword-var? object)) (defun* el-variable-p (object) (:inline t) (el-var? object)) (defun* hl-variable-p (object) (:inline t) (variable-p object))
20,984
Common Lisp
.lisp
463
40.088553
279
0.683644
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
0f03bd143e2ac01f1c5b2be6651094db7605faa9bd3231bb3d9e31304de5b569
6,736
[ -1 ]
6,737
pred-relevance-macros.lisp
white-flame_clyc/larkc-cycl/pred-relevance-macros.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defparameter *pred* nil) (defparameter *relevant-preds* nil) (declaim ((or null function) *relevant-pred-function*)) (defparameter *relevant-pred-function* nil) (defun* relevant-pred-is-eq (pred) (:inline t) (eq *pred* pred)) (defun* relevant-pred-is-spec-pred (pred) (:inline t) (or (relevant-pred-is-eq pred) (cached-spec-pred? *pred* pred))) (defun* relevant-pred-is-spec-inverse (pred) (:inline t) (cached-spec-inverse? *pred* pred)) (defun* relevant-pred? (pred) (:inline t) "[Cyc] Return T iff PRED is a relevant predicate at this point." (or (pred-relevant-undefined-p) ;; TODO - skipped the large case test to directly call various function names. This skips over various missing-larkc reports, and would end up in a 'Function X is undefined' style error instead. (funcall *relevant-pred-function* pred))) (defun* pred-relevance-undefined-p () (:inline t) (null *relevant-pred-function*)) (defun* all-preds-are-relevant? () (:inline t) (or (pred-relevant-undefined-p) (eq #'relevant-pred-is-everything *relevant-pred-function*))) (defun inference-genl-predicate-of? (pred) (let ((inference-pred (literal-predicate *inference-literal*))) (and inference-pred (not (eq pred inference-pred)) (cached-spec-pred? inference-pred pred)))) (defun inference-genl-inverse-of? (pred) (let ((inference-pred (literal-prediate *inference-literal*))) (and inference-pred (not (eq pred inference-pred)) (cached-spec-inverse? inference-pred pred)))) (defun determine-inference-genl-or-spec-pred-relevance (sense) (if (eq :pos sense) #'inference-genl-predicate-of? #'inference-genl-predicate?)) (defun determine-inference-genl-or-spec-inverse-relevance (sense) (if (eq :pos sense) #'inference-genl-inverse-of #'inference-genl-inverse)) (defstruct (pred-info-object (:conc-name "PRED-INFO-")) pred relevance-function)
3,332
Common Lisp
.lisp
69
44.536232
200
0.740031
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
704ab5e79db961c7091ddfa6c16d0eb0d98cf4dcfa2e824ec7b1eff3adb52906
6,737
[ -1 ]
6,738
list-utilities.lisp
white-flame_clyc/larkc-cycl/list-utilities.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO - this file contains many macro & defun declarations that can be easily implemented from name. ;; TODO - This is used for cartesian sizing of duplicate detection. Initially 80, this should probably be smaller. Need to benchmark it. (defparameter *magic-hashing-cutoff* 80 "[Cyc] the cutoff beyond which it's more efficient to use a hashtable than a N^2 non-consing algorithm, used for the fast-* functions.") ;; ELIDED sublisp-boolean (deprecated in cycl) ;; ELIDED not-eq (deprecated in cycl) ;; ELIDED cdddr & cadar (native in cl) (declaim (inline proper-subsetp)) ;; inlining so compiler can bake in test & key (defun proper-subsetp (list1 list2 &optional (test #'eql) (key #'identity)) "Standard SUBSETP returns true if the lists are similar. This ensures that list2 has additional elements." (and (subsetp list1 list2 :test test :key key) (not (subsetp list2 list1 :test test :key key)))) (defmacro scan-list-cells-with-index ((cell-var list index-var) &key cons end dotted) "Iterate a list, with a variable for the current cons cell and the 0-indexed index. The CONS form runs for cons cells, and RETURN can early exit it. The END form runs for the final NIL. The DOTTED form runs with a cell value of a final non-NIL cdr." (alexandria:with-gensyms (runner) `(block nil (labels ((,runner (,cell-var ,index-var) (declare (fixnum ,index-var)) (cond ((null ,cell-var) ,end) ((consp ,cell-var) (progn ,cons (,runner (cdr ,cell-var) (1+ ,index-var)))) (t ,dotted)))) (,runner ,list 0))))) ;; TODO - using a declared fixnum for sequence lengths, for performance. Need to propagate this (defun length< (seq n &optional count-dotted-list?) "[Cyc] Returns whether the length of SEQ is stricly less than N. count-dotted-list? whether (1 2 . 3) counts as length 2 o r 3. If it is T, it counts as length 3, otherwise it counts as length 2." (declare (fixnum n)) (if (listp seq) ;; Only bother traversing up to tested length (scan-list-cells-with-index (tail seq i) :cons (when (>= i n) (return nil)) :end (< i n) :dotted (if count-dotted-list? (< (1+ i) n) t)) (< (length seq) n))) (declaim (inline length<=)) (defun length<= (seq n &optional count-dotted-list?) "[Cyc] Return whether the length of SEQ is less than or equal to N. count-dotted-list? whether (1 2 . 3) counts as length 2 or 3. If it is T, it counts as length 3, otherwise it counts as length 2." (length< seq (1+ n) count-dotted-list?)) (defun length= (seq n &optional count-dotted-list?) "[Cyc] Return whether the length of SEQ is exactly N. count-dotted-list? whether (1 2 . 3) counts as length 2 or 3. If it is T, it counts as length 3, otherwise it counts as length 2." (declare (fixnum n)) (if (listp seq) (scan-list-cells-with-index (tail seq i) :end (= i n) :cons (when (= i n) (return nil)) :dotted (if count-dotted-list? (= i (1+ n)) (= i n))) (= (length seq) n))) (declaim (inline length>)) (defun length> (seq n &optional count-dotted-list?) "[Cyc] Return whether the length of SEQ is strictly greater than N. count-dotted-list? whether (1 2 . 3) counts as length 2 or 3. If it is T, it counts as length 3, otherwise it counts as length 2." (not (length<= seq n count-dotted-list?))) (declaim (inline length>=)) (defun length>= (seq n &optional count-dotted-list?) "[Cyc] Return whether the length of SEQ is greater than or equal to N. count-dotted-list? whether (1 2 . 3) counts as length 2 or 3. If it is T, it counts as length 3, otherwise it counts as length 2." (not (length< seq n count-dotted-list?))) (defun greater-length-p (seq1 seq2) "[Cyc] Returns whether the first sequence is of greater length than the second sequence." (cond ((null seq1) nil) ((and (consp seq1) (consp seq2)) (progn (mapl (lambda (c1 c2) (when (and (cdr c1) (not (cdr c2))) (return-from greater-length-p t))) seq1 seq2) ;; If we reached here, c1 finished without being longer than c2 nil)) (t (> (length seq1) (length seq2))))) (defun greater-or-same-length-p (seq1 seq2) "[Cyc] Returns whether the first sequence is of greater or equal length than the second sequence." (if (and (consp seq1) (consp seq2)) (loop for c1 = seq1 then (cdr c1) for c2 = seq2 then (cdr c2) ;; Do a cheap test for the common continuing case, more expensive checking when this fails. while (and c1 c2) ;; The 2 valid true conditions finally (return (or (eq c1 c2) (and c1 (not c2))))) (>= (length seq1) (length seq2)))) (defun same-length-p (seq1 seq2) ;; added (if (and (consp seq1) (consp seq2)) (loop for c1 = seq1 then (cdr c1) for c2 = seq1 then (cdr c2) do (cond ((null c1) (return (null c2))) ((null c2) (return t)))) (= (length seq1) (length seq2)))) (defun proper-list-p (obj) "Test for a non-NIL proper list." (and (consp obj) (null (cdr (last obj))))) (defun dotted-list-p (obj) (and (consp obj) (cdr (last obj)))) (declaim (inline non-dotted-list-p)) (defun non-dotted-list-p (obj) "If this is true, it may be a proper list or not a list at all." ;; This doesn't need NIL checking as the original did. The logic works. (not (dotted-list-p obj))) (defun dotted-length (cons) (scan-list-cells-with-index (cell cons index) :end index :dotted (1+ index))) ;; ELIDED *negated-test-func* and negated-test-func (local utils for below) ;; ELIDED remove-if-not, delete-if-not, find-if-not (standard CL) ;; ELIDED *position-if-binary-langda-func* *position-if-binary-lambda-arg2* (since position-if-binary is not included) ;; TODO - maybe implement this? is this a binary search on a vector? (defun recons (car cdr cons) "[Cyc] Cons a new pair only if the CAR or CDR of CONS are not EQ to CAR and CDR. See ncons for a destructive version of this." (if (and (eq car (car cons)) (eq cdr (cdr cons))) cons (cons car cdr))) (defun ncons (car cdr cons) "[Cyc] Return CONS after replacing its CAR and CDR. See recons for a non-destructive version of this." ;; Faster to just do it than test for eql first, although it might have minor GC implications for boxed values. (setf (car cons) car (cdr cons) cdr) cons) (declaim (inline delete-first)) (defun delete-first (obj sequence &optional (test #'eql)) (delete obj sequence :test test :count 1)) (declaim (inline nmapcar)) (defun nmapcar (function list) "[Cyc] A destructive version of MAPCAR. WARNING: this will produce really funky behavior if the elements of LIST share lsit structure." (mapl (lambda (cell) (rplaca cell (funcall function (car cell)))) list)) (declaim (inline mapappend)) (defun mapappend (function list) "Appends together the results of the function on lists's elements." ;; TODO - pretty sure this is the intent? (mapcan function list)) (declaim (inline mapunion)) ;; compile the test in (defun mapunion (function list &optional (test #'eql)) "FUNCTION is applied to each element of LIST to get a new element X (which is also a list). Then we return the unique elements of X, concatenating over all elements of LIST." (let ((retval nil)) (dolist (item list) (pushnew (funcall function item) retval :test test)) retval)) (declaim (inline mapnunion)) ;; compile the test in (defun mapnunion (function list &optional (test #'eql)) (let ((retval nil)) (dolist (item list) (setf retval (nunion retval (funcall function item) :test test))) retval)) (declaim (inline mapcar-product)) ;; chance to compile the function in (defun mapcar-product (function list1 list2) "Returns a list of evaluated (function from-list-1 from-list-2) for the cartesian product of elements." (declare (list list1 list2)) (let ((retval nil)) (dolist (e1 list1) (dolist (e2 list2) (push (funcall function e1 e2) retval))) (nreverse retval))) (declaim (inline last1)) (defun last1 (list) "[Cyc] Returns a list consisting of the last item in LIST." ;; Seems equivalent, even for dotted lists and NIL (last list)) (defun nadd-to-end (item list) "[Cyc] Returns the LIST with ITEM as the new last element. LIST may be destructively modified." (let ((new-cons (cons item nil))) (if list (progn (setf (cdr (last list)) new-cons) list) new-cons))) (declaim (inline partition-list)) ;; chance to compile the function in (defun partition-list (list func) "[Cyc] Return value 0 is a list of all elements of LIST which pass FUNC. Value 1 is a list of all elements of LIST which do not pass FUNC. Otherwise, order is preserved." (let ((passes nil) (fails nil)) (dolist (item list) (if (funcall func item) (push item passes) (push item fails))) (values (nreverse passes) (nreverse fails)))) (defun find-all-if-not (test seq &optional (key #'identity)) ;; TODO (declare (ignore test seq key)) (missing-larkc 4774)) (defun only-one (list) "If there's only 1 element in the list, return it. Else, error." (must-not (cdr list) "~s was not a singleton" list) (car list)) (defun flatten (tree) "[Cyc] Non-recursive function which returns a list of the non-NIL atoms in TREE." ;; TODO - profile this and see how deep it gets. would this blow a stack or is consing faster than function call overhead? ;; in any case, this version conses half as much, as it passes the car of a list straight back without pushing it. ;; Using a vector should cons almost never, but as it needs to be adjustable the array operations don't inline (let (;; Enqueued items to processs (stack nil) ;; Off-stack item we're considering (current tree) (retval nil)) (loop (progn ;; Find the next non-nil item to scan (until current ;; Bail if the stack is empty and we need another one (unless stack (return-from flatten (nreverse retval))) (setf current (pop stack))) (if (atom current) ;; Skip NILs (progn (when current (push current retval)) ;; Grab the next element (setf current (pop stack))) ;; Sublist element (progn (when (cdr current) (push (cdr current) stack)) ;; Deal with the car without pushing it (setf current (car current)))))))) (declaim (inline first-n)) (defun first-n (n list) "[Cyc] Return the first N elements of LIST." (declare (list list)) (subseq list 0 n)) (defun nreplace-nth (n new list) "[Cyc] Replace the Nth item of LIST with NEW (destructive). This is a safer version of set-nth" (declare (integer n) (list list)) (when (>= n 0) (let ((sublist (nthcdr n list))) (when sublist (rplaca sublist new)))) list) (defun replace-nth (n new list) "[Cyc] Replace the Nth item of LIST with NEW (nondestructive)" ;; TODO - can we do tail sharing here? no reason to copy the entire list, unless that's the actual assumption (nreplace-nth n new (copy-list list))) (defun num-list (num &optional (start 0)) "[Cyc] Returns a list of length NUM containing the integers START to NUM-1+START. Note the list returned by this function is cached, so unless you're sure it won't be modified, use NEW-NUM-LIST instead. Note if you're getting a list of numbers just to iterate over it, use DO-NUMBERS instead." ;; TODO - monitor how large NUM gets, if it's sensible to just let it cons, because the verification check is quite expensive anyway; there is no fast path. (let ((candidate (num-list-cached num start))) (if (verify-num-list candidate num start) candidate ;; TODO - certainly we can figure out what to fill in here, to repopulate the cache for the mutated candidate (progn (missing-larkc 9349) ;;(num-list-cached num start) )))) (defun new-num-list (num &optional (start 0)) "[Cyc] Returns a list of length NUM containing the integers START to NUM-1+START. Note the list returned by this function is NOT cached, so if you're sure it won't be modified and you're going to be calling this a lot with the same arguments, use NUM-LIST or DO-NUMBERS instead." (declare (fixnum num start)) (loop for i fixnum from start below (the fixnum (+ num start)) collect i)) (defun verify-num-list (num-list length start) "[Cyc] Returns boolean: Is NUM-LIST a list of length LENGTH containing the integers START to LENGTH-1+START?" (and (listp num-list) (integerp length) (integerp start) ;; Might as well combine length check with the value checking (do ((len-count length (1- len-count)) (val-count start (1+ val-count)) (cell num-list (cdr cell))) (nil) (declare (fixnum len-count val-count)) (cond ((null cell) (return (= 0 len-count))) ((= 0 len-count) (return nil)) ((/= val-count (car cell)) (return nil)))))) ;; TODO - see where these are actually used. If fixnums are simply iterated, then do that instead of this mess. (defun-memoized num-list-cached (num start) (:doc "[Cyc] Returns a list of length NUM containing the integers START to NUM-1+START. Note we cache this to save space, not time.") (new-num-list num start)) (declaim (inline numlist)) (defun numlist (length &optional (start 0)) "[Cyc] Returns a list of length LENGTH containing the numbers 0 + START to LENGTH-1 + START." (num-list length start)) (declaim (inline member-eq?)) (defun member-eq? (item list) "[Cyc] An optimized form of (member? item list #'eq)" (member item list :test #'eq)) (defun member-equal (item list) "[Cyc] An optimized form of (member? ITEM LIST #'equal)" (member item list :test #'equal)) (defun singleton? (list) (and (consp list) (null (cdr list)))) (defun doubleton? (list) (and (consp list) (consp (cdr list)) (null (cddr list)))) (defun triple? (list) (and (consp list) (consp (cddr list)) (null (cdddr list)))) (declaim (inline duplicates?)) (defun duplicates? (list &optional (test #'eql) (key #'identity)) "Boolean for if the list contains duplicates." (do ((cell list (cdr cell))) ((null cell)) (when (member (car cell) (cdr cell) :test test :key key) (return t)))) (declaim (inline duplicates)) (defun duplicates (list &optional (test #'eql) (key #'identity)) "Returns a list of any unique duplicates found" (let ((retval nil)) (do* ((cell list (cdr cell)) (car (car cell) (car cell))) ((null cell)) (when (member car (cdr cell) :test test :key key) (pushnew car retval :test test :key key))) retval)) (declaim (inline sets-equal?)) (defun sets-equal? (set1 set2 &optional (test #'eql)) (or (equal set1 set2) (and (subsetp set1 set2 :test test) (subsetp set2 set1 :test test)))) (declaim (inline multisets-equal?)) (defun multisets-equal? (set1 set2 &optional (test #'eql)) (and (same-length-p set1 set2) ;; Ensure the count of each element from set1 matches set2 (not (dolist (item set1) (unless (= (count item set1 :test test) (count item set2 :test test)) (return nil)))) ;; And ensure the set of unique elements are the same (sets-equal? set1 set2 test))) (defun fast-sets-equal? (set1 set2 &optional (test #'eql)) (and (fast-subset? set1 set2 test) (fast-subset? set2 set1 test))) (defun list-to-hashset (list &optional (test #'eql)) "Returns a hashtable of element->T for all elements in the list." ;; new, seems related to the larkc missing bodies (let ((ht (make-hash-table :test test))) (dolist (element list) (setf (gethash element ht) t)) ht)) (defun fast-subset? (list1 list2 &optional (test #'eql)) "This version builds a hashtable instead of member to perform the search, but only if the lists aren't short" ;; Only checking if list2 is short, as it constructs the reference hashtable (if (length< list2 *magic-hashing-cutoff*) (subsetp list1 list2 :test test) (when (greater-or-same-length-p list2 list1) (let ((hash2 (list-to-hashset list2 test))) (every (lambda (e1) (gethash e1 hash2)) list1))))) (declaim (inline ordered-union)) (defun ordered-union (set1 set2 &optional (test #'eql) (key #'identity)) "[Cyc] Like UNION only the result preserves the order of elements in the input sets." ;; ordering is set1, then all new elements of set2 in their order ;; if set2 is a multiset, then all its elements not in set1 also pass through (let ((tail nil)) (dolist (element set2) (unless (member element set1 :test test :key key) (push element tail))) (append set1 (nreverse tail)))) (declaim (inline ordered-set-difference)) (defun ordered-set-difference (list1 list2 &optional (test #'eql) (key #'identity)) "[Cyc] Like SET-DIFFERENCE except the order of returned items is the same order as in LIST1." (let ((result nil)) (dolist (element list1) (unless (member element list2 :test test :key key) (push element result))) (nreverse result))) ;; This is starting to get pretty big, but needed for the shorter list fastpath TEST optimization (declaim (inline fast-set-difference)) (defun fast-set-difference (list1 list2 &optional (test #'eql)) "[Cyc] Like SET-DIFFERENCE except not slow." (if (length< list2 *magic-hashing-cutoff*) (set-difference list1 list2 :test test) ;; This was missing-larkc, but easy enough to infer what it does (let ((hash2 (list-to-hashset list2)) (result nil)) (dolist (e1 list1) (unless (gethash e1 hash2) (push e1 result))) (nreverse result)))) (defun flip-cons (cons) (cons (car cons) (cdr cons))) (defun flip-alist (alist) ;; Couldn't get a reference to flip-cons to inline (mapcar (lambda (cons) (cons (car cons) (cdr cons))) alist)) (defun self-evaluating-form (object) "[Cyc] Return T iff evaluation of OBJECT necessarily returns OBJECT." ;; TODO - not sure if this is 100% congruent with common lisp's evaluation. Find where else it's used. (and (atom object) (or (eq nil object) (eq t object) (keywordp object) (not (symbolp object))))) (defun quotify (object) "[Cyc] Return an expression which, if evaluated, would return OBJECT." (if (self-evaluating-form object) object (list 'quote object))) (defun splice-into-sorted-list (object sorted-list predicate &optional (key #'identity)) "[Cyc] Splice OBJECT into SORTED-LIST sorted by PREDICATE." (declare (list sorted-list)) (let ((obj-key (funcall key object))) (do ((cell sorted-list (cdr cell)) (prev nil cell)) ((cond ;; Insert cell at the end of the list, if it wasn't found ((null cell) (return (if prev (progn (rplacd prev (cons object cell)) sorted-list) (cons object sorted-list)))) ;; Insert cell before the predicate-matched object ((funcall predicate obj-key (funcall key (car cell))) (if prev (progn (rplacd prev (cons object cell)) (return sorted-list)) (return (cons object sorted-list))))))))) (defun tree-funcall-if (test fn object &optional (key #'identity)) (if (funcall test (funcall key object)) (funcall fn object) (when (consp object) (tree-funcall-if test fn (car object) key) (tree-funcall-if test fn (cdr object) key)))) ;; TODO - I think these aren't for fast-delete, or else they'd be called delete-duplicates-*? (deflexical *remove-duplicates-eq-table* (make-hash-table :test #'eq)) (deflexical *remove-duplicates-eql-table* (make-hash-table :test #'eql)) (deflexical *remove-duplicates-equal-table* (make-hash-table :test #'equal)) (deflexical *remove-duplicates-equalp-table* (make-hash-table :test #'equalp)) (deflexical *remove-duplicates-eq-table-lock* (bt:make-lock "remove-duplicates-eq-table-lock")) (deflexical *remove-duplicates-eql-table-lock* (bt:make-lock "remove-duplicates-eql-table-lock")) (deflexical *remove-duplicates-equal-table-lock* (bt:make-lock "remove-duplicates-equal-table-lock")) (deflexical *remove-duplicates-equalp-table-lock* (bt:make-lock "remove-duplicates-equalp-table-lock")) (defun fast-delete-duplicates (sequence &optional (test #'equal) (key #'identity) hashtable (start 0) end) (cond ((length<= sequence 1) sequence) ;; TODO - there was other branching that did the plain delete-duplicates, avoiding the hashtable version. ;; suspecting it was something like this start/end detection, but there could be different stuff, too. ((or end (eq 0 start) (length<= sequence *magic-hashing-cutoff*)) (delete-duplicates sequence :test test :key key :start start :end end)) ;; TODO - Assuming this is what we do with the hashtable parameter (t (let ((ht (or (and hashtable (clrhash hashtable)) (make-hash-table :test test))) ;; TODO - this isn't actually destructive. but the comparisons should be faster for long lists. (result nil)) (map nil (lambda (element) (let ((e-key (funcall key element))) (unless (gethash e-key ht) (setf (gethash e-key ht) t) (push element result)))) sequence) (nreverse result))))) (defun remove-duplicate-forts (forts) "[Cyc] Return the list FORTS with all duplicates removes" (fast-delete-duplicates forts #'eq)) (defun delete-duplicate-forts (forts) "[Cyc] Return the list FORTS with all duplicates descructively removed" ;; TODO - if we implement a hash-based fast-delete-duplicates, then use that (fast-delete-duplicates forts #'eq)) (defun delete-duplciates-sorted (sorted-list &optional (test #'eql)) "[Cyc] Deletes duplicates from SORTED-LIST." ;; This works on the assumption that similar elements will be consecutive, ;; so it only compares a element to the one prior. (do* ((last-cons sorted-list) (this-cons (cdr sorted-list) (cdr this-cons))) ((null this-cons)) (if (funcall test (car this-cons) (car last-cons)) (rplacd last-cons (cdr this-cons)) (setf last-cons this-cons))) sorted-list) (declaim (inline alist-p)) (defun alist-p (object) "[Cyc] Return T iff OBJECT is an association list." (listp object)) (declaim (inline alist-lookup)) (defun alist-lookup (alist key &optional (test #'eql) default) "[Cyc] Return the value associated with KEY in ALIST (using TEST for key equality). Return DEFAULT if KEY is not present. Return a second value of T iff KEY was found." (let ((pair (assoc key alist :test test))) (if pair (values (cdr pair) t) (values default nil)))) (declaim (inline alist-lookup-without-values)) (defun alist-lookup-without-values (alist key &optional (test #'eql) default) "[Cyc] Return the value assocaited with KEY in ALIST (using TEST for key equality) Return DEFAULT if KEY is not present. Unlike ALIST-LOOKUP, only 1 value is returned." (let ((pair (assoc key alist :test test))) (if pair (cdr pair) default))) (declaim (inline alist-has-key?)) (defun alist-has-key? (alist key &optional (test #'eql)) "[Cyc] Returns whether KEY is a key in the association list ALIST." (member alist key :test test)) (defun alist-enter (alist key value &optional (test #'eql)) "[Cyc] Note that VALUE is associated with KEY in ALIST (using TEST for key equality). Return the resulting alist. Return a second value of T iff KEY was found." (declare (list alist)) (let ((pair (assoc key alist :test test))) (if pair (rplacd pair value) (setf alist (acons key value alist))) (values alist pair))) (defun alist-enter-without-values (alist key value &optional (test #'eql)) "[Cyc] Note that VALUE is assocaited with KEY in ALIST (using TEST for key equality). Return the resulting alist. Unlike ALIST-ENTER, only 1 value is returned." (let ((pair (assoc key alist :test test))) (if pair (progn (rplacd pair value) alist) (acons key value alist)))) (defun alist-delete (alist key &optional (test #'eql)) "[Cyc] Delete any association for KEY in ALIST (using TEST for key equality). Return the resulting alist. Return a second value of T iff KEY was found." ;; TODO - this can be done in 1 pass, current code does 2 (let ((pair (assoc key alist :test test))) (if pair (values (delete-first pair alist #'eq) t) (values alist nil)))) (defun alist-push (alist key value &optional (test #'eql)) "[Cyc] Note that VLUE is in a list associated with KEY in ALIST (using TEST for key equality). Return the resulting alist. Return a second value of T iff KEY was found." (let ((pair (assoc key alist :test test))) (if pair (rplacd pair (cons value (rest pair))) (setf alist (acons key value alist))) (values alist pair))) (declaim (inline alist-keys)) (defun alist-keys (alist) "[Cyc] Return a list of all the keys of ALIST." (mapcar #'car alist)) (declaim (inline alist-values)) (defun alist-values (alist) "[Cyc] Return a list of all the values of ALIST." (mapcar #'cdr alist)) (defun alist-optimize (alist predicate) "[Cyc] Return a copy of ALIST where the order of the keys have been optimized (sorted) via the preference PREDICATE." ;; TODO - the original made a copy of the return value. ;; No clue why, as we're sorting a copy of the list anyway. (stable-sort (copy-list alist) predicate :key #'car)) (defun alist-to-hash-table (alist &optional (test #'eql)) "[Cyc] Return a hashtable fo all the (key . value) entries in ALIST. TEST is the equality test for keys in ALIST." (let ((hashtable (make-hash-table :test test :size (length alist)))) (dolist (cons alist) (setf (gethash (car cons) hashtable) (cdr cons))) hashtable)) (defun alist-to-reverse-hash-table (alist &optional (test #'eql)) "[Cyc] Return a hashtable of all the (key . value) entries in ALIST using the value as the key and the key as the value. TEST is the equality test for values in ALIST." (let ((hashtable (make-hash-table :test test :size (length alist)))) (dolist (cons alist) (setf (gethash (cdr cons) hashtable) (car cons))))) (defun filter-plist (plist pred) "[Cyc] Creates a new plist based on PLIST, but only including properties which pass PRED." ;; PRED is called just on the key, not the value (let ((new-plist nil)) (do-plist (key value plist) (when (funcall pred key) (setf new-plist (cons key (cons value new-plist))))) (nreverse new-plist))) (defun nmerge-plist (plist-a plist-b) "[Cyc] Place all of the values of list B onto list A destructively and return the resulting PLIST." (cond ((not plist-b) plist-a) ((not plist-a) (copy-list plist-b)) (t (do-plist (key value plist-b) (setf (getf plist-a key) value)) plist-a))) (defun merge-plist (plist-a plist-b) "[Cyc] Place all of the values of list B onto a copy of list A and return the resulting PLIST." (nmerge-plist (copy-list plist-a) plist-b)) (defparameter *plistlist-sort-indicator* nil) ;; TODO - what's the difference between this and SOME? (declaim (inline any-in-list)) ;; should collapse into being pretty small (defun any-in-list (predicate list &optional (key #'identity)) (let ((ans nil)) (if (eq key #'identity) (csome (item list ans) (setf ans (funcall predicate item))) (csome (item list ans) (setf ans (funcall predicate (funcall key item))))) ans)) (declaim (inline every-in-list)) (defun every-in-list (predicate list &optional (key #'identity)) (let ((ans nil)) (if (eq key #'identity) (csome (item list ans) (setf ans (not (funcall predicate item)))) (csome (item list ans) (setf ans (not (funcall predicate (funcall key item)))))) (not ans))) (defparameter *subseq-subst-recursive-answers* nil) (defun* extremal (list test &optional (key #'identity)) (:inline t) "[Cyc] Return the first item in LIST which maximizes TEST." (when list (let ((best (first list))) (if (eq key #'identity) (dolist (item (rest list)) (when (funcall test item best) (setf best item))) (dolist (item (rest list)) (when (funcall test (funcall key item) (funcall key best)) (setf best item)))) best))) (defun position-< (item1 item2 guide-seq &optional (test #'eql) (key #'identity)) "[Cyc] Return T iff the position of ITEM1 in GUIDE-SEQ is less than that of ITEM2. All objects not in the GUIDE-SEQ are considered to be after all those that are, and are themselves considered equivalent by this test." (let ((position1 (position item1 guide-seq :test test :key key)) (position2 (position item2 guide-seq :test test :key key))) (if position1 (if position2 (< position1 position2) t) nil))) (defparameter *sort-via-position-guide* nil) (defparameter *sort-via-position-test* nil) (defun sort-via-position (seq guide-seq &optional (test #'eql) (key #'identity)) "[Cyc] Sort SEQ using GUIDE-SEQ as a positional guide. Objects in GUIDE-SEQ appear in the order they are in GUIDE-SEQ. Objects not in GUIDE-SEQ all appear after those that do." (let ((*sort-via-position-guide* guide-seq) (*sort-via-position-test* test)) (sort seq #'sort-via-position-earlier :key key))) (defun stable-sort-via-position (seq guide-seq &optional (test #'eql) (key #'identity)) (let ((*sort-via-position-guide* guide-seq) (*sort-via-position-test* test)) (stable-sort seq #'sort-via-position-earlier :key key))) (defun sort-via-position-earlier (item1 item2) (position-< item1 item2 *sort-via-position-guide* *sort-via-position-test*)) (defparameter *sort-via-test-function* nil) (defun safe-= (object1 object2) (when (and (numberp object1) (numberp object2)) (= object1 object2))) (defun parameterized-median (list sort-pred) "[Cyc] Returns the median of a list, after sorting by SORT-PRED. It picks the larger if the median falls in the middle. Example: (parameterized-median '(1 2 3 4 5) #'<) 3 Example: (parameterized-median '(4 1 2 5 3) #'<) 3 Example: (parameterized-median '(4 1 2 5) #'<) 4" (let ((sorted-list (sort (copy-list list) sort-pred))) (nth (floor (length sorted-list) 2) sorted-list))) (defun tree-find (item object &optional (test #'eql) (key #'identity)) "[Cyc] For the first sub-object in OBJECT (including OBJECT) that satisfies TEST applied to KEY of it and ITEM, return the sub-object. Return 0: the found sub-object Return 1: T if a sub-object is found." ;; TODO - optimized version with test & key known (cond ((funcall test item (funcall key object)) (values object t)) ((consp object) (do* ((list object (cdr list)) (sub (car list) (car list))) ((not (consp (cdr list))) ;; Ending forms (multiple-value-bind (ans found?) (tree-find item (car list) test key) (when found? (return (values ans found?)))) (alexandria:when-let ((cdr (cdr list))) (multiple-value-bind (ans found?) (tree-find item cdr test key) (when found? (return (values ans found?))))) (values nil nil)) ;; Iteration (multiple-value-bind (ans found?) (tree-find item sub test key) (when found? (return (values ans found?)))))) (t (values nil nil)))) (defun simple-tree-find? (item object) "[Cyc] Return T iff the non-nil ITEM is found in OBJECT (via EQ)." (cond ((eq item object) t) ((consp object) (do* ((list object (cdr list)) (sub (car list) (car list))) ((not (consp (cdr list))) ;; Ending forms, searches the final cons cell's car & cdr (or (simple-tree-find? item (car list)) (and (cdr list) (simple-tree-find? item (cdr list))))) ;; Iteration ;; TODO - unwrap the equality test & use a LABELS to avoid leaf recursion, both here and in the -equal version below. (when (simple-tree-find? item sub) (return t)))))) (defun simple-tree-find-via-equal? (item object) "[Cyc] Return T iff the non-nil ITEM is found in OBJECT (via EQUAL)" (cond ((equal item object) t) ((consp object) (do* ((list object (cdr list)) (sub (car list) (car list))) ((not (consp (cdr list))) ;; Ending forms (or (simple-tree-find-via-equal? item (car list)) (and (cdr list) (simple-tree-find-via-equal? item (cdr list))))) ;; Iteration (when (simple-tree-find-via-equal? item sub) (return t)))))) (defun tree-find-any (items tree &optional (test #'eql) (key #'identity)) "[Cyc] Look for any of ITEMS in the tree OBJECT. Return the first item found, or NIL if none found." (dolist (item items) (when (tree-find item tree test key) (return item)))) (defun cons-tree-find-if (test object &optional (key #'identity)) "[Cyc] Obsolete -- use tree-find-if" ;; TODO - mark obsolete (tree-find-if test object key)) (defun tree-find-if (test object &optional (key #'identity)) (cond ((funcall test (funcall key object)) object) ((consp object) (do* ((list object (cdr list)) (sub (car list) (car list))) ((not (consp (cdr list))) (or (tree-find-if test (car list) key) (and (cdr list) (tree-find-if test (cdr list) key)))) (alexandria:when-let ((ans (tree-find-if test sub key))) (return ans)))))) (defun tree-count-if (test object &optional (key #'identity)) (cond ((funcall test (funcall key object)) 1) ((consp object) (let ((total 0)) (do* ((list object (cdr list)) (sub (car list) (car list))) ((not (consp (cdr list))) (incf total (tree-count-if test (car list) key)) (when (cdr list) (incf total (tree-count-if test (cdr list) key))) total) (incf total (tree-count-if test sub key))))) (t 0))) (defun tree-gather (object predicate &optional (test #'eql) (key #'identity) (subs-too? t)) (nreverse (tree-gather-internal object predicate test key subs-too? nil))) (defun tree-gather-internal (object predicate test key subs-too? so-far) (let ((result so-far)) (when (funcall predicate (funcall key object)) (if test (pushnew object result :test test) (push object result)) (unless subs-too? (return-from tree-gather-internal result))) (when (consp object) (do* ((list object (cdr list)) (sub (car list) (car list))) ((not (consp (cdr list))) (setf result (tree-gather-internal (car list) predicate test key subs-too? result)) (when (cdr list) (setf result (tree-gather-internal (cdr list) predicate test key subs-too? result)))) (setf result (tree-gather-internal sub predicate test key subs-too? result)))) result)) (defun delete-subsumed-items (list test &optional (key #'identity)) "[Cyc] If a and b are in LIST, and (TEST (KEY a) (KEY b)) is true, don't include b in the result" (declare (ignore test key)) (when list (missing-larkc 9081))) (defun permute-list (elements &optional (test #'equal)) "[Cyc] Return a list of all possible distinct ordered lists of the elements in ELEMENTS. By convention, (permute-list NIL) -> NIL. By convention, if TEST is NIL, the check for duplicates is skipped." (when elements (let ((number-of-elements (length elements)) (result nil)) (cond ((null test) (dolist (permutation (all-permutations (length elements))) (push (permute elements permutation) result))) ((< number-of-elements 5) (dolist (permutation (all-permutations (length elements))) (pushnew (permute elements permutation) result :test test))) (t (dolist (permutation (all-permutations (length elements))) (push (permute elements permutation) result)) (setf result (fast-delete-duplicates result test)))) result))) (defun permute-list-int (elements &optional (test #'eq)) "[Cyc] Given a list of elements, return all permutations of the elements. Assumes no two elements are equal with respect to TEST." (cond ((not elements) nil) ((atom elements) (list elements)) ((not (cdr elements)) (list elements)) ((not (cddr elements)) (list elements (reverse elements))) (t (let ((perms nil)) (dolist (elem elements) (dolist (perm (permute-list-int (remove elem elements :test test))) (push (cons elem perm) perms))) perms)))) (defun all-permutations (n) "[Cyc] Returns all permutations of the numbers from 0 to N-1. By convention, (all-permutations 0) -> (NIL)." (if (zerop n) (list nil) (permute-list-int (num-list n)))) (defun permute (list permutation) "[Cyc] e.g. (permute '(a b c) '(2 0 1)) -> (c a b) By convention, (permute X NIL) -> X." (if permutation (let (result) (dolist (elem permutation) (push (nth elem list) result)) (nreverse result)) list)) (defun cartesian-product (l &optional (fun #'cons) (start '()) test) "[Cyc] Returns a list of the cartesian product of the elements of l. FUN: an optional function to build the product. START: an optional seed for building the product." (let ((accum (list start))) (if (fboundp test) (dolist (this-one l) (declare (ignore this-one)) (setf accum (missing-larkc 9053))) (dolist (this-one l) (setf accum (cartesian-helper this-one accum fun)))) (nmapcar #'reverse accum))) (defun cartesian-helper (a b fun) "[Cyc] Takes two lists and returns the cartesian product. FUN generally should be #'CONS." (let (accum) (dolist (b-er b) (dolist (a-er a) (push (funcall fun a-er b-er) accum))) (nreverse accum))) (defun list-of-type-p (pred object) "[Cyc] Returns T if OBJECT is a non-dotted list, and PRED returns non-NIL when applied to any item in OBJECT. Otherwise, returns NIL." (when (non-dotted-list-p object) (some pred object)))
42,375
Common Lisp
.lisp
870
40.770115
295
0.6332
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
5a9e04fc08c34028b91f43b9198c86c380a23c5ed4fba64ca4772311ba14ae4a
6,738
[ -1 ]
6,739
cycl-utilities.lisp
white-flame_clyc/larkc-cycl/cycl-utilities.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO - defun as symbol, forward referenced in this file (defparameter *opaque-arg-function* 'default-opaque-arg? "[Cyc] The function to use to determine argument opacity.") ;; TODO - defun as symbol, forward referenced in this file (defparameter *opaque-seqvar-function* 'default-opaque-seqvar? "[Cyc] The function to use to determine sequence variable opacity.") (defun opaque-arg? (formula argnum) "[Cyc] Returns T iff FORMULA is opaque in the argument position ARGNUM, meaning that it should not be recursed into in that arg position. By convention, if ARGNUM is greater than the arity of FORMULA, this denotes the sequence variable in FORMULA." (opaque-arg?-int formula argnum *opaque-arg-function*)) (defun* expression-nsubst-free-vars (new old expression &optional (test #'eql)) (:inline t) (expression-nsubst-free-vars-int new old expression test)) (defun expression-nsubst-free-vars-int (new old expression test) "[Cyc] Replaces free var in the EXPRESSION. Takes quoting into account. *CANONICALIZE-VARIABLES?* determines whether #$EscapeQuotes will be removed / reduced from the quoted terms. If variables are to be canonicalized then the #$EscapeQuotes will already contain HL variables due to the various czer steps before. This step just removes the #$EscapeQuotes to complete the canonicalization of the variables." (cond ((funcall test expression old) (if *inside-quote* expression new)) ((not (el-formula-p expression)) expression) ((or (fast-escape-quote-term-p expression) (fast-quasi-quote-term-p expression)) (let ((*inside-quote* nil)) (if *canonicalize-variables?* (expression-nsubst-free-vars-int new old (formula-arg1 expression) test) (make-unary-formula (formula-arg0 expression) (expression-nsubst-free-vars-int new old (formula-arg1 expression) test))))) ((fast-quote-term-p expression) (let ((*inside-quote* t)) (make-unary-formula #$Quote (expression-nsubst-free-vars-int new old (formula-arg1 expression) test)))) ((and (expand-subl-fn-p expression) (member? old (formula-arg1 expression) :test test)) (make-binary-formula #$ExpandSubLFn (subst new old (formula-arg1 expression) :test test) (expression-nsubst-free-vars-int new old (formula-arg2 expression) test))) (t (let* ((seqvar (sequence-var expression)) (substituted-seqvar (if (when seqvar (not (opaque-seqvar? expression))) (expression-nsubst-free-vars-int new old seqvar test) seqvar))) (do* ((rest-of-expression expression (rest rest-of-expression)) (term (car rest-of-expression) (car rest-of-expression)) (argnum 0 (1+ argnum))) ;; End test ((not (consp (cdr rest-of-expression))) ;; Return forms (unless (opaque-arg-wrt-free-vars? expression argnum) (rplaca rest-of-expression (expression-nsubst-free-vars-int new old term test))) (rplacd rest-of-expression substituted-seqvar) expression) ;; Iteration body (unless (opaque-arg-wrt-free-vars? expression argnum) (rplaca rest-of-expression (expression-nsubst-free-vars-int new old term test)))))))) (defun* opaque-seqvar? (formula) (:inline t) "[Cyc] Returns T iff FORMULA contains an opaque sequence variable, which should not be considered a proper part of the formula." (funcall *opaque-seqvar-function* formula)) (defun* nat-arg2 (nat &optional (seqvar-handling :ignore)) (:inline t) "[Cyc] Returns the 2nd argument of NAT. Returns NIL if NAT is not a nat." (nat-arg nat 2 seqvar-handling)) (defun* opaque-arg?-int (formula argnum opaque-arg-function) (:inline t) ;; This did a case to find known function names and bypass funcall. (funcall opaque-arg-function formula argnum)) (defun* formula-arg4 (formula &optional (seqvar-handling :ignore)) (:inline t) "[Cyc] Returns the 4th argument of FORMULA. Returns NIL if FORMULA is not a formula." (formula-arg formula 4 seqvar-handling)) (defun* formula-arg5 (formula &optional (seqvar-handling :ignore)) (:inline t) "[Cyc] Returns the 5th argument of FORMULA. Returns NIL if FORMULA is not a formula." (formula-arg formula 5 seqvar-handling)) (defun default-opaque-arg? (formula argnum) (when (formula-arity< formula argnum) (missing-larkc 29826)) (subl-escape-p formula)) (defun opaque-arg-wrt-free-vars? (formula argnum) (cond ((and (= 2 argnum) (el-formula-with-operator-p formula #$SkolemFunctionFn)) t) ((formula-arity< formula argnum) (missing-larkc 29827)) (t (subl-quote-p formula)))) (defun opaque-arg-wrt-quoting? (formula argnum) "[Cyc] Return T iff arg number ARGNUM of FORMULA is quoted or otherwise opaque." (or (default-opaque-arg? formula argnum) (and (not (tou-lit? formula)) (or (fast-quote-term-p (formula-arg formula argnum)) (quoted-argument? (formula-arg0 formula) argnum))))) (defun opaque-arg-wrt-quoting-not-counting-logical-ops? (formula argnum) (unless (or (el-formula-with-operator-p formula #$trueSentence) (cyc-const-logical-operator-p (formula-operator formula)) (cyc-const-quantifier-p (formula-operator formula))) (opaque-arg-wrt-quoting? formula argnum))) (defun hl-term-with-el-counterpart-p (object) "[Cyc] Return T iff OBJECT is an HL term with an EL counterpart." (or (valid-nart-handle? object) (valid-assertion-handle? object) (variable-p object))) (defun careful-hl-term-to-el-term (hl-term) "[Cyc] Converts HL-TERM to an EL term if HL-TERM has an EL counterpart, otherwise leaves HL-TERM unchanged. Not robust against invalid narts or assertions. Note: Careful: the result is not destructible!" (cond ((nart-p hl-term) (funcall *nart-key* hl-term)) ((assertion-p hl-term) (funcall *assertion-key* hl-term)) ((variable-p hl-term) (default-el-var-for-hl-var hl-term)) (t hl-term))) (defun reified-term-p (object) (or (atomic-reified-term-p object) (reified-formula-p object))) (defun* atomic-reified-term-p (object) (:inline t) (constant-p object)) (defun* reified-formula-p (object) (:inline t) (hl-formula-p object)) ;;TODO DESIGN - again a long list of parameters that are passed through multiple levels. Reevaluate. (defun expression-gather-int-2 (expression pred penetrate-hl-structures? key subs-too?) (let ((result (when (funcall pred (funcall key expression)) (list expression)))) (when (or subs-too? result) (cond ((and penetrate-hl-structures? (hl-term-with-el-counterpart-p expression)) (npush-list (expression-gather-int-2 (careful-hl-term-to-el-term expression) pred t key subs-too?) result)) ((el-formula-p expression) nil) (t (dolistn (argnum term (formula-terms expression :regularize)) (unless (opaque-arg? expression argnum) (npush-list (expression-gather-int-2 term pred penetrate-hl-structures? key subs-too?) result)))))) result)) (defun expression-gather-int (expression pred penetrate-hl-structures? test key subs-too?) (fast-delete-duplicates (expression-gather-int-2 expression pred penetrate-hl-structures? key subs-too?) test key)) (defun* expression-gather (expression pred &optional penetrate-hl-structures? (test #'eql) (key #'identity) (subs-too? t)) (:inline t) "[Cyc] Return a list of all objects within EXPRESSION which pass the test PRED, without duplicates but in no particular order. See file-level documentation for explanation of PENETRATE-HL-STRUCTURES? and #$ExpandSubLFn. Returns the singleton list containing EXPRESSION if EXPRESSION passes PRED." (expression-gather-int expression pred penetrate-hl-structures? test key subs-too?)) (defun assertion-gather (pred assertion &optional penetrate-hl-structures? (test #'eql) (key #'identity) (subs-too? t)) (when (hl-term-with-el-counterpart-p assertion) (let ((mt-objects (expression-gather-int (assertion-mt assertion) pred penetrate-hl-structures? test key subs-too?)) (formula-objects (expression-gather-int (assertion-cons assertion) pred penetrate-hl-structures? test key subs-too?))) (cond ((not mt-objects) formula-objects) ((not formula-objects) mt-objects) (t (fast-delete-duplicates (nconc mt-objects formula-objects) test key)))))) (defparameter *expression-count-item* nil) (defparameter *expression-count-test* nil) (defun* formula-gather (formula pred &optional penetrate-hl-structures? (test #'eql) (key #'identity) (subs-too? t)) (:inline t) "[Cyc] Return a list of all objects within the EL formula FORMULA which pass the test PRED, without duplicates but in no particular order. See file-level documentation for explanation of PENETRATE-HL-STRUCTURES? and #$ExpandSubLFn." (expression-gather formula pred penetrate-hl-structures? test key subs-too?)) (defun* expression-narts (expression &optional penetrate-hl-structures? (subs-too? t)) (:inline t) "[Cyc] Return a list of the narts mentioned in EXPRESSION, without duplicates but in no particular order. See file-level documentation for explanation of PENETRATE-HL-STRUCTURES? and #$ExpandSubLFn. Returns the singleton list containing EXPRESSION if EXPRESSION is a nart." (expression-gather-int expression #'nart-p penetrate-hl-structures? #'eq #'identity subs-too?)) (defparameter *containing-subexpressions-labmda-term* nil) (defun expression-find-if-int (test expression penetrate-hl-structures? key) (let* ((transformed-expression (if (eq key #'identity) expression (funcall key expression))) (test-succeeded? (funcall test transformed-expression))) (cond (test-succeeded? expression) ((and penetrate-hl-structures? (hl-term-with-el-counterpart-p expression)) (expression-find-if-int test (careful-hl-term-to-el-term expression) t key)) ((el-formula-p expression) nil) (t (dolistn (argnum term (formula-terms expression :regularize)) (unless (opaque-arg? expression argnum) (return (expression-find-if-int test term penetrate-hl-structures? key)))))))) (defun expression-find-if (test expression &optional penetrate-hl-structures? (key #'identity)) "[Cyc] Return an object which passes the test TEST if such an object exists within the CycL expression EXPRESSION. Otherwise NIL. See file-level documentation for explanation of PENETRATE-HL-STRUCTURES? and #$ExpandSubLFn." (unless (and (not penetrate-hl-structures?) (not (tree-find-if test expression key))) (expression-find-if-int test expression penetrate-hl-structures? key))) (defun* formula-find-if (test formula &optional penetrate-hl-structures? (key #'identity)) (:inline t) "[Cyc] Return an object which passes the test TEST if such an object exists within the EL formula FORMULA. Otherwise NIL. See file-level documentation for explanation of PENETRATE-HL-STRUCTURES? and #$ExpandSubLFn." (expression-find-if test formula penetrate-hl-structures? key)) (defun expression-find-int (object expression penetrate-hl-structures? test key) (cond ((funcall test object (funcall key expression)) expression) ((and penetrate-hl-structures? (hl-term-with-el-counterpart-p expression)) (expression-find-int object (careful-hl-term-to-el-term expression) t test key)) ((not (el-formula-p expression)) nil) (t (dolistn (argnum term (formula-terms expression :regularize)) (unless (opaque-arg? expression argnum) (return (expression-find-int object term penetrate-hl-structures? test key))))))) (defun* expression-find (object expression &optional penetrate-hl-structures? (test #'eql) (key #'identity)) (:inline t) "[Cyc] Return OBJECT if it is found within the CycL expression EXPRESSION, otherwise NIL. See file-level documentation for explanation of PENETRATE-HL-STRUCTURES? and #$ExpandSubLFn." (expression-find-int object expression penetrate-hl-structures? test key)) (deflexical *default-transformation-limit* 212) ;; These arglists are getting nuts. Not bothering with formatting these. (defun expression-ntransform-int (expression pred transform transform-sequence-variables? transformation-limit transformation-level test-pred-on-transformation-result? negate-pred?) "[Cyc] Opacity can change during transformation - it's unclear what the desired behaviour is, though. PRED has a different meaning based on test-pred-on-transformation-result? and negate-pred?" (when (> transformation-level transformation-limit) (throw :transformation-limit-exceeded transformation-limit)) (let ((transformed-expression nil)) (if test-pred-on-transformation-result? (let ((transform-result (funcall transform expression))) ;; makeBoolean(..) != makeBoolean(..) should be equivalent to XOR ;; a single NOT should booleanify the variables, and we only care about equivalence (if (not (eq (not negate-pred?) (not (funcall pred transform-result)))) (setf transformed-expression (expression-ntransform-int transform-result pred transform transform-sequence-variables? transformation-limit (1+ transformation-level) test-pred-on-transformation-result? negate-pred?)) (setf transformed-expression expression))) (if (not (eq (not negate-pred?) (not (funcall pred expression)))) (let ((transform-result (funcall transform expression))) (if (not (eq expression transform-result)) (setf transformed-expression (expression-ntransform-int transform-result pred transform transform-sequence-variables? transformation-limit (1+ transformation-level) test-pred-on-transformation-result? negate-pred?)) (setf transformed-expression expression))) (setf transformed-expression expression))) (unless (el-formula-p transformed-expression) transformed-expression) (let* ((seqvar (sequence-var transformed-expression)) (transformed-seqvar (if (and seqvar transform-sequence-variables? (missing-larkc 29828)) ;; Missing-larkc kills this anyway nil ;;(expression-ntransform-int seqvar pred transform t transformation-limit (1+ transformation-level) test-pred-on-transformation-result? negate-pred?) seqvar)) (ist-sentence? (ist-sentence-p transformed-expression)) (new-mt nil)) ;; This is mutating the actual list, so we do need to expose the cons cells (loop for rest-of-expression on transformed-expression for term = (car rest-of-expression) for argnum from 0 do (let* ((mt-var new-mt) (*relevant-mt-function* (possibly-in-mt-determine-function mt-var)) (*mt* (possibly-in-mt-determine-mt mt-var))) (unless (opaque-arg? transformed-expression argnum) (rplaca rest-of-expression (expression-ntransform-int term pred transform transform-sequence-variables? transformation-limit (1+ transformation-level) test-pred-on-transformation-result? negate-pred?)) (when (and ist-sentence? (= argnum 1)) (setf new-mt (car rest-of-expression))))) ;; Last cons elemnt ;; TODO - this test is redundant with for-on, maybe wrap our own macro for a raw DO form. do (when (not (consp (cdr rest-of-expression))) (unless (opaque-arg? transformed-expression argnum) (rplaca rest-of-expression (expression-ntransform-int term pred transform transform-sequence-variables? transformation-limit (1+ transformation-level) test-pred-on-transformation-result? negate-pred?))) (rplacd rest-of-expression transformed-seqvar))) transformed-expression))) (defun* expression-transform (expression pred transform &optional transform-sequence-variables? (transformation-limit *default-transformation-limit*)) (:inline t) "[Cyc] Recursively tests PRED within the CycL expression EXPRESSION. If PRED applies to EXPRESSION or a subexpression/subterm of EXPRESSION, TRANSFORM is called on that term or expression. If an expression is transformed into another expression, the result is itself subjected to the transformation if PRED applies to the result. Thus one must take care when calling this function, to avoid infinite recursion. It does not penetrate into HL structures." (expression-ntransform-int (copy-expression expression) pred transform transform-sequence-variables? transformation-limit 0 nil nil)) (defun expression-nsublis-free-vars-int (alist expression test) "[Cyc] Replaces free vars in the EXPRESSION. Takes quoting into account. *CANONICALIZE-VARIABLES?* determines whether #$EscapeQuotes will be removed / reduced from the quoted terms. If variables are to be canonicalized then the #$EscapeQuotes will already contain HL variables due to the various czer steps before. This step just removes the #$EscapeQuotes to complete the canonicalization of the variables." ;; TODO - this was oldXnew in the java, not sure what the punc was supposed to be (when-let ((old-new (assoc expression alist :test test))) (if *inside-quote* expression (cdr old-new))) (cond ((not (el-formula-p expression)) expression) ((or (fast-escape-quote-term-p expression) (fast-quasi-quote-term-p expression)) (let ((*inside-quote* nil)) (if *canonicalize-variables?* (expression-nsublis-free-vars-int alist (formula-arg1 expression) test) (make-unary-formula (formula-arg0 expression) (expression-nsublis-free-vars-int alist (formula-arg1 expression) test))))) ((fast-quote-term-p expression) (let ((*inside-quote* t)) (make-unary-formula #$Quote (expression-nsublis-free-vars-int alist (formula-arg1 expression) test)))) ((expand-subl-fn-p expression) (let* ((arg1 (formula-arg1 expression)) (vars (expression-gather arg1 #'cyc-var?)) (non-opaque-var-list nil)) (when vars (dolist (var vars) (when-let ((old-new (assoc var alist :test test))) (push old-new non-opaque-var-list))) (if non-opaque-var-list (make-binary-formula #$ExpandSubLFn (expression-nsublis-free-vars-int alist arg1 test) (expression-nsublis-free-vars-int non-opaque-var-list (formula-arg2 expression) test)) expression)))) (t (let* ((seqvar (sequence-var expression)) (substituted-seqvar (if (and seqvar (missing-larkc 29829)) ;; missing-larkc kills that anyway nil ;;(expression-nsublis-free-vars-int alist seqvar test) seqvar))) (loop for rest-of-expression on expression for term = (car rest-of-expression) for argnum from 0 do (unless (opaque-arg-wrt-free-vars? expression argnum) (rplaca rest-of-expression (expression-nsublis-free-vars-int alist term test))) ;; Last cons element do (when (not (consp (cdr rest-of-expression))) (unless (opaque-arg-wrt-free-vars? expression argnum) (rplaca rest-of-expression (expression-nsublis-free-vars-int alist term test))) (rplacd rest-of-expression substituted-seqvar))) expression)))) (defun* expression-nsublis-free-vars (alist expression &optional (test #'eql)) (:inline t) (expression-nsublis-free-vars-int alist expression test)) ;; TODO - probably from a missing-larkc defun-memoized? (deflexical *permute-list-cached-caching-state* nil) (defun canonical-commutative-permutations (formula &optional (var? #'cyc-var?) penetrate-args?) "[Cyc] Return the permutations of the formula that can be possibly canonical. For fully bound formula, it returns the formula. For non fully-bound formula, it return the permutations of the variable arg with the other args in canonical order. Doesn't permute sequence vars." (if (ground? formula var?) (list (canonicalize-literal-commutative-terms formula)) (let ((variable-argnums (variable-argnums formula var?))) (cond ((and (not penetrate-args?) (not variable-argnums)) (list (canonicalize-literal-commutative-args formula))) ((and penetrate-args? (not variable-argnums)) (nreverse (args-canonical-commutative-permutations (canonicalize-literal-commutative-terms formula) var?))) (t (let ((target-formulas (if (and penetrate-args? variable-argnums) (args-canonical-commutative-permutations (canonicalize-literal-commutative-terms formula) var?) (list (canonicalize-literal-commutative-args formula))))) (nreverse (formulas-canonical-permutations target-formulas)))))))) (defun variable-argnums (formula &optional (var? #'cyc-var?)) (unless (ground? formula var?) (let ((argnums nil)) (dolistn (argnum arg (formula-args formula :ignore)) (when (funcall var? arg) (push argnum argnums))) argnums))) (defun args-canonical-commutative-permutations (formula var?) "[Cyc] Result is destructible. If any of the arg of the formula has a commutative relation formula, the commutative permutations for those args are generated." (let ((target-formulas (list (copy-formula formula)))) (dolistn (argnum arg (formula-args formula :ignore)) (cond ((subl-escape-p arg) nil) ((naut? arg) (missing-larkc 29803)) ((el-relation-expression? arg) (dolist (formula-permutation (canonical-commutative-permutations arg var? t)) (unless (equal formula-permutation arg) (push (nreplace-formula-arg argnum formula-permutation (copy-formula formula)) target-formulas)))))) target-formulas)) (defun formulas-canonical-permutations (source-formulas) (let ((target-formulas nil) (permuted? nil)) (dolist (source-formula source-formulas) (dolist (commutative-argnums (commutative-argnums source-formula)) (let* ((variable-argnums (variable-argnums source-formula)) (argnums-to-permute (fast-intersection commutative-argnums variable-argnums)) (other-argnums nil) (argnum-permutations nil)) (if argnums-to-permute (progn (setf other-argnums (nreverse (set-difference commutative-argnums argnums-to-permute))) (setf argnum-permutations (permutations-merge other-argnums argnums-to-permute)) (setf permuted? t) (dolist (argnum-permutation argnum-permutations) (push (canonical-permute-formula source-formula commutative-argnums argnum-permutation) target-formulas))) (push source-formula target-formulas))))) (if permuted? (delete-duplicates target-formulas :test #'equal) source-formulas))) (defun canonical-permute-formula (source-formula argnums-to-permute argnum-permutation) "[Cyc] Result is destructible." (let ((target-formula (copy-formula source-formula))) (dolistn (index source-argnum argnum-permutation) (let ((target-argnum (nth index argnums-to-permute))) (unless (eq target-argnum source-argnum) (let ((target-term (formula-arg source-formula source-argnum))) (setf target-formula (nreplace-formula-arg target-argnum target-term target-formula)))))) target-formula)) (defun split-list-set (l) (let ((splits (list l nil)) (length (length l))) (loop for i from 1 below length do (multiple-value-bind (list1 list2) (split-list l i) (push (list list1 list2) splits))) splits)) (defun permutations-merge (list1 list2) (let ((merged nil) (permutations (permute-list list2)) (list1-splits (split-list-set list1))) ;; TODO - test and ensure all this nesting is correct (dolist (list1-split list1-splits) (destructuring-bind (front1 rest1) list1-split (dolist (permutation permutations) (let ((list2-splits (split-list-set permutation))) (dolist (list2-split list2-splits) (destructuring-bind (front2 rest2) list2-split (push (append front1 front2 rest1 rest2) merged) (push (append front2 front1 rest2 rest1) merged))))))) (delete-duplicates merged :test #'equal))) (defparameter *renamed-default-el-var-prefix* "?RENAMED-VAR") (deflexical *non-indexed-constants* (append *cyc-const-unary-logical-ops* *cyc-const-binary-logical-ops* *cyc-const-ternary-logical-ops* *cyc-const-quaternary-logical-ops* *cyc-const-quintary-logical-ops* *cyc-const-variable-arity-logical-ops* *cyc-const-regular-quantifiers* *cyc-const-bounded-existentials* *cyc-const-exception-operators* *cyc-const-pragmatic-requirement-operators*) "[Cyc] Cyc constants that have no indexing maintained for them. All other constants except instances of #$ELRelation are indexed (4/3/00)") (defun functional-in-some-arg? (pred) "[Cyc] Returns non-NIL iff PRED is functional in some argument." (or (some-pred-assertion-somewhere? #$functionalInArgs pred 1) (some-pred-assertion-somewhere? #$strictlyFunctionalInArgs pred 1))) (defun reify-arg-when-closed-naut (reln psn) (let ((object (formula-arg reln psn))) (if (arg-types-prescribe-unreified? reln psn) object (reify-when-closed-naut object)))) (defun reify-when-closed-naut (object) (cond ((not (possibly-naut-p object)) object) ((closed-naut? object) (or (nart-substitute object) object)) ((el-formula? object) (loop for psn from 0 below (formula-length object :ignore) collect (reify-arg-when-closed-naut object psn))) (t object))) (defun find-closed-naut (object) "[Cyc] If OBJECT is a closed, unreified, specification of a reified non-atomic term, then return the NART implementing the reification; otherwise return NIL." (when (closed-naut? object) (missing-larkc 10332))) (defun find-ground-naut (object) "[Cyc] If OBJECT is a ground, unreified, specification of a reified non-atomic term, then return the NART implementing the reification; otherwise return NIL." (when (ground-naut? object) (missing-larkc 10333))) (defun atomic-sentence-with-pred-p (asent pred) "[Cyc] Returns T iff ASENT is (possibly) an atomic sentence with predicate PRED. Assumes equality can be tested with #'eq." (and (possibly-atomic-sentence-p asent) (eq pred (atomic-sentence-predicate asent)))) (defun atomic-sentence-with-any-of-preds-p (asent preds) "[Cyc] Returns T iff ASENT is (possibly) an atomic sentence with a predicate in PREDS. Assumes equality can be tested with #'eq." (and (possibly-atomic-sentence-p asent) (member-eq? (atomic-sentence-predicate asent) preds))) (defun possibly-cycl-formula-p (object) "[Cyc] Returns T iff OBJECT is an EL formula, a nart, or an assertion." (or (el-formula-p object) (nart-p object) (assertion-p object))) (defun negated? (form) "[Cyc] Assuming FORM is a valid CycL formula, return T IFF it is negated." (and (consp form) (eq (first form) #$not) (length= form 2))) (defun negate (form) "[Cyc] Assuming FORM is a valid CycL formula, return a negated version of it." (if (negated? form) (formula-arg1 form) (list #$not form))) (defun possibly-negate (sentence truth) "[Cyc] Assuming SENTENCE is a CycL sentence, return a negated version of it if TRUTH is :FALSE" ;; Technically, the comment should say "is not :TRUE". (if (eq truth :true) sentence (negate sentence))) (defun formula-arg (formula argnum &optional (seqvar-handling :ignore)) "[Cyc] Returns the ARGNUMth argument of FORMULA. An ARGNUM of 0 will return the operator. Works with forts and assertions. If seqvar-handling is :IGNORE, it will return NIL if asked for the arg position where the sequence variable is. If seqvar-handling is :REGULARIZE, it will return the sequence variable if asked for its position. e.g. (formula-arg (<pred> <arg1> . ?SEQ) 2 :IGNORE) -> NIL but (formula-arg (<pred> <arg1> . ?SEQ) 2 :REGULARIZE) -> ?SEQ" (cond ((not (non-negative-integer-p argnum)) nil) ((el-formula-p formula) (el-formula-arg formula argnum seqvar-handling)) ((nart-p formula) (missing-larkc 10395)) ((assertion-p formula) (el-formula-arg (assertion-hl-formula formula) argnum)))) (defun el-formula-arg (el-formula argnum &optional (seqvar-handling :ignore)) "[Cyc] Returns the ARGNUMth argument of EL-FORMULA. An ARGNUM of 0 will return the operator. If seqvar-handling is :ignore, it will return NIL if asked for the arg position where the sequence variable is. If seqvar-handling is :regularize, it will return the sequence variable if asked for its position. e.g. (el-formula-arg (<pred> <arg1> . ?SEQ) 2 :IGNORE) -> NIL but (el-formula-arg (<pred> <arg1> . ?SEQ) 2 :REGULARIZE) -> ?SEQ" (when (el-formula-arity>= el-formula argnum seqvar-handling) (nth argnum (el-formula-terms el-formula seqvar-handling)))) (defun formula-arg0 (formula) "[Cyc] Returns the 0th argument of FORMULA, which is by convention the operator. Returns NIL if FORMULA is not a formula." (cond ((el-formula-p formula) (el-formula-operator formula)) ((nart-p formula) (missing-larkc 10396)) ((assertion-p formula) (el-formula-operator (assertion-hl-formula formula))))) (defun* formula-operator (formula) (:inline t) "[Cyc] Returns the operator of FORMULA. Returns NIL if FORMULA is not a formula." (formula-arg0 formula)) (defun* el-formula-operator (el-formula) (:inline t) "[Cyc] Returns the operator of EL-FORMULA." (car el-formula)) (defun* formula-arg1 (formula &optional (seqvar-handling :ignore)) (:inline t) (formula-arg formula 1 seqvar-handling)) (defun* formula-arg2 (formula &optional (seqvar-handling :ignore)) (:inline t) "[Cyc] Returns the 2nd argument of FORMULA. Returns NIL if FORMULA is not a formula." (formula-arg formula 2 seqvar-handling)) (defun* formula-arg3 (formula &optional (seqvar-handling :ignore)) (:inline t) "[Cyc] Returns the 3rd argument of FORMULA. Returns NIL if FORMULA is not a formula." (formula-arg formula 3 seqvar-handling)) (defun formula-args (formula &optional (seqvar-handling :ignore)) "[Cyc] Returns the arguments of FORMULA. If seqvar-handling is :IGNORE, it chops off the sequence var if there is one. If seqvar-handling is :REGULARIZE, it treats the sequence var as a regular variable. If seqvar-handling is :INCLUDE, it returns it as a sequence var. Note that using the :INCLUDE option may cause formula-args to return a variable instead of a list! e.g. (formula-args (#$different . ?X) :INCLUDE) -> ?X Does the right thing for narts and assertions, but ignores the MT of the assertion. Returns NIL if FORMULA is not a possibly-cycl-formula-p." (cond ((el-formula-p formula) (el-formula-args formula seqvar-handling)) ((nart-p formula) (missing-larkc 10397)) ((assertion-p formula) (el-formula-args (assertion-hl-formula formula))))) (defun el-formula-args (el-formula &optional (seqvar-handling :ignore)) "[Cyc] Return the arguments of FORMULA. If seqvar-handling is :IGNORE, it chops off the sequence var if there is one. If seqvar-handling is :REGULARIZE, it treats the sequence var as a regular variable. If seqvar-handling is :INCLUDE, it returns it as a sequence var. Note that using the :INCLUDE option may cause el-formula-args to return a variable instead of a list! e.g. (el-formula-args (#$different . ?X) :INCLUDE) -> ?X" (if (non-dotted-list-p el-formula) (cdr el-formula) (formula-terms-int (cdr el-formula) seqvar-handling))) (defun formula-terms (formula &optional (seqvar-handling :ignore)) "[Cyc] R a list of the terms in FORMULA. If seqvar-handling is :IGNORE, it chops off the sequence var if there is one. If seqvar-handling is :REGULARIZE, it treats the sequence var as a regular variable. If seqvar-handling is :INCLUDE, it returns it as a sequence var. Does the right thing for narts and assertions, but ignores the MT of the assertion. returns NIL if FORMULA is not a possibly-cycl-formula-p." (cond ((el-formula-p formula) (el-formula-terms formula seqvar-handling)) ((nart-p formula) (missing-larkc 10398)) ((assertion-p formula) (el-formula-terms (assertion-hl-formula formula))))) (defun* el-formula-terms (el-formula &optional (seqvar-handling :ignore)) (:inline t) "[Cyc] Returns a list of the terms in EL-FORMULA. If seqvar-handling is :IGNORE, it chops off the sequence var if there is one. If seqvar-handling is :REGULARIZE, it treats the sequence var as a regular variable. If seqvar-handling is :INCLUDE, it returns it as a sequence var." (formula-terms-int el-formula seqvar-handling)) (defun formula-terms-int (formula seqvar-handling &optional force-one-pass?) (if force-one-pass? (formula-terms-int-one-pass formula seqvar-handling) (formula-terms-int-two-pass formula seqvar-handling))) (defun formula-terms-int-two-pass (formula seqvar-handling) "[Cyc] Returns the terms of FORMULA. This version makes two passes if FORMULA has a sequence variable, but it avoids the consing done by VALUES in Allegro for formulas without sequence variables. Also it avoids cdr recursion." (cond ((formula-with-sequence-term? formula) (formula-terms-int-one-pass formula seqvar-handling)) ((consp formula) formula) (t (formula-terms-int-one-pass formula seqvar-handling)))) (defun formula-terms-int-one-pass (formula seqvar-handling) "[Cyc] Return 0: The terms of FORMULA. Return 1: Whether to cons. In the case of formula-args having the optional sequence var argument be :INCLUDE, we can simply use rest; in the case it is :IGNORE or :REGULARIZE, we could use a recursive internal function that recurses down the arg-list until a sequence var is encountered and, only if one is encountered conses the car (the arg) while unwinding; if no result is consed-up (e.g., no sequence var is found), it can simply return rest. No separate call to proper-list-p would be made. This would seem to minimize both consing and cdr'ing through the formula args. -ksm" (cond ((not formula) (values nil nil)) ((consp formula) (multiple-value-bind (subformula cons?) (formula-terms-int (rest formula) seqvar-handling t) (if cons? (values (cons (car formula) subformula) t) (values formula nil)))) ((cyc-var? formula) (case seqvar-handling (:ignore (values nil t)) (:regularize (values (list formula) t)) (:include (values formula nil)) (otherwise (values nil t)))) (t (el-error 3 "formula-terms-int got a non-el-variable or cons: ~a~%" formula) (values nil t)))) (defun* nat-args (nat &optional (seqvar-handling :ignore)) (:inline t) "[Cyc] Returns (as a list or a variable) the arguments of NAT. Returns NIL if NAT is not a nat. If seqvar-handling is :IGNORE, it chops off the sequence var if there is one. If seqvar-handling is :REGULARIZE, it treats the sequence var as a regular variable. If seqvar-handling is :INCLUDE, it returns it as a sequence var." (formula-args nat seqvar-handling)) (defun* nat-arg (nat n &optional (seqvar-handling :ignore)) (:inline t) "[Cyc] Return the argument in position N of non-atomic term NAT. If seqvar-handling is :IGNORE, it will return NIL if asked for the arg position where the sequence variable is. If seqvar-handling is :REGULARIZE, it will return the sequence variable if asked for its position. e.g. (nat-arg (<func> <arg1> . ?SEQ) 2 :IGNORE) -> NIL but (nat-arg (<func> <arg1> . ?SEQ) 2 :REGULARIZE) -> ?SEQ" (formula-arg nat n seqvar-handling)) (defun* nat-functor (nat) (:inline t) "[Cyc] Returns the functor of NAT. Returns NIL if NAT is not a nat." (nat-arg0 nat)) (defun* naut-functor (naut) (:inline t) "[Cyc] Returns the functor of NAUT." (el-formula-operator naut)) (defun nat-arg0 (nat) "[Cyc] Returns the 0th argument of NAT, which is by convention the functor. Returns NIL if NAT is not a nat." (cond ((el-formula-p nat) (naut-functor nat)) ((nart-p nat) (missing-larkc 10400)))) (defun* nat-arg1 (nat &optional (seqvar-handling :ignore)) (:inline t) "[Cyc] Returns the 1st argument of NAT. Returns NIL if NAT is not a nat." (nat-arg nat 1 seqvar-handling)) (defun* sentence-arg (sentence argnum &optional (seqvar-handling :ignore)) (:inline t) (formula-arg sentence argnum seqvar-handling)) (defun* sentence-args (sentence &optional (seqvar-handling :ignore)) (:inline t) (formula-args sentence seqvar-handling)) (defun* sentence-truth-function (sentence) (:inline t) (formula-arg0 sentence)) (defun* sentence-arg0 (sentence) (:inline t) (formula-arg0 sentence)) (defun* sentence-arg1 (asent &optional (seqvar-handling :ignore)) (:inline t) (formula-arg1 asent seqvar-handling)) (defun* sentence-arg2 (asent &optional (seqvar-handling :ignore)) (:inline t) (formula-arg2 asent seqvar-handling)) (defun* atomic-sentence-arg (asent argnum &optional (seqvar-handling :ignore)) (:inline t) (formula-arg asent argnum seqvar-handling)) (defun* atomic-sentence-args (asent &optional (seqvar-handling :ignore)) (:inline t) (formula-args asent seqvar-handling)) (defun* atomic-sentence-predicate (asent) (:inline t) (formula-arg0 asent)) (defun* atomic-sentence-arg1 (asent &optional (seqvar-handling :ignore)) (:inline t) (formula-arg1 asent seqvar-handling)) (defun* atomic-sentence-arg2 (asent &optional (seqvar-handling :ignore)) (:inline t) (formula-arg2 asent seqvar-handling)) (defun* atomic-sentence-arg3 (asent &optional (seqvar-handling :ignore)) (:inline t) (formula-arg3 asent seqvar-handling))
42,645
Common Lisp
.lisp
679
52.428571
555
0.663519
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
cb9599c36cb56fe36a8e98b63938fd1137464c698a0b6c87ce37b0b9ceffa353
6,739
[ -1 ]
6,740
set-utilities.lisp
white-flame_clyc/larkc-cycl/set-utilities.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun set-union (set-list &optional (test #'eql)) "Returns a new set that is the union of the sets in the given list." (cond ((null set-list) (new-set :test test)) ((singleton? set-list) (copy-set-contents (car set-list))) ;; TODO DESIGN - it could be better to copy the test of the 1st set, rather than having to remember to specify it. (t (let ((union (make-hash-table :test test))) (dolist (set set-list union) (dohash (key val set) (setf (gethash key union) val))))))) (defun set-intersection (set-list &optional (test #'eql)) (cond ((null set-list) (new-set :test test)) ((singleton? set-list) (copy-set-contents (car set-list))) (t (let* ((smallest (extremal set-list #'< #'set-contents-size)) (other-sets (remove smallest set-list)) (intersection (make-hash-table :test test))) (dohash (key val smallest) (declare (ignore val)) (when (every (lambda (set) (gethash key set)) other-sets) (setf (gethash key intersection) t))) intersection)))) (defun construct-set-from-list (list &optional (test #'eql) (size (length list))) "[Cyc] Returns a set-contents object constructed from the objects in LIST." (let ((set (make-hash-table :test test :size size))) (dolist (item list set) (setf (gethash item set) t)))) (defun set-add-all (elements set) (dolist (element elements set) (setf (gethash element set) t)))
2,881
Common Lisp
.lisp
57
45.368421
118
0.706576
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
5bf4ef6b469ca72f4f97e1aea1812a2e9a2daf502589be2b577dc61f9189de34
6,740
[ -1 ]
6,741
deduction-handles.lisp
white-flame_clyc/larkc-cycl/deduction-handles.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defglobal *deduction-from-id* nil "[Cyc] The ID -> DEDUCTION mapping table.") (defun* do-deductions-table () (:inline t) *deduction-from-id*) (defun setup-deduction-table (size exact?) (declare (ignore exact?)) (unless *deduction-from-id* (setf *deduction-from-id* (new-id-index size 0)))) (defun finalize-deductions (&optional max-deduction-id) (set-next-deduction-id max-deduction-id) (unless max-deduction-id (missing-larkc 30888))) (defun clear-deduction-table () (clear-id-index *deduction-from-id*)) (defun deduction-count () "[Cyc] Return the total number of deductions." (let ((index *deduction-from-id*)) (if index (id-index-count index) 0))) (defun* lookup-deduction (id) (:inline t) (id-index-lookup *deduction-from-id* id)) (defun set-next-deduction-id (&optional max-deduction-id) (let ((next-id (1+ (or max-deduction-id (let ((max -1)) (do-id-index (id deduction *deduction-from-id* :progress-message "Determining maximum deduction ID.") (setf max (max max id))) max))))) (set-id-index-next-id *deduction-from-id* next-id) next-id)) (defun register-deduction-id (deduction id) "[Cyc] Note that ID will eb used as the id for DEDUCTION." (reset-deduction-id deduction id) (id-index-enter *deduction-from-id* id deduction)) (defun deregister-deduction-id (id) "[Cyc] Note that ID is not in use as a deduction id." (id-index-remove *deduction-from-id* id)) (defun* make-deduction-id () (:inline t) "[Cyc] Return a new integer id for a deduction." (id-index-reserve *deduction-from-id*)) (defstruct (deduction (:conc-name "D-")) id) (defmethod sxhash ((object deduction)) (let ((id (d-id object))) (or id 786))) (defun* get-deduction () (:inline t) "[Cyc] Make a new deduction shell, potentially in static space." (make-deduction)) (defun free-deduction (deduction) "[Cyc] Invalidate DEDUCTION." (setf (d-id deduction) nil)) (defun valid-deduction-handle? (object) (and (deduction-p object) (deduction-handle-valid? object))) (defun* valid-deduction (deduction &optional robust?) (:inline t) (valid-deduction? deduction robust?)) (defun valid-deduction? (deduction &optional robust?) (if (valid-deduction-handle? deduction) (or (not robust?) (let ((supports (deduction-supports deduction))) (and (valid-support? (deduction-assertion deduction)) (consp supports) (every-in-list #'valid-support? supports)))))) (defun make-deduction-shell (&optional id) (unless id (setf id (make-deduction-id))) (let ((deduction (get-deduction))) (register-deduction-id deduction id) deduction)) (defun* create-sample-invalid-deduction () (:inline t) (get-deduction)) (defun free-all-deductions () (do-id-index (id deduction (do-deductions-table) :progress-message "Freeing deductions") (free-deduction deduction)) (clear-deduction-table) (clear-deduction-content-table)) (defun* deduction-id (deduction) (:inline t) "[Cyc] Return the id of DEDUCTION." (d-id deduction)) (defun reset-deduction-id (deduction new-id) "[Cyc] Primitively change the id of DEDUCTION to NEW-ID." (setf (d-id deduction) new-id)) (defun* deduction-valid-handle? (deduction) (:inline t) ;; TODO - original checked for integerp (d-id deduction)) (defun* find-deduction-by-id (id) (:inline t) (lookup-deduction id))
4,981
Common Lisp
.lisp
116
37.931034
98
0.698258
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
da10963cae01f5f2e165ed842e8e6201f4cafd046650cd23b9526c2b253d3abb
6,741
[ -1 ]
6,742
clause-utilities.lisp
white-flame_clyc/larkc-cycl/clause-utilities.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun nmake-clause (neg-lits pos-lits clause) "[Cyc] Destructively modify CLAUSE to have NEG-LITS and POS-LITS." ;; TODO - test eq before write (unless (eq neg-lits (neg-lits clause)) (setf (nth 0 clause) neg-lits)) (unless (eq pos-lits (pos-lits clause)) (setf (nth 1 clause) pos-lits)) clause) (defun* make-gaf-cnf (asent) (:inline t) "[Cyc] Return a new cnf constructed from the true gaf ASENT." (make-cnf nil (list asent))) (defun* nmake-dnf (neg-lits pos-lits dnf) (:inline t) "[Cyc] Destructively modify DNF to have NEG-LITS and POS-LITS, and return DNF itself." (nmake-clause neg-lits pos-lits dnf)) (defun clause-with-lit-counts-p (clause neg-lit-count pos-lit-count) "[Cyc] Return T iff CLAUSE is a clause with exactly NEG-LIT-COUNT neglits and exactly POS-LIT-COUNT poslits." (and (clause-p clause) (length= (neg-lits clause) neg-lit-count) (length= (pos-lits clause) pos-lit-count))) (defun pos-atomic-cnf-p (cnf) "[Cyc] Return T iff CNF is a cnf representation of an atomic formula with exactly one poslit and no neglits. This is much quicker to check than GAF-CNF?." (and (cnf-p cnf) (clause-with-lit-counts-p cnf 0 1))) (defun* pos-atomic-clause-p (clause) (:inline t) "[Cyc] Return T iff CLAUSE is a clause representation of an atomic formula with exactly one poslit and no neglits." (clause-with-lit-counts-p clause 0 1)) (defun* neg-atomic-clause-p (clause) (:inline t) "[Cyc] Return T iff CLAUSE is a clause representation of an atomic formula with exactly one neglit and no poslits." (clause-with-lit-counts-p clause 1 0)) (defun atomic-clause-with-all-var-args? (clause) "[Cyc] Return T iff CLAUSE is an atomic clause, and all of the arguments to its predicate are variables." (when (atomic-clause-p clause) (let* ((asent (atomic-clause-asent clause)) (asent-args (atomic-sentence-args asent))) (every-in-list #'cyc-var? asent-args)))) (defun* gaf-cnf-literal (cnf) (:inline t) (first (pos-lits cnf))) (defun atomic-cnf-asent (atomic-clause) "[Cyc] Returns the single pos-lit if it's a positive gaf cnf, or the single neg-lit if it's a negated gaf cnf." (if (pos-atomic-cnf-p atomic-clause) (first (pos-lits atomic-clause)) (first (neg-lits atomic-clause)))) (defun atomic-clause-asent (atomic-clause) "[Cyc] Returns the single pos-lit if it's a positive gaf clause, or the single neg-lit if it's a negated gaf clause." (if (pos-atomic-clause-p atomic-clause) (first (pos-lits atomic-clause)) (first (neg-lits atomic-clause)))) (defun atomic-cnf-predicate (atomic-clause) (atomic-sentence-predicate (atomic-cnf-asent atomic-clause))) (defun atomic-clauses-p (object) "[Cyc] Return T iff OBJECT is a singleton list containing one atomic-clause-p." (and (consp object) (singleton? object) (atomic-clause-p (first object)))) (defun pos-atomic-clauses-p (object) "[Cyc] Return T iff OBJECT is a singleton list containing one pos-atomic-clause-p." (and (consp object) (singleton? object) (pos-atomic-clause-p (first object)))) (defun* unmake-clause (clause) (:inline t) "[Cyc] Return 0: a list of the negative literals (neg-lits) in CLAUSE. Return 1: a list of the positive literals (pos-lits) in CLAUSE." (values (neg-lits clause) (pos-lits clause))) (defun* clause-number-of-literals (clause) (:inline t) "[Cyc] Returns the number of literals (both positive and negative) in CLAUSE." (clause-literal-count clause)) (defun clause-literal-count (clause) (+ (length (neg-lits clause)) (length (pos-lits clause)))) (defun binary-clause-p (clause) (= 2 (clause-number-of-literals clause))) (defun all-literals-as-asents (clause) (append (neg-lits clause) (pos-lits clause))) (defun clause-free-variables (clause &optional (var? #'cyc-var?) (include-sequence-vars? t)) (destructuring-bind (neg-lits pos-lits) clause (let ((bound nil)) (if (and (atomic-clause-p clause) (tou-lit? (first pos-lits))) (let ((*within-tou-gaf?* t)) (ordered-union (literals-free-variables neg-lits bound var? include-sequence-vars?) (literals-free-variables pos-lits bound var? include-sequence-vars?))) (ordered-union (literals-free-variables neg-lits bound var? include-sequence-vars?) (literals-free-variables pos-lits bound var? include-sequence-vars?)))))) (defun new-subclause-spec (negative-indices positive-indices) "[Cyc] Note: this could be memoized" (list (canonicalize-literal-indices negative-indices) (canonicalize-literal-indices positive-indices))) (defun new-single-literal-subclause-spec (sense index) (new-subclause-spec (when (eq sense :neg) (list index)) (when (eq sense :pos) (list index)))) (defun* ncanonicalize-literal-indices (indices) (:inline t) (sort indices #'<)) (defun* canonicalize-literal-indices (indices) (:inline t) (ncanonicalize-literal-indices (copy-list indices))) (defun new-complement-subclause-spec (subclause-spec sample-clause) (let ((neg-lit-count (length (neg-lits sample-clause))) (pos-lit-count (length (pos-lits sample-clause)))) (destructuring-bind (neg-indices pos-indices) subclause-spec (let ((complement-neg-indices nil) (complement-pos-indices nil)) (dotimes (neg-index neg-lit-count) (unless (member? neg-index neg-indices) (push neg-index complement-neg-indices))) (dotimes (pos-index pos-lit-count) (unless (member? pos-index pos-indices) (push pos-index complement-pos-indices))) (new-subclause-spec complement-neg-indices complement-pos-indices))))) (defstruct (subclause-spec (:type list)) negative-indices positive-indices) ;; Inlining since it seems sense is often given literally (declaim (notinline index-and-sense-match-subclause-spec?)) (defun index-and-sense-match-subclause-spec? (index sense subclause-spec) (member-eq? index (if (eq :neg sense) (subclause-spec-negative-indices subclause-spec) (subclause-spec-positive-indices subclause-spec)))) ;; DESIGN - Changed params to select between matching & not matching ;; Switched to neg-form and pos-form to be more direct, and avoid unreachable code warnings due to the testing that often happens. (defmacro do-subclause-spec* ((asent sense clause subclause-spec &optional invert?) &body (neg-form pos-form)) ;; Implementation taken from subclause-specified-by-spec ;; Iterates both the pos & neg lits (indicated by SENSE being :pos or :neg), ;; giving the INDEX into each list. ;; Clause & subclause-spec are values passed in. (let ((test (if invert? 'unless 'when))) (alexandria:with-gensyms (index) (alexandria:once-only (clause subclause-spec) `(progn (let ((,sense :neg)) (declare (ignorable sense)) (dolistn (,index ,asent (neg-lits ,clause)) ;; This is the slow dynamic part (,test (index-and-sense-match-subclause-spec? ,index :neg ,subclause-spec) ,neg-form))) (let ((,sense :pos)) (declare (ignorable sense)) (dolistn (,index ,asent (pos-lits ,clause)) ;; Again, slow dynamic part (,test (index-and-sense-match-subclause-spec? ,index :pos ,subclause-spec) ,pos-form)))))))) (defun subclause-specified-by-spec (clause subclause-spec) (let ((neg-lits nil) (pos-lits nil)) (do-subclause-spec* (asent sense clause subclause-spec) (push asent neg-lits) (push asent pos-lits)) (make-clause (nreverse neg-lits) (nreverse pos-lits)))) (defun complement-of-subclause-specified-by-spec (clause subclause-spec) (let ((neg-lits nil) (pos-lits nil)) (do-subclause-spec* (asent sense clause subclause-spec t) (push asent neg-lits) (push asent pos-lits)) (make-clause (nreverse neg-lits) (nreverse pos-lits)))) (defun subclause-spec-from-clauses (big-clause little-clause) (new-subclause-spec (literal-indices-from-literals (neg-lits big-clause) (neg-lits little-clause)) (literal-indices-from-literals (pos-lits big-clause) (pos-lits little-clause)))) (defun literal-indices-from-literals (big-lits little-lits) (loop for lit in little-lits collect (position lit big-lits :test #'equal))) (defun subclause-spec-literal-count (subclause-spec) (+ (length (subclause-spec-positive-indices subclause-spec)) (length (subclause-spec-negative-indices subclause-spec)))) (defun single-literal-subclause-spec? (subclause-spec) "[Cyc] Return T iff SUBCLAUSE-SPEC specifies a single literal." (= 1 (subclause-spec-literal-count subclause-spec)))
10,495
Common Lisp
.lisp
200
45.885
156
0.686975
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
01d701e41c47f8142dfcf35a15e350662288a3d74e1e6bafc8ce3b6401daa55f
6,742
[ -1 ]
6,743
mt-relevance-macros.lisp
white-flame_clyc/larkc-cycl/mt-relevance-macros.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defparameter *relevant-mt-function* nil) (defun* mt-function-eq (mt-function symbol) (:inline t) "[Cyc] Return T iff relevant-mt function MT-FUNCTION matches that specified by SYMBOL." (eq mt-function symbol)) (defun* relevant-mt-function-eq (symbol) (:inline t) "[Cyc] Return T iff the currently relevant mt-function matches that specified by SYMBOL" (mt-function-eq *relevant-mt-function* symbol)) (defparameter *mt* *assertible-theory-mt-root* "[Cyc] A ubiquitous parameter used to dynamically bind the current mt assumptions, if they can be expressed by a single mt.") (defparameter *relevant-mts* nil) (defun current-mt-relevance-mt () *mt*) (defun relevant-mt-is-everything (mt) (declare (ignore mt)) t) (defun relevant-mt-is-any-mt (mt) (declare (ignore mt)) t) (defun relevant-mt-is-eq (mt) (hlmt-equal *mt* mt)) (defun relevant-mt-is-genl-mt (mt) (or (eq mt *mt*) (let ((spec-core? (core-microtheory-p *mt*)) (genl-core? (core-microtheory-p mt))) (cond ((and spec-core? genl-core?) (core-genl-mt? mt *mt*)) (genl-core? t) (spec-core? nil) (t (basemt? *mt*)))))) (defun relevant-mt? (mt) "[Cyc] Return T iff MT is relevant with respect to the current dynamic mt scope." (let ((function *relevant-mt-function*)) (if (not function) (relevant-mt-is-genl-mt mt) (case function (relevant-mt-is-genl-mt (relevant-mt-is-genl-mt mt)) (relevant-mt-is-any-mt (relevant-mt-is-any-mt mt)) (relevant-mt-is-eq (relevant-mt-is-eq mt)) (relevant-mt-is-in-list (missing-larkc 31127)) (relevant-mt-is-genl-mt-of-list-member (missing-larkc 31125)) (relevant-mt-is-genl-mt-with-any-time (missing-larkc 31126)) ;; TODO - this is exactly the same as the above non-missing cases. If the missing functions get filled in, then this funcall can take over all cases. (otherwise (funcall function mt)))))) (defun genl-mts-are-relevant? () (or (not *relevant-mt-function*) (relevant-mt-function-eq 'relevant-mt-is-genl-mt))) (defun any-mt-is-relevant? () (relevant-mt-function-eq 'relevant-mt-is-any-mt)) (defun all-mts-are-relevant? () (relevant-mt-function-eq 'relevant-mt-is-everything)) (defun any-or-all-mts-are-relevant? () (or (relevant-mt-function-eq 'relevant-mt-is-everything) (relevant-mt-function-eq 'relevant-mt-is-any-mt))) (defun genl-mts-of-listed-mts-are-relevant? () (relevant-mt-function-eq 'relevant-mt-is-genl-mt-of-list-member)) (defun any-time-is-relevant? () (relevant-mt-function-eq 'relevant-mt-is-gnl-mt-with-any-time)) (defun only-specified-mt-is-relevant? () (relevant-mt-function-eq 'relevant-mt-is-eq)) (defun possibly-in-mt-determine-function (mt) (if (or (not mt) (with-inference-any-mt-relevance? mt) (with-inference-mt-relevance-all-mts? mt) (genl-mts-of-listed-mts-are-relevant?) (any-time-is-relevant?)) *relevant-mt-function* 'relevant-mt-is-genl-mt)) (defun* possibly-in-mt-determine-mt (mt) (:inline t) (or mt *mt*)) ;; Taken from kb-mapping-utilities, some-pred-value-in-relelvant-mts (defmacro possibly-in-mt ((mt) &body body) (once-only (mt) `(let ((*relevant-mt-function* (possibly-in-mt-determine-function ,mt)) (*mt* (possibly-in-mt-determine-mt ,mt))) ,@body))) (defun* possibly-with-just-mt-determine-function (mt) (:inline t) (if (not mt) *relevant-mt-function* #'relevant-mt-is-eq)) (defun* possibly-with-just-mt-determine-mt (mt) (:inline t) (or mt *mt*)) ;; Taken from many uses in kb-mapping, and inlined (defmacro possibly-with-just-mt ((mt) &body body) (once-only (mt) `(let ((*relevant-mt-function* (if ,mt *relevant-mt-function* #'relevant-mt-is-eq)) (*mt* (if ,mt ,mt *mt*))) ,@body))) (defun with-inference-mt-relevance-validate (mt) (or mt (error "No microtheory was specified."))) (defun update-inference-mt-relevance-mt (mt) (when mt (check-type mt 'hlmt-p)) (or mt *mt*)) (defun update-inference-mt-relevance-function (mt) (cond ((not mt) *relevant-mt-function*) ((with-inference-any-mt-relevance? mt) 'relevant-mt-is-any-mt) ((with-inference-mt-relevance-all-mts? mt) 'relevant-mt-is-everything) ((with-mt-union-relevance? mt) 'relevant-mt-is-genl-mt-of-list-member) ((with-inference-anytime-relevance? mt) 'relevant-mt-is-genl-mt-with-any-time) (t 'relevant-mt-is-genl-mt))) (defun update-inference-mt-relevance-mt-list (mt) (cond ((null mt) *relevant-mts*) ((with-mt-union-relevance? mt) (missing-larkc 12317)) (t nil))) (defun with-inference-any-mt-relevance? (mt) (eq 'psc-inference (mt-inference-function mt))) (defun with-inference-mt-relevance-all-mts? (mt) (eq 'all-mts-inference (mt-inference-function mt))) (defun with-mt-union-relevance? (mt) (eq 'mt-union-inference (mt-inference-function mt))) (defun with-inference-anytime-relevance? (mt) (eq 'anytime-psc-inference (mt-inference-function mt))) (defun inference-relevant-mt () "[Cyc] From the dynamic mt context, return an mt suitable for passing to WITH-INFERENCE-MT-RELEVANCE. Using thsi is usually preferable to referencing *MT* directly." (cond ((all-mts-are-relevant?) #$EverythingPSC) ((any-mt-is-relevant?) #$InferencePSC) ((genl-mts-of-listed-mts-are-relevant?) (make-formula #$MtUnionFn *relevant-mts*)) (t *mt*))) (defun mt-info (&optional mt) (cond ((all-mts-are-relevant?) #$EverythingPSC) ((any-mt-is-relevant?) #$InferencePSC) ((genl-mts-of-listed-mts-are-relevant?) (make-formula #$MtUnionFn *relevant-mts*)) (mt mt) (t *mt*))) (defun any-or-all-mts-relevant-to-mt? (mt) (or (with-inference-any-mt-relevance? mt) (with-inference-mt-relevance-all-mts? mt))) (defun conservative-constraint-mt (mt) "[Cyc] Assuming that relevance is being established from MT, and we are imposing a constraint about which we need to be conservative, return the mt in which we should look for such constraints." (if (any-or-all-mts-relevant-to-mt? mt) *core-mt-floor* mt)) (defun any-relevant-mt? (mts) (some #'relevant-mt? mts)) ;; Derived macros ;; TODO - this is likely still manually used everywhere, because it's small (defmacro with-all-mts (&body body) `(let ((*relevant-mt-function* #'relevant-mt-is-everything) (*mt* #$EverythingPSC)) ,@body)) ;; From kb-indexing, dependent-narts (defmacro with-inference-mt-relevance (mt &body body) "[Cyc] BODY evaluated with the same relevance used for inferences in MT. This is like WITH-GENL-MTS, except it is special-cased to WITH-ALL-MTS when the MT is #$EverythingPSC, WITH-ANY-MT when the MT is #$InferencePSC. Also, WITH-INFERENCE-MT-RELEVANCE errors if passed NIL for an MT." ;; TODO - verify that the docstring matches the functionality of these helper calls `(let ((mt-var (with-inference-mt-relevance-validate ,mt))) (let ((*mt* (update-inference-mt-relevance-mt mt-var)) (*relevant-mt-function* (update-inference-mt-relevance-function mt-var)) (*relevant-mts* (update-inference-mt-relevance-mt-list mt-var))) ,@body) ))
8,648
Common Lisp
.lisp
181
43.254144
287
0.7015
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
a1bec9a8132afc30514428419457b90f53527fa587ed02b4eeefdab76afc299b
6,743
[ -1 ]
6,744
gt-vars.lisp
white-flame_clyc/larkc-cycl/gt-vars.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; Building off the macro from at-vars.lisp (defmacro def-gt-state-var (name val &body (&optional docstring (definer 'defparameter))) `(def-state-var ,name ,val *at-state-variables* ,docstring ,definer)) (def-gt-state-var *gt-dispatch-table* '((:superiors gtm-superiors (fort &optional mt)) (:inferiors gtm-inferiors (fort &optional mt)) (:min-superiors gtm-min-superiors (fort &optional mt)) (:max-inferiors gtm-max-inferiors (fort &optional mt)) (:co-inferiors gtm-co-inferiors (fort &optional mt)) (:co-superiors gtm-co-superiors (fort &optional mt)) (:redundant-superiors gtm-redundant-superiors (fort &optional mt)) (:redundant-inferiors gtm-redundant-inferiors (fort &optional mt)) (:all-superiors gtm-all-superiors (fort &optional mt)) (:all-inferiors gtm-all-inferiors (fort &optional mt)) (:all-accessible gtm-all-accessible (fort &optional mt)) (:union-all-inferiors gtm-union-all-inferiors (fort &optional mt)) (:compose-fn-superiors gtm-compose-fn-all-superiors (fort fn &optional (combine-fn 'nconc) mt)) (:compose-fn-inferiors gtm-compose-fn-all-inferiors (fort fn &optional (combine-fn 'nconc) mt)) (:all-dependent-inferiors gtm-all-dependent-inferiors (fort &optional mt)) (:compose-pred-superiors gtm-compose-pred-all-superiors (fort pred &optional (index 1) (gather 2) mt)) (:compose-pred-inferiors gtm-compose-pred-all-inferiors (fort pred &optional (index 1) (gather 2) mt)) (:roots gtm-roots (fort &optional mt)) (:leaves gtm-leaves (fort &optional mt)) (:boolean? gtm-boolean? (arg1 arg2 &optional mt)) (:superior? gtm-superior? (superior inferior &optional mt)) (:inferior? gtm-inferior? (inferior superior &optional mt)) (:has-superior? gtm-has-superior? (inferior superior &optional mt)) (:has-inferior? gtm-has-inferior? (superior inferior &optional mt)) (:gather-superior gtm-gather-superior (spec gather-fn &optional mt)) (:gather-inferior gtm-gather-inferior (genl gather-fn &optional mt)) (:cycles? gtm-cycles? (fort &optional mt)) (:completes-cycle? gtm-completes-cycle? (fort-1 fort-2 &optional mt)) (:min-nodes gtm-min-nodes (forts &optional mt)) (:max-nodes gtm-max-nodes (forts &optional mt)) (:min-ceilings gtm-min-ceilings (forts &optional candidates mt)) (:max-floors gtm-max-floors (forts &optional candidates mt)) (:min-superiors-excluding gtm-min-superiors-excluding (inferior superior &optional mt)) (:max-inferiors-excluding gtm-max-inferiors-excluding (superior inferior &optional mt)) (:any-superior-path gtm-any-superior-path (inferior superior &optional mt)) (:why-superior? gtm-why-superior? (superior inferior &optional mt)) (:why-completes-cycle? gtm-why-completes-cycle? (fort1 fort2 &optional mt)) (:all-superior-edges gtm-all-superior-edges (inferior superior &optional mt)) (:all-inferior-edges gtm-all-inferior-edges (inferior superior &optional mt)) (:all-paths gtm-all-paths (inferior superior &optional mt)) (:inferiors-with-mts gtm-all-inferiors-with-mts (superior)) (:superior-in-what-mts gtm-in-what-mts (inferior superior key-method)) (:inferior-in-what-mts gtm-in-what-mts (superior inferior key-method)) (:accessible-in-what-mts gtm-accessible-in-what-mts (inferior superior key-method))) "[Cyc] Table used to dispatch gt methods as actual calls on gt executables." deflexical) (def-gt-state-var *gt-methods* (mapcar #'car *gt-dispatch-table*) "[Cyc] Candidate methods for gt modules.") (def-gt-state-var *gt-parameters* (append '(:predicate :index-arg :gather-arg :accessors :mt) *gt-methods*) "[Cyc] Candidate parameters for gt methods.") (def-gt-state-var *transitivity-modules* nil "[Cyc] All cyc modules defined using the general transitivity module.") (def-gt-state-var *gt-pred* nil "[Cyc] Transitive predicate used for current gt query.") (def-gt-state-var *gt-index* nil "[Cyc] Arg used as initial index for current gt query.") (def-gt-state-var *gt-gather* nil "[Cyc] Arg used as initial gather (e.g., search target) for current gt query.") (def-gt-state-var *gt-index-arg* 1 "[Cyc] Indexing arg position used for current gt query.") (def-gt-state-var *gt-gather-arg* 2 "[Cyc] Gathering arg position used for current gt query.") (def-gt-state-var *gt-accessors* nil "[Cyc] Accessors used for current gt query.") (def-gt-state-var *gt-link-type* :assertion "[Cyc] Type of links used in gt module.") (def-gt-state-var *gt-mode* :superior "[Cyc] Mode (e.g., direction) of search during gt query.") (def-gt-state-var *gt-modes* (list :superior :inferior :accessible :directed :inverse) "[Cyc] Candidate modes for gt search.") (def-gt-state-var *gt-truth* :true "[Cyc] Truth relevant to the current gt query [:true :false].") (def-gt-state-var *gt-query* nil "[Cyc] Literal denoting query formula of current gt query.") (def-gt-state-var *gt-done?* nil "[Cyc] Terminate the current gt search?") (def-gt-state-var *gt-searched?* nil "[Cyc] Current gt search path encountered searched nodes.") (def-gt-state-var *gt-target* nil "[Cyc] Target of current gt search.") (def-gt-state-var *gt-result* nil "[Cyc] Accumlates results of current gt query.") (def-gt-state-var *gt-searcher* nil "[Cyc] Current searcher during multiple-searcher gt search.") (def-gt-state-var *gt-base-fn* nil "[Cyc] Fn applied to each candidate node during gt search.") (def-gt-state-var *gt-step-fn* nil "[Cyc] Fn used to step from one node to another during gt closure search.") (def-gt-state-var *gt-compose-fn* nil "[Cyc] Fn applied to each accessed node during composing gt search.") (def-gt-state-var *gt-gather-fn* nil "[Cyc] Fn applied to each accessed node durung a gather gt search.") (def-gt-state-var *gt-combine-fn* #'nconc "[Cyc] Fn used to combine results of composing fn applied to each accessed node.") (def-gt-state-var *gt-compare-fn* nil "[Cyc] Test used to compare each accessed node with target during gt search.") (def-gt-state-var *gt-equality-fn* #'equal "[Cyc] Equality test used to remove duplicates from non-fort results during gt search.") (def-gt-state-var *gt-compose-pred* nil "[Cyc] Composing predicate used for current composing gt query.") (def-gt-state-var *gt-compose-index-arg* 1 "[Cyc] Indexing arg position used for composing pred in current gt query.") (def-gt-state-var *gt-compose-gather-arg* 2 "[Cyc] Gathering arg position used for composing pred in current gt query.") (def-gt-state-var *gt-max-nodes-direction* :down "[Cyc] Default search direction when computing gt-max-nodes.") (def-gt-state-var *gt-use-spec-preds?* t "[Cyc] Use spec preds during gt searches?") (def-gt-state-var *gt-handle-non-transitive-predicate?* nil "[Cyc] Make gt modules applicable to non-transitive predicates?") ;; This one is plain without the state var registration (defparameter *gt-link-support* nil "[Cyc] The current link assertion or hl support.") (def-gt-state-var *gt-what-mts-result* nil "[Cyc] Result holder for what-mts.") (def-gt-state-var *gt-what-mts-goal-node* nil "[Cyc] Goal node of in-what-mt searches.") (def-gt-state-var *gt-path-list-of-mts* nil "[Cyc] List of mts along current path.") (def-gt-state-var *gt-path-list-of-nodes* nil "[Cyc] Path list of nodes, accumulated to guard against cycles.") (def-gt-state-var *gt-path-length* 0 "[Cyc] Length of current mt path.") (def-gt-state-var *gt-list-of-path-lengths* nil "[Cyc] List of path lengths in order.") (def-gt-state-var *gt-marking-table* nil "[Cyc] The hash table where we do the marking (usually dynamic).") (def-gt-state-var *gt-target-marking-table* nil "[Cyc] Used for the occasional nested search.") (def-gt-state-var *gt-depth-cutoff* 1 "[Cyc] Depth cutoff for the search.") (def-gt-state-var *gt-depth-cutoff?* nil "[Cyc] Flag for whether or not to use depth cutoff.") (def-gt-state-var *gt-prev-depth-cutoff* 1 "[Cyc] What the previous depth cutoff was, used for iterive deepening.") (def-gt-state-var *gt-time-cutoff?* nil "[Cyc] Flag for whether or not to use time cutoff.") (def-gt-state-var *gt-time-cutoff* 10 "[Cyc] Time cutoff, in seconds, for the search.") (def-gt-state-var *gt-initial-time* 0 "[Cyc] When did the timing begin?") (def-gt-state-var *gt-answers-cutoff?* nil "[Cyc] Flag for whether or not to use number of answers cutoff.") (def-gt-state-var *gt-answers-cutoff* 1 "[Cyc] Number of answers after which we are done searching.") (def-gt-state-var *gt-answers-so-far* 0 "[Cyc] Accumulator for number of answers so far.") (def-gt-state-var *gt-goal-node* nil "[Cyc] Goal node.") (def-gt-state-var *gt-edge-list* nil "[Cyc] List of edges along search, for graphing.") (def-gt-state-var *gt-edge-list-return?* nil "[Cyc] Are we gather edge lists?") (def-gt-state-var *gt-path-list-of-assertions* nil "[Cyc] List of assertions along search. for graphing.") (def-gt-state-var *gt-cyclical-edges* nil "[Cyc] List of pairs (a b), where a is the node in the search upon which the cycle was discovered, and b is the edge list of a cycle it belongs to.") (def-gt-state-var *gt-trace-level* 1 "[Cyc] Controls extent of tracing, warnings, etc., for the general transitivity module [0 .. 5].") (def-gt-state-var *gt-test-level* 3 "[Cyc] Controls extent of testing for the general transitivity module [0 .. 5].") (def-gt-state-var *suspend-gt-type-checking?* nil "[Cyc] Skip type checking during gt queries?") (def-gt-state-var *gt-warnings* nil "[Cyc] Warnings from transitiviy module; possible values: :invalid-module :invalid-method.") (def-gt-state-var *tt-dispatch-table* '((:all-targets ttm-all-targets (fort &optional mt)) (:all-sources ttm-all-sources (fort &optional mt)) (:boolean? ttm-boolean? (fort term &optional mt)) (:accesses-in-what-mts ttm-accesses-in-what-mts (fort term))) "[Cyc] Table used to dispatch tt methods as actual calls on tt executables.") (def-gt-state-var *tt-methods* (mapcar #'car *tt-dispatch-table*) "[Cyc] Candidate methods for gt modules.") (def-gt-state-var *transfers-through-modules* nil "[Cyc] All cyc modules defined using the general transfers-through module.") (def-gt-state-var *tt-parameters* (append (list :predicate :conduit-pred :tt-index-arg :tt-gather-arg :gt-index-arg :gt-gather-arg :mt) *tt-methods*) "[Cyc] Candidate parameters for tt methods.") (def-gt-state-var *tt-pred* nil "[Cyc] Transitive predicate used for current tt query.") (def-gt-state-var *tt-index* nil "[Cyc] Arg used as initial index for current tt query.") (def-gt-state-var *tt-gather* nil "[Cyc] Arg used as initial gather (e.g., search target) for current tt query.") (def-gt-state-var *tt-index-arg* 1 "[Cyc] Indexing arg position used for current tt query.") (def-gt-state-var *tt-gather-arg* 2 "[Cyc] Gathering arg position used for current tt query.") (def-gt-state-var *tt-truth* :true "[Cyc] Truth relevant to the current gt query [:true :false].") (def-gt-state-var *tt-step-fn* nil "[Cyc] Fn used to step from one node to another during tt search.") (def-gt-state-var *tt-transitive-conduit?* nil "[Cyc] Is conduit-arg transitive in current tt search?") (def-gt-state-var *gt-transitive-via-arg-active?* t "[Cyc] Is the gt-transitive-via-arg module active?") (def-gt-state-var *gt-within-transitive-via-arg?* nil "[Cyc] Currently within scope of a gt-transitive-via-arg module?")
13,703
Common Lisp
.lisp
243
50.078189
151
0.682887
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
163b2a5ae294494cea6aa28f78caea29b288a91b83f9e1668f32a5aa4173661a
6,744
[ -1 ]
6,745
constant-completion-low.lisp
white-flame_clyc/larkc-cycl/constant-completion-low.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defglobal *constant-completion-table* (create-trie t "Constant Completion Table") "[Cyc] Table for indexing constants by the string for their name.") (defparameter *require-valid-constants* t) (defun constant-shell-from-name (string) "[Cyc] Return a constant or constant shell whose name exactly matches STRING." (declare (string string)) (trie-exact *constant-completion-table* string t 0 nil)) (defun kb-constant-complete-exact-internal (string start end) (let ((answer (trie-exact *constant-completion-table* string t start end))) (unless (and (constant-p answer) *require-valid-constants* (not (valid-constant-handle-p answer))) answer))) (defun kb-constant-complete-internal (prefix case-sensitive? exact-length? start end) (let ((answer (trie-prefix *constant-completion-table* prefix case-sensitive? exact-length? start end))) (if *require-valid-constants* (delete-if #'invalid-constant-handle answer) answer))) (defun add-constant-to-completions (constant string) "[Cyc] Add CONSTANT to the completions table under the name STRING." (declare (constant constant) (string string)) (trie-insert *constant-completion-table* string constant) constant) (defun remove-constant-from-completions (constant string) (declare (constant constant) (string string)) (trie-remove *constant-completion-table* string constant) constant) (defun kb-new-constant-completion-iterator-internal (&optional (forward? t)) (new-trie-iterator *constant-completion-table* forward?))
2,981
Common Lisp
.lisp
58
47.155172
106
0.757345
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
ff7292d19bfc51f581622e21f2443266a9221036ae0f1c4475f7d963275246e3
6,745
[ -1 ]
6,746
cycl-variables.lisp
white-flame_clyc/larkc-cycl/cycl-variables.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defconstant *el-variable-prefix-char* #\? "[Cyc] The character used as the first character of an EL variable's name.") (defconstant *el-variable-prefix-string* (string *el-variable-prefix-char*) "[Cyc] The string used as the first character of an EL variable's name.") (defconstant *el-variable-hyphen-char* #\- "[Cyc] The character used as the hyphen character in an EL variable's name.") (defconstant *el-variable-invalid-hyphen-sequence* "--" "[Cyc] The string which is deemed as an invalid hyphen sequence in an EL variable's name.") (defconstant *valid-el-var-regular-expression* "([?]|[?][?]) [A-Z] ([A-Z]|[0-9])* ([-] ([A-Z]|[0-9])+)*" "[Cyc] The current filter for valid EL variable name in regular expression format.") (defun* el-variable-prefix-char () (:inline t) "[Cyc] Returns the character used as teh first character of an EL variable's name." *el-variable-prefix-char*) (defun* el-variable-prefix-char? (object) (:inline t) "[Cyc] Returns T if OBJECT is the character used as the first character of an EL variable's name." (char= object (el-variable-prefix-char))) (defun* has-el-variable-prefix? (string) (:inline t) "[Cyc] Returns T if STRING begins with ?. STRING assumed to be stringp." ;; TODO - will crash if string is "" (el-variable-prefix-char? (char string 0))) (defun* has-dont-care-var-prefix? (string) (:inline t) "[Cyc] Returns T if STRING begins with ??. STRING assumed to be stringp." (and (el-variable-prefix-char? (char string 0)) (el-variable-prefix-char? (char string 1)))) (defun el-var? (object) "[Cyc] Return T iff OBJECT is a symbol which can be interpreted as an EL variable." (and (symbolp object) object (not (keywordp object)) (el-var-name? (el-var-name object)))) (defun* el-var-name (el-var) (:inline t) "[Cyc] The name of EL-VAR. Includes the prefix character." (symbol-name el-var)) (defun el-var-name? (object) (and (stringp object) (length> object 1) (has-el-variable-prefix? object))) (defun* make-el-var (object) (:inline t) (intern-el-var object)) (defun make-el-var-name (object) (if (el-var-name? object) (string-upcase object) (missing-larkc 31891))) ;; TODO - add a ? to the end of this name (defun invalid-variable-name-char (object) "[Cyc] Returns T if OBJECT is a character which could not possibly be a valid character in an EL variable name." (and (not (upper-case-alphanumeric-p object)) (missing-larkc 31890))) (defun valid-el-var? (object) "[Cyc] Returns T if OBJECT is a symbol whose name satisfies the regular expression *VALID-EL-VAR-REGULAR-EXPRESSION*." (and (symbolp object) (not (keywordp object)) (valid-el-var-name? (el-var-name object)))) (defun valid-el-var-name? (object) "[Cyc] Returns T if OBJECT satisfies the regular expression *VALID-EL-VAR-REGULAR-EXPRESSION*." ;; TODO - I bet there was a macroexpansion from the regex to this? (unless (or (not (stringp object)) (empty-string-p object) (not (has-el-variable-prefix? object))) (let* ((length (length object)) (last (1- length)) (subseq-check-start 1)) (when (has-dont-care-var-prefix? object) (setf subseq-check-start 2)) (when (<= last subseq-check-start) (setf last (1+ subseq-check-start))) (when (valid-el-variable-name-subsequence? (subseq object subseq-check-start last)) (upper-case-alphanumeric-p (char object (1- length))))))) (defun valid-el-variable-name-subsequence? (object) (and (length> object 0) (upper-case-p (char object 0)) (not (find-if #'invalid-variable-name-char (subseq object 1))) (not (search (invalid-hyphen-sequence) object)))) (defun* invalid-hyphen-sequence () (:inline t) *el-variable-invalid-hyphen-sequence*) (defun* intern-el-var (object) (:inline t) (intern (make-el-var-name object) *cyc-package*)) (defconstant *keyword-variable-prefix-char* #\: "[Cyc] The character used as the first character of a keyword variable's name.") (defun* permissible-keyword-var? (thing) (:inline t) "[Cyc] Return T iff THING is deemed a keyword variable, and we are allowing such things." (and *permit-keyword-variables?* (keywordp thing))) (defun* keyword-var? (thing) (:inline t) "[Cyc] Return T iff THING is deemed a keyword variable." (keywordp thing)) (defun variable-name (var) "[Cyc] Returns the name of the CycL variable VAR. Does not strip prefix characters." (cond ((variable-p var) (variable-name (default-el-var-for-hl-var var))) ((el-var? var) (el-var-name var)) ;; TODO - this should be easy? I guess concat a colon, or just format ~s ((keyword-var? var) (missing-larkc 31895)) ;; TODO - probably just format ~s (t (missing-larkc 7491)))) (defun cyc-var? (thing) "[Cyc] Returns T iff THING is any possible kind of variable in the CycL language or any of its extensions or relata, being as permissive as possible." (or (el-var? thing) (kb-var? thing) (tl-var? thing) (permissible-keyword-var? thing) (generic-arg-var? thing))) (defun generic-arg-var? (thing) "[Cyc] Return T iff THING is deemed a generic-arg variable." (declare (ignore thing)) (and *permit-generic-arg-variables* (missing-larkc 3473))) (defun variable-predicate-fn (var) "[Cyc] Return the SubL boolean function that admits VAR as a variable." (cond ((hl-var? var) #'hl-var?) ((el-var? var) #'el-var?) ((tl-var? var) #'tl-var?) ((permissible-keyword-var? var) #'keyword-var?) ((generic-arg-var? var) #'generic-arg-var?) (t #'false))) (defun* kb-var? (symbol) (:inline t) (kb-variable? symbol)) (defun* kb-variable? (symbol) (:inline t) (variable-p symbol)) (defun* hl-var? (thing) (:inline t) (variable-p thing))
7,247
Common Lisp
.lisp
149
44.516779
152
0.70061
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
093079175b41bfe3ab1be4b9218f94b9831d434f5ad716bb1caf6855478ef6a8
6,746
[ -1 ]
6,747
constant-completion-interface.lisp
white-flame_clyc/larkc-cycl/constant-completion-interface.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun kb-constant-complete-exact (string &optional (start 0) (end (length string))) "[Cyc] Return a valid constant whose name exactly matches STRING. Optionally the START and END character positions can be specified, such that the STRING matches the characters between the START and END range. If no constant exists, return NIL." (if (hl-access-remote?) (missing-larkc 29536) (kb-constant-complete-exact-internal string start end))) (defun kb-constant-complete (prefix &optional case-sensitive? exact-length? (start 0) (end (length prefix))) "[Cyc] Return all valid constants with PREFIX as a prefix of their name. When CASE-SENSITIVE? is non-NIL, the comparison is done in a case-sensitive fashion. When EXACT-LENGTH? is non-NIL, the prefix must be the entire string. Optionally the START and END character positions can be specified, such that the PREFIX matches characters between the START and END range. If no constant exists, return NIL." (if (hl-access-remote?) (missing-larkc 29537) (kb-constant-complete-internal prefix case-sensitive? exact-length? start end))) (defun kb-new-constant-completion-iterator (&optional (forward? t) (buffer-size 1)) "[Cyc] Returns an iterator for the constants in the constant completion table." (new-hl-store-iterator (list 'kb-new-constant-completion-iterator-internal (quotify forward?)) buffer-size))
2,805
Common Lisp
.lisp
47
55.93617
143
0.769568
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
7d4be411e733ced84ca74ea25139f4366a62d824685a54011da5ac32b93c5fe8
6,747
[ -1 ]
6,748
system-info.lisp
white-flame_clyc/larkc-cycl/system-info.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (deflexical *cyc-home-directory* #P"./" "[Cyc] The pathname for the cyc home directory (suitable for use with MERGE-PATHNAMES)") (defglobal *available-cyc-features* nil) ;; Check for feature, that will always be nil? (defun cyc-opencyc-feature () nil) (defun cyc-revision-string () "[Cyc] Returns the current Cyc revision numbers expressed as a period-delimited string" *cyc-revision-string*) (defun cyc-revision-numbers () "[Cyc] Returns a list of the current Cyc revision numbers" *cyc-revision-numbers*) (defglobal *cycl-start-time* nil) (defun reset-cycl-start-time (&optional (universal-time (get-universal-time))) (setf *cycl-start-time* universal-time)) (defglobal *subl-initial-continuation* nil "[Cyc] Backpointer for the original SubL initial continuation.")
2,190
Common Lisp
.lisp
44
46.704545
90
0.774941
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
1a0d25064a4d9f832e1060a6b0d0751fe2a252a2439985f623f902e2efb5614b
6,748
[ -1 ]
6,749
cfasl-utilities.lisp
white-flame_clyc/larkc-cycl/cfasl-utilities.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun cfasl-load (filename) "[Cyc] Return the first object saved in FILENAME in CFASL format." (with-open-file (stream filename :element-type '(unsigned-byte 8)) (cfasl-input stream)))
1,590
Common Lisp
.lisp
31
47.903226
77
0.777489
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
7e13222bfd75f37ed76dbef4227f7a71ab0480801fe28b597d46cf4428229d32
6,749
[ -1 ]
6,750
kb-accessors.lisp
white-flame_clyc/larkc-cycl/kb-accessors.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO - a lot of integerp tests around argnums, probably could be fixnum instead, as well as type declarations. (defun* relation? (relation) (:inline t) "[Cyc] Return T iff RELATION is a relationship." (relation-p relation)) (defun* irreflexive-predicate? (predicate) (:inline t) "[Cyc] Return T iff PREDICATE is an irreflexive predicate." (irreflexive-binary-predicate-p predicate)) (defun* asymmetric-predicate? (predicate) (:inline t) "[Cyc] Return T iff PREDICATE is an asymmetric predicate." (asymmetric-binary-predicate-p predicate)) (defun result-isa (functor &optional mt) "[Cyc] Return a list of the collections that include as instances the results of non-predicate function constant FUNCTOR." (cond ((fort-p functor) (pred-values-in-relevant-mts functor #$resultIsa mt)) ((naut-with-corresponding-nart? functor) (result-isa (find-nart functor) mt)) ((reifiable-nat? functor #'cyc-var? mt) (meta-result-isa (nat-functor functor) mt)) ((function-to-arg-term? functor) (argn-isa (nat-arg2 functor) (nat-arg1 functor) mt)))) (defun function-to-arg-term? (term) (and (consp term) (eql #$FunctionToArg (nat-functor term)))) (defun meta-result-isa (meta-functor &optional mt) "[Cyc] META-FUNCTOR is the functor of a function-denoting function; return the resultIsa collections inherited to instances of the resultIsa of META-FUNCTOR." (cond ((fort-p meta-functor) (let ((meta-result-isa nil)) (let ((*mapping-fn* #'pred-arg-values-in-relevant-mts) (*mapping-fn-arg* 1) (*mapping-fn-arg2* #$relationAllInstance) (*mapping-fn-arg3* #$resultIsa) (*mapping-fn-arg4* mt) (*mapping-fn-arg5* 2) (*mapping-fn-arg6* 1) ;; TODO - are these memory allocation spaces? remove them? (*sbhl-space* (get-sbhl-marking-space)) (*sbhl-gather-space* (get-sbhl-marking-space)) (*sbhl-suspend-new-spaces?* t)) (dolist (result-isa (result-isa meta-functor mt)) (setf meta-result-isa (nconc meta-result-isa (gather-all-genls #'mapping-funcall-arg result-isa mt))))) meta-result-isa)) ((naut-with-corresponding-nart? meta-functor) (meta-result-isa (find-nart meta-functor) mt)))) (defun* anti-symmetric-predicate? (predicate) (:inline t) "[Cyc] Return T iff PREDICATE is an anti-symmetric predicate." (anti-symmetric-binary-predicate-p predicate)) (defun* transitive-predicate? (predicate) (:inline t) "[Cyc] Return T iff PREDICATE is a transitive predicate." (transitive-binary-predicate-p predicate)) (defun* anti-transitive-predicate? (predicate) (:inline t) "[Cyc} Return T iff PREDICATE is an anti-transitive predicate." (anti-transitive-binary-predicate-p predicate)) (defun binary-predicate? (predicate) "[Cyc] Return T iff PREDICATE is a predicate of arity 2." (and (predicate-p predicate) (eql (arity predicate) 2))) (defun admitting-defns? (col &optional mt) (or (sufficient-defns? col mt) (defining-defns? col mt))) (defun* sufficient-defns? (col &optional mt) (:inline t) (some-pred-value-in-relevant-mts col #$defnSufficient mt)) (defun* necessary-defns? (col &optional mt) (:inline t) (some-pred-value-in-relevant-mts col #$defnNecessary mt)) (defun* defining-defns? (col &optional mt) (:inline t) (some-pred-value-in-relevant-mts col #$defnIff mt)) (defun* cyclist? (term) (:inline t) "[Cyc] Return T iff TERM is an instance of #$Cyclist somewhere." (isa-in-any-mt? term #$Cyclist)) (defun decontextualized-predicate? (predicate) "[Cyc] Return T iff PREDICATE is decontextualized, i.e. it can be thought of as having its complete extent in all mts." (some-pred-value-in-relevant-mts predicate #$decontextualizedPredicate *decontextualized-predicate-mt*)) (defun predicate-convention-mt (predicate) (or (fpred-value-in-any-mt predicate #$predicateConventionMt) *default-convention-mt*)) (defun decontextualized-collection? (collection) "[Cyc] Return T iff COLLECTION is decontextualized, i.e. it can be thought of as having its complete collection extent in all mts." (some-pred-value-in-relevant-mts collection #$decontextualizedCollection *decontextualized-collection-mt*)) (defun collection-convention-mt (collection) (or (fpred-value-in-any-mt collection #$collectionConventionMt) *default-convention-mt*)) (defun decontextualized-literal? (literal) (when (el-formula-p literal) (let ((predicate (literal-predicate literal))) (and (fort-p predicate) (or (decontextualized-predicate? predicate) (decontextualized-collection-literal? literal)))))) (defun decontextualized-literal-convention-mt (literal) (if (decontextualized-collection-literal? literal) (collection-convention-mt (sentence-arg2 (literal-atomic-sentence literal))) (predicate-convention-mt (literal-predicate literal)))) (defun decontextualized-collection-literal? (literal) (when (el-binary-formula-p literal) (let ((predicate (literal-predicate literal)) (arg2 (literal-arg2 literal))) (and (or (eql #$isa predicate) (eql #$genls predicate)) (fort-p arg2) (decontextualized-collection? arg2))))) (defun decontextualized-atomic-cnf? (cnf) (when (atomic-clause-p cnf) (let ((asent (atomic-cnf-asent cnf))) (decontextualized-literal? asent)))) (defparameter *decontextualized-weakening-prohibited?* t "[Cyc] Temporary control variable: When non-nil, we don't decontextualize to a lower microtheory from a strictly higher one.") (defun* decontextualized-weakening-prohibited? () (:inline t) *decontextualized-weakening-prohibited?*) (defun mt-matches-convention-mt? (given-mt convention-mt) (or (eq given-mt convention-mt) (hlmt-equal? given-mt convention-mt) (and (decontextualized-weakening-prohibited?) (proper-genl-mt? convention-mt given-mt)))) (defun possibly-convention-mt-for-decontextualized-cnf (mt cnf) (block nil (when (decontextualized-atomic-cnf? cnf) (let* ((asent (atomic-cnf-asent cnf)) (convention-mt (decontextualized-literal-convention-mt asent))) (when (and convention-mt (not (mt-matches-convention-mt? mt convention-mt))) (return convention-mt)))) mt)) (defun quoted-argument? (relation argnum) "[Cyc] Return T iff arg number ARGNUM of RELATION is quoted via #$quotedArgument." (and (fort-p relation) (numberp argnum) (> argnum 0) (pred-u-v-holds-in-any-mt #$quotedArgnument relation argnum))) (defun complete-extent-asserted-gaf (predicate &optional mt) "[Cyc] If PREDICATE's extent has been completely asserted, returns an assertion justifying this claim." (and (some-pred-assertion-somewhere? #$completeExtentAsserted predicate 1) (fpred-value-gaf-in-relevant-mts predicate #$completeExtentAsserted mt))) (defun complete-extent-asserted-for-value-in-arg-gaf (predicate value argnum &optional mt) "[Cyc] If PREDICATE's curried extent is completely asserted once VALUE is its ARGNUMth argument, returns an assertion justifying this claim." (declare (ignore mt)) ;; likely in missing-larkc (when (some-pred-assertion-somewhere? #$completeExtentAssertedForValueInArg predicate 1) (let ((asent (make-ternary-formula #$completeExtentAssertedForValueInArg predicate value argnum))) (declare (ignore asent)) (missing-larkc 12717)))) (defun complete-extent-enumerable-gaf (predicate &optional mt) "[Cyc] If PREDICATE's extent can be completely enumerated, returns an assertion justifying this claim." (when (some-pred-assertion-somewhere? #$completeExtentEnumerable predicate 1) (fpred-value-gaf-in-relevant-mts predicate #$completeExtentEnumerable mt))) (defun complete-extent-decidable-gaf (predicate &optional mt) "[Cyc] If PREDICATE's extent can be completely decided, returns an assertion justifying this claim." (when (some-pred-assertion-somewhere? #$completeExtentDecidable predicate 1) (fpred-value-gaf-in-relevant-mts predicate #$completeExtentDecidable mt))) (defun complete-extent-enumerable-for-arg-gaf (predicate argnum &optional mt) "[Cyc] If PREDICATE's curried extent is enumerable once its ARGNUMth argument is fixed, returns an assertion justifying this claim." (declare (ignore argnum mt)) (when (some-pred-assertion-somewhere? #$completeExtentEnumerableForArg predicate 1) (missing-larkc 30008))) (defun complete-extent-enumerable-for-value-in-arg-gaf (predicate value argnum &optional mt) "[Cyc] If PREDICATE's curried extent is enumerable once VALUE is its ARGNUMth argument, returns an assertion justifying this claim." (declare (ignore mt)) (when (some-pred-assertion-somewhere? #$completeExtentEnumerableForValueInArg predicate 1) (let ((asent (make-ternary-formula #$completeExtentEnumerableForValueInArg predicate value argnum))) (declare (ignore asent)) (missing-larkc 12718)))) (defun complete-extent-decidable-for-value-in-arg-gaf (predicate value argnum &optional mt) "[Cyc] If PREDICATE's curried extent is decidable once VALUE is its ARGNUMth argument, returns an ssertion justifying this claim." (declare (ignore mt)) (when (some-pred-assertion-somewhere? #$completeExtentDecidableForValueInArg predicate 1) (let ((asent (make-ternary-formula #$completeExtentDecidableForValueInArg predicate value argnum))) (declare (ignore asent)) (missing-larkc 12719)))) (defun* completely-enumerable-collection? (collection &optional mt) (:inline t) "[Cyc] Return whether COLLECTION is completely enumerable in MT." (completely-enumerable-collection-gaf collection mt)) (defun completely-enumerable-collection-gaf (collection mt) (and (fort-p collection) (fpred-value-gaf-in-relevant-mts collection #$completelyEnumerableCollection mt))) (defun* backchain-required? (predicate mt) (:inline t) (some-pred-value-in-relevant-mts predicate #$backchainRequired mt)) (defun* backchain-forbidden (predicate &optional mt) (:inline t) (some-pred-value-in-relevant-mts predicate #$backchainForbidden mt)) (defun* collection-isa-backchain-required? (collection &optional mt) (:inline t) (some-pred-value-in-relevant-mts collection #$collectionIsaBackchainRequired mt)) (defun* collection-genls-backchain-required? (collection &optional mt) (:inline t) (some-pred-value-in-relevant-mts collection #$collectionGenlsBackchainRequired mt)) (defun* collection-backchain-required? (collection &optional mt) (:inline t) (some-pred-value-in-relevant-mts collection #$collectionBackchainRequired mt)) (defun skolemize-forward-somewhere? (function) (and (fort-p function) (some-pred-assertion-somewhere? #$skolemizeForward function 1))) (defun skolemize-forward? (function &optional mt) (and (fort-p function) (skolemize-forward-somewhere? function) (some-pred-value-in-relevant-mts function #$skolemizeForward mt))) (defun forward-reification-rule? (function rule &optional mt) (when (and (fort-p function) (rule-assertion? rule)) ;; TODO - mt macro (let ((*mt* (update-inference-mt-relevance-mt mt)) (*relevant-mt-function* (update-inference-mt-relevance-function mt)) (*relevant-mts* (update-inference-mt-relevance-mt-list mt))) (pred-u-v-holds #$forwardReificationRule function rule 1 2)))) (defun arg-and-rest-isa-min-argnum (relation &optional mt) "[Cyc] Returns the smallest integer in an #$argAndRestIsa gaf constraining RELN if one exists, otherwise returns NIL." (let ((result nil)) (when (some-arg-and-rest-isa-assertion-somewhere? relation) (dolist (argnum (pred-values-in-relevant-mts relation #$argAndRestIsa mt)) (when (integerp argnum) (when (or (not result) (< argnum result)) (setf result argnum))))) result)) (defun arg-and-rest-isa-applicable? (reln argnum &optional mt) "[Cyc] Returns T iff ARGNUM of RELN is constrained via #$argAndRestIsa" (let ((min-argnum (arg-and-rest-isa-min-argnum reln mt))) (and (integerp min-argnum) (>= argnum min-argnum)))) (defun arg-and-rest-quoted-isa-min-argnum (relation &optional mt) "[Cyc] Returns the smallest integer in an #$argAndRestQuotedIsa gaf constraining RELN if one exists, otherwise returns NIL." (let ((result nil)) (dolist (argnum (pred-values-in-relevant-mts relation #$argAndRestQuotedIsa mt)) (cond ((not (integerp argnum)) nil) ((not result) (setf result argnum)) ((< argnum result) (setf result argnum)))) result)) (defun arg-and-rest-quoted-isa-applicable? (reln argnum &optional mt) "[Cyc] Returns T iff ARGNUM of RELN is constrained via #$argAndRestIsa." (let ((min-argnum (arg-and-rest-quoted-isa-min-argnum reln mt))) (and (integerp min-argnum) (>= argnum min-argnum)))) (defun* argn-isa (relation argnum &optional mt) (:inline t) "[Cyc] Returns a list of the local isa constraints applied to the ARGNUMth argument of RELATION (#$argsIsa conjoins with #$arg1Isa et al)." (argn-isa-int relation argnum mt)) (defun argn-quoted-isa (relation argnum &optional mt) "[Cyc] Returns a list of the local isa constraints applied to the ARGNUMth argument of RELATION (#$argsIsa conjoins with #$arg1Isa et al)." (if (within-czer-memoization-state?) (copy-list (czer-argn-quoted-isa-int relation argnum (mt-info mt))) (argn-quoted-isa-int relation argnum mt))) (defun argn-isa-int (relation argnum mt) (cond ((fort-p relation) (argn-isa-int-2 relation argnum mt)) ((reifiable-nat? relation #'cyc-var? mt) (missing-larkc 10348)))) (defun argn-isa-int-2 (relation argnum mt) (let ((result nil)) (when (some-args-isa-assertion-somewhere? relation) (setf result (nconc result (pred-values-in-relevant-mts relation #$argsIsa mt)))) (when (some-arg-and-rest-isa-assertion-somewhere? relation) (missing-larkc 6808)) (when (positive-integer-p argnum) (setf result (nconc result (if-let ((arg-isa-pred (arg-isa-pred-int argnum))) (cached-arg-isas-in-mt relation argnum mt) (pred-values-in-relevant-mts relation arg-isa-pred mt))))) (delete-duplicate-forts result))) (defun argn-quoted-isa-int (relation argnum mt) (cond ((fort-p relation) (cond ;; TODO - do these need to be freshly consed lists? can we use literal lists with #$ ? ((cyc-const-logical-operator-p relation) (list #$CyclSentence-Assertible)) ((and (cyc-const-quantifier-p relation) (= argnum (quantified-sub-sentence-argnum-for-operator relation))) (list #$CyclSentence-Assertible)) ((cyc-const-quantifier-p relation) (missing-larkc 30632)) (t (let ((result nil)) (dolist (arg-quoted-isa-pred (arg-quoted-isa-preds argnum relation mt)) (cond ((member? arg-quoted-isa-pred *arg-quoted-isa-binary-preds*) (setf result (nconc result (pred-values-in-relevant-mts relation arg-quoted-isa-pred mt)))) ((member? arg-quoted-isa-pred *arg-quoted-isa-ternary-preds*) (missing-larkc 6814)) ((isa? arg-quoted-isa-pred #$ArgQuotedIsaBinaryPredicate) (setf result (nconc result (pred-values-in-relevant-mts relation arg-quoted-isa-pred mt)))) ((isa? arg-quoted-isa-pred #$ArgQuotedIsaTernaryPredicate) (missing-larkc 6815)) (t (el-error 3 "Illegal arg-quoted-isa-pred encountered in argn-isa: ~s" arg-quoted-isa-pred)))) (remove-duplicate-forts result))))) ((reifiable-nat? relation #'cyc-var? mt) (missing-larkc 10349)))) (defun arg-isa-pred-int (index) ;; TODO - convert to a bounds-checked array lookup, instead of this junk (case index (1 #$arg1Isa) (2 #$arg2Isa) (3 #$arg3Isa) (4 #$arg4Isa) (5 #$arg5Isa) (6 #$arg6Isa) (0 #$argsIsa) (otherwise (el-error 3 "Illegal index specification for arg-isa-pred: ~s" index)))) (defun arg-isa-pred (index &optional reln mt) "[Cyc] Returns the appropriate predicate for constraining the INDEXth argument of RELN." (cond (reln (let ((argnum (arg-and-rest-isa-min-argnum reln mt))) (if (integerp argnum) (if (>= index argnum) #$argAndRestIsa (arg-isa-pred-int index)) (if (variable-arity? reln) #$argsIsa (arg-isa-pred-int index))))) ((valid-argnum-p index) (arg-isa-pred-int index)) (t (el-error 3 "Illegal index specification for arg-isa-pred: ~s" index)))) (defun arg-isa-preds (argnum &optional reln mt) "[Cyc] Returns the appropriate predicates for constraining the INDEXth argument of RELN." (cond ((valid-argnum-p argnum) (let ((result nil)) (when-let ((var (arg-isa-pred-int argnum))) (push var result)) (pushnew #$argsIsa result) (when (and (fort-p reln) (arg-and-rest-isa-applicable? reln argnum mt)) (push #$argAndRestIsa result)) (nreverse result))) (t (el-error 3 "Illegal argnum specification for arg-isa-preds: ~s" argnum)))) (defun arg-quoted-isa-pred-int (index) ;; TODO - convert to a bounds-checked array lookup, instead of this junk (case index (1 #$arg1QuotedIsa) (2 #$arg2QuotedIsa) (3 #$arg3QuotedIsa) (4 #$arg4QuotedIsa) (5 #$arg5QuotedIsa) (6 #$arg6QuotedIsa) (t (el-error 3 "Illegal index specification for arg-quoted-isa-pred: ~s" index)))) (defun arg-quoted-isa-pred (index &optional reln mt) "[Cyc] Returns the appropriate predicate for constraining the INDEXth argument of RELN." (cond (reln (let ((argnum (arg-and-rest-quoted-isa-min-argnum reln mt))) (if (integerp argnum) (if (>= index argnum) #$argAndRestQuotedIsa (arg-quoted-isa-pred-int index)) (if (variable-arity? reln) #$argsQuotedIsa (arg-quoted-isa-pred-int index))))) ((valid-argnum-p index) (arg-quoted-isa-pred-int index)) (t (el-error 3 "Illegal index specification for arg-quoted-isa-pred: ~s" index)))) (defun arg-quoted-isa-preds (argnum &optional reln mt) "[Cyc] Returns the appropriate predicates for constraining the INDEXth argument of RELN." (cond ((valid-argnum-p argnum) (let ((result nil)) (when-let ((var (arg-quoted-isa-pred-int argnum))) (push var result)) (pushnew #$argsQuotedIsa result) (when (and (fort-p reln) (arg-and-rest-quoted-isa-applicable? reln argnum mt)) (push #$argAndRestQuotedIsa result)) (nreverse result))) (t (el-error 3 "Illegal argnum specification for arg-quoted-isa-preds: ~s" argnum)))) (defun arg-isa-inverse (index &optional reln mt) "[Cyc] Returns the appropriate predicate for constraining the inverse of the INDEXth argument of RELN." (case index (1 (arg-isa-pred 2 reln mt)) (2 (arg-isa-pred 1 reln mt)))) (defun arg-quoted-isa-inverse (index &optional reln mt) "[Cyc] Returns the appropriate predicate for constraining the inverse of the INDEXth argument of RELN." (case index (1 (arg-quoted-isa-pred 2 reln mt)) (2 (arg-quoted-isa-pred 1 reln mt)))) (defun inverse-argnum (argnum) "[Cyc] Return the inverse argnum of ARGNUM." (case argnum (1 2) (2 1) (otherwise (error "Invalid argument to inverse-argnum: ~s" argnum)))) (defun isa-pred-arg (isa-pred) "[Cyc] Return the arg constrained by ISA-PRED (e.g., (isa-pred-arg #$arg1Isa) -> 1) By convention (isa-pred-arg #$argsIsa) -> 0." ;; TODO - ensure that the constants are manifesting properly here, because CASE doesn't evaluate its test terms (case isa-pred (#$arg1Isa 1) (#$arg2Isa 2) (#$arg3Isa 3) (#$arg4Isa 4) (#$arg5Isa 5) (#$arg6Isa 6) (#$arg0Isa 0))) (defun argn-genl (relation argnum &optional mt) "[Cyc] Returns the local genl constraints applied to the ARGNUMth argument of RELATION." (cond ((fort-p relation) (let ((result nil)) (dolist (arg-genl-pred (arg-genl-preds argnum relation mt)) (cond ((member? arg-genl-pred *arg-genl-binary-preds*) (setf result (nconc result (pred-values-in-relevant-mts relation arg-genl-pred mt)))) ((member? arg-genl-pred *arg-genl-ternary-preds*) (missing-larkc 6803)) ((isa? arg-genl-pred #$ArgGenlBinaryPredicate) (setf result (nconc result (pred-values-in-relevant-mts relation arg-genl-pred mt)))) ((isa? arg-genl-pred #$ArgGenlTermaryPredicate) (missing-larkc 6804)) (t (el-error 3 "Illegal arg-genl-pred encountered in argn-genl: ~s" arg-genl-pred)))) (remove-duplicate-forts result))) ((reifiable-nat? relation #'cyc-var? mt) (missing-larkc 10350)))) (defun arg-and-rest-genl-min-argnum (relation &optional mt) "[Cyc] Returns the smallest integer in an #$argAndRestGenl gaf constraining RELN if one exists, otherwise returns NIL." (let ((result nil)) (dolist (argnum (pred-values-in-relevant-mts relation #$argAndRestGenl mt)) (cond ((not (integerp argnum)) ;; do nothing ) ((not result) (setf result argnum)) ((< argnum result) (setf result argnum)))) result)) (defun arg-and-rest-genl-applicable? (reln argnum &optional mt) "[Cyc] Returns T iff ARGNUM of RELN is constrained via #$argAndRestGenl." (let ((min-argnum (arg-and-rest-genl-min-argnum reln mt))) (and (integerp min-argnum) (>= argnum min-argnum)))) (defun arg-genl-pred-int (index) ;; TODO - convert to bounds-checked array lookup (case index (1 #$arg1Genl) (2 #$arg2Genl) (3 #$arg3Genl) (4 #$arg4Genl) (5 #$arg5Genl) (6 #$arg6Genl) (0 #$argsGenl) (otherwise (el-error 3 "Illegal index specification for arg-genl-pred: ~s" index)))) (defun arg-genl-pred (index &optional reln mt) "[Cyc] Returns the appropriate predicate for constraining the INDEXth argument of RELN." (cond (reln (let ((argnum (arg-and-rest-genl-min-argnum reln mt))) (if (integerp argnum) (if (>= index argnum) #$argAndRestGenl (arg-genl-pred-int index)) (if (variable-arity? reln) #$argsGenl (arg-genl-pred-int index))))) ((valid-argnum-p index) (arg-genl-pred-int index)) (t (el-error 3 "Illegal index specification for arg-genl-pred: ~s" index)))) (defun arg-genl-preds (argnum &optional reln mt) "[Cyc] Returns the appropriate predicates for constraining the ARGNUMth argument of RELN." (cond ((valid-argnum-p argnum) (let ((result nil)) (when-let ((var (arg-genl-pred-int argnum))) (push var result)) (pushnew #$argsGenl result) (when (and (fort-p reln) (arg-and-rest-genl-applicable? reln argnum mt)) (push #$argAndRestGenl result)) (nreverse result))) (t (el-error 3 "Illegal argnum specification for arg-genl-preds: ~s" argnum)))) (defun arg-genl-inverse (index &optional reln mt) "[Cyc] Returns the appropriate predicate for constraining the inverse of the INDEXth argument of RELN." (case index (1 (arg-genl-pred 2 reln mt)) (2 (arg-genl-pred 1 reln mt)))) (defun argn-format-inverse (n) "[Cyc] Returns the appropriate arg-format predicate for constraining the inverse of N." (case n (1 (argn-format-pred 2)) (2 (argn-format-pred 1)))) (defun argn-format-pred (n) ;; TODO - convert to bounds-checked array (case n (1 #$arg1Format) (2 #$arg2Format) (3 #$arg3Format) (4 #$arg4Format) (5 #$arg5Format) (6 #$arg6Format) (otherwise (el-error 3 "Illegal arg specification for argn-format-pred: ~s" n)))) (defun inter-arg-format-pred (ind-arg dep-arg) (let ((ind-candidates (inter-arg-format-preds-ind ind-arg)) (dep-candidates (inter-arg-format-preds-dep dep-arg)) (pred nil)) ;; TODO - return-from would be simpler & faster (csome (candidate ind-candidates pred) (when (member? candidate dep-candidates) (setf pred candidate))) pred)) (defun inter-arg-format-preds-dep (arg) ;; TODO - convert to bounds-checked array (case arg (1 '(#$interArgFormat2-1 #$interArgFormat3-1 #$interArgFormat4-1 #$interArgFormat5-1)) (2 '(#$interArgFormat1-2 #$interArgFormat3-2 #$interArgFormat4-2 #$interArgFormat5-2)) (3 '(#$interArgFormat1-3 #$interArgFormat2-3 #$interArgFormat4-3 #$interArgFormat5-3)) (4 '(#$interArgFormat1-4 #$interArgFormat2-4 #$interArgFormat3-4 #$interArgFormat5-4)) (5 '(#$interArgFormat1-5 #$interArgFormat2-5 #$interArgFormat3-5 #$interArgFormat4-5)))) (defun inter-arg-format-preds-ind (arg) ;; TODO - convert to bounds-checked array (case arg (1 '(#$interArgFormat1-2 #$interArgFormat1-3 #$interArgFormat1-4 #$interArgFormat1-5)) (2 '(#$interArgFormat2-1 #$interArgFormat2-3 #$interArgFormat2-4 #$interArgFormat2-5)) (3 '(#$interArgFormat3-1 #$interArgFormat3-2 #$interArgFormat3-4 #$interArgFormat3-5)) (4 '(#$interArgFormat4-1 #$interArgFormat4-2 #$interArgFormat4-3 #$interArgFormat4-5)) (5 '(#$interArgFormat5-1 #$interArgFormat5-2 #$interArgFormat5-3 #$interArgFormat5-4)))) (defun fan-out-arg (pred &optional mt) "[Cyc] Which arg is the #$fanOutArg for hierarchically transitive PRED." (or (asserted-fan-out-arg pred mt) 1)) (defun asserted-fan-out-arg (pred &optional mt) "[Cyc] Return which arg is asserted to be the #$fanOutArg for hierarchically transitive PRED, or NIL." (fpred-value-in-relevant-mts pred #$fanOutArg mt)) (defun assertion-still-there? (assertion truth) (some (lambda (argument) (eq truth (argument-truth argument))) (assertion-arguments assertion))) (defun scoping-args (relation &optional mt) (when (and (fort-p relation) (some-scoping-arg-somewhere? relation)) (pred-values-in-relevant-mts relation #$scopingArg mt))) (defun some-scoping-arg-somewhere? (relation) (some-pred-assertion-somewhere? #$scopingArg relation 1)) (defun all-term-assertions (term &optional remove-duplicates?) "[Cyc] Return a list of all the assertions indexed via the indexed term TERM." (term-assertions term #$InferencePSC remove-duplicates?)) (defun term-assertions (term &optional mt remove-duplicates?) (with-inference-mt-relevance mt (gather-index term remove-duplicates?))) (defun not-assertible-predicate? (pred &optional mt) (if (fort-p pred) (some-pred-value-in-relevant-mts pred #$notAssertible mt) (not (reifiable-nat? pred #'cyc-var? mt)))) (defun not-assertible-collection? (collection &optional mt) (when (fort-p collection) (some-pred-value-in-relevant-mts collection #$notAssertibleCollection mt))) (defun not-assertible-mt? (mt) (let ((reduced-mt (canonicalize-hlmt mt))) (when (and (fort-p reduced-mt) (possibly-mt-p reduced-mt)) (some-pred-value-in-any-mt reduced-mt #$notAssertibleMt)))) (deflexical *common-non-skolem-indeterminate-term-denoting-functions* '(#$RelationAllExistsFn #$RelationExistsAllFn #$RelationInstanceExistsFn #$RelationExistsInstanceFn) "[Cyc] Functions commonly known to denote non-skolem indeterminate terms.") (defun common-non-skolem-indeterminate-term-denoting-function? (object) (member-eq? object *common-non-skolem-indeterminate-term-denoting-functions*)) (defun non-skolem-indeterminate-term-denoting-function? (object) (and (fort-p object) (function? object) (skolem-function-p object) (isa? object #$IndeterminateTermDenotingFunction))) (defun fast-non-skolem-indeterminate-term? (term) "[Cyc] Will sometimes return false negatives." (cond ((or (variable-p term) (cycl-unrepresented-term-p term)) nil) ((and (el-formula-p term) (common-non-skolem-indeterminate-term-denoting-function? (formula-operator term))) t) ((and (el-formula-p term) (non-skolem-indeterminate-term-denoting-function? (formula-operator term))) t))) (defparameter *smallest-num-index-so-far* nil) (defparameter *most-specialized-fort-so-far* nil)
31,173
Common Lisp
.lisp
569
46.525483
160
0.66788
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
8f1fb315dbcefcc9cfe85e93a819077c6c8a325b71c19dae85f67fca070e00d0
6,750
[ -1 ]
6,751
number-utilities.lisp
white-flame_clyc/larkc-cycl/number-utilities.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; A ton of these functions are very simplistic. I wonder if they're used to pass around as lambdas. Else, it's a lot easier to just type out their effects than remember which fiddly bits are in here under what name. (defun* 2* (number) (:inline t) "[Cyc] Return (* NUMBER 2)." (* 2 number)) (defun* onep (object) (:inline t) "[Cyc] Return T iff OBJECT is 1." (eql 1 object)) (defun* encode-boolean (object) (:inline t) "[Cyc] Convert any object to either 1 or 0." (if object 1 0)) (defun* decode-boolean (integer) (:inline t) "[Cyc] Convert 1 or 0 to T or NIL." (not (eq 0 integer))) (defun* get-bit (bits bit-number) (:inline t) "[Cyc] Return the boolean value encoded in BIT-NUMBER of BITS." (declare (fixnum bits bit-number)) (decode-boolean (ldb (byte 1 bit-number) bits))) (defun* set-bit (bits bit-number &optional (boolean t)) (:inline t) (declare (fixnum bits bit-number)) (dpb (encode-boolean boolean) (byte 1 bit-number) bits)) ;; TODO - are things doing speedup checks that would take advantage of this being larger? (deflexical *large-immediate-positive-integer* (ash 1 26) "[Cyc] A large positive integer guaranteed to be stored immediately.") (defconstant *e* 2.718281828459045d0 "[Cyc] exp1, what a silly name for e.") (defun* bytep (object) (:inline t) (typep object '(integer 0 255))) (defun* zero-number-p (object) (:inline t) "[Cyc] Like ZEROP, but doesn't error on non-numbers." (or (eq object 0) (eql object 0.0d0))) ;; TODO - not defconstant? are we going to have dynamically updated fp formats? (deflexical *maximum-float-significant-digits* 16 "[Cyc] The maximum possible number of significant digits for a floating-point number.") (defun significant-digits (number digits) (declare (fixnum digits)) (cond ((infinite-number-p number) number) ((scientific-number-p number) (missing-larkc 690)) ((zerop number) 0) ((minusp number) (significant-digits (- number) digits)) ((and (integerp number) (>= digits (missing-larkc 31687))) number) ((and (doublep number) (>= digits *maximum-float-significant-digits*)) number) (t (let* ((normalization-power (floor (log number 10))) (normalization-ratio (expt 10 normalization-power)) (normalized-number (/ number normalization-ratio)) (significant-ratio (expt 10 (1- digits))) (scaled-normalized (* normalized-number significant-ratio)) (scaled-significant (round scaled-normalized)) (normalized-significant (/ scaled-significant significant-ratio)) (significant (* normalized-significant normalization-ratio))) (when (integerp number) (let* ((unnormalization-power (- normalization-power (1- digits))) (unnormalization-ratio (expt 10 unnormalization-power))) (setf significant (* scaled-significant unnormalization-ratio)))) (when (and (doublep significant) (>= number most-negative-fixnum) (<= number most-positive-fixnum)) (let ((nearest-integer (round significant))) ;; TODO - what is this doing, casting a double to an integer? (when (= nearest-integer significant) (setf significant nearest-integer)))) (if (doublep significant) (significant-digits-optimize-float significant) significant))))) (defun significant-digits-optimize-float (float) (multiple-value-bind (significand exponent sign) (integer-decode-float float) (let ((tersest-length most-positive-fixnum) (tersest-float nil)) (loop for delta from 2 below 3 do (let* ((candidate-significand (+ significand delta)) (candidate-float (* sign (scale-float (float candidate-significand) exponent))) (candidate-length (length (prin1-to-string candidate-float)))) (when (< candidate-length tersest-length) (setf tersest-length candidate-length) (setf tersest-float candidate-float)))) tersest-float))) (defun* percent (numerator &optional (denominator 1) significant-digits) (:inline t) "[Cyc] Express NUMERATOR/DENOMINATOR as a percent. The answer is limited to SIGNIFICANT-DIGITS, when non-NIL." (let ((result (* 100 (/ numerator denominator)))) (if significant-digits (significant-digits result significant-digits) result))) ;; TODO DESIGN - SBCL does support infinite numbers in sb-ext:, including math operators, numeric comparisons, and predicates. The serialization process, however, would need to be extended to support it, if these are ever asserted. It's a tossup which way to go, but I'm hoping that the potentially-infinite-* functions aren't the norm and thus these manual implementations won't have too much of a burden. ;; TODO - instrument or deprecate these to measure their presence. (defun* potentially-infinite-number-p (object) (:inline t) (or (numberp object) (infinite-number-p object))) (defun* positive-infinity () (:inline t) :positive-infinity) (defun* negative-infinity-p (object) (:inline t) (eq object :negative-infinity)) (defun* positive-infinity-p (object) (:inline t) (eq object :positive-infinity)) (defun* infinite-number-p (object) (:inline t) (or (negative-infinity-p object) (positive-infinity-p object))) (defun* potentially-infinite-number-= (num1 num2) (:inline t) (eql num1 num2)) (defun potentially-infinite-number-< (num1 num2) (cond ((negative-infinity-p num1) (not (negative-infinity-p num2))) ((negative-infinity-p num2) nil) ((positive-infinity-p num2) (not (positive-infinity-p num1))) ((positive-infinity-p num1) nil) (t (< num1 num2)))) (defun* potentially-infinite-number-> (num1 num2) (:inline t) (not (potentially-infinite-number-< num1 num2))) (defun potentially-infinite-number-plus (num1 num2) (cond ;; TODO - this missing-larkc is missing. Maybe fallout from there not being a negative-infinity function? ((negative-infinity-p num1) (missing-larkc 31726)) ((negative-infinity-p num2) (missing-larkc 31727)) ((positive-infinity-p num1) (missing-larkc 31742)) ((positive-infinity-p num2) (missing-larkc 31743)) (t (+ num1 num2)))) (defun potentially-infinite-number-times (num1 num2) (cond ((negative-infinity-p num1) (missing-larkc 31728)) ((negative-infinity-p num2) (missing-larkc 31729)) ((positive-infinity-p num1) (missing-larkc 31744)) ((positive-infinity-p num2) (missing-larkc 31745)) (t (* num1 num2)))) (defun potentially-infinite-number-divided-by (num1 num2) ;; Not sure if this is intended to return 2 values (cond ;; This hits a missing-larkc on infinite stuff before it has the opportunity to check div-by-zero ((zero-number-p num2) (missing-larkc 31731)) ((negative-infinity-p num1) (missing-larkc 31723)) ((negative-infinity-p num2) (missing-larkc 31688)) ((positive-infinity-p num1) (missing-larkc 31739)) ((positive-infinity-p num2) (missing-larkc 31689)) (t (/ num1 num2)))) (defun* potentially-infinite-number-max (num1 num2) (:inline t) "[Cyc] Returns the potentially-infinite-number-p max value between NUM1 and NUM2." (if (potentially-infinite-number-> num1 num2) num1 num2)) (defun* potentially-infinite-number-min (num1 num2) (:inline t) "[Cyc] Returns the potentially-infinite-number-p min value between NUM1 and NUM2." (if (potentially-infinite-number-< num1 num2) num1 num2)) (defun* potentially-infinite-integer-= (int1 int2) (:inline t) (eql int1 int2)) (defun* potentially-infinite-integer-< (int1 int2) (:inline t) (potentially-infinite-number-< int1 int2)) (defun* potentially-infinite-integer-> (int1 int2) (:inline t) (potentially-infinite-integer-< int2 int1)) (defun* potentially-infinite-integer-<= (int1 int2) (:inline t) (not (potentially-infinite-integer-> int1 int2))) (defun* potentially-infinite-integer-plus (int1 int2) (:inline t) (potentially-infinite-number-plus int1 int2)) (defun* potentially-infinite-integer-times (int1 int2) (:inline t) (potentially-infinite-number-times int1 int2)) ;; Cool, SBCL detects the infinite number paths as unreachable from the -times and -divided routines. (defun potentially-infinite-integer-times-number-rounded (int1 num2) "[Cyc] A truncated version of (INT1 * NUM2)." (let ((raw-product (potentially-infinite-number-times int1 num2))) (if (infinite-number-p raw-product) raw-product (truncate raw-product)))) (defun potentially-infinite-integer-divided-by-number-rounded (int1 num2) "[Cyc] A truncated version of (INT1 / NUM2)." (let ((raw-product (potentially-infinite-number-divided-by int1 num2))) (if (infinite-number-p raw-product) raw-product (truncate raw-product)))) (defun maximum (items &optional (key #'identity)) "[Cyc] Returns the maximal element of ITEMS. KEY: A unary function that will return a NUMBERP when applied to any item in ITEMS." (must (consp items) "Cannot compute the maximum of an atom or empty list.") (if (or (eq key #'identity) (eq key 'identity)) (let ((maximum (car items))) (dolist (item (cdr items) maximum) (when (> item maximum) (setf maximum item)))) (extremal items #'> key))) (defun median (items &optional key) "[Cyc] If KEY is provided, and ITEMS are non-numeric, then ITEMS must be of odd length." (must (consp items) "Cannot compute the median of an atom or empty list.") (let ((sorted-items (if key (sort (copy-list items) #'< :key key) (sort (copy-list items) #'<)))) (median-sorted sorted-items))) (defun median-sorted (items &optional length) "[Cyc] This will simply access the middle of the list of items or average the two middle items in the case of an evenp length." (must (consp items) "Cannot compute the median of an atom or empty list") (unless length (setf length (length items))) (let ((middle-position (floor length 2))) (if (oddp length) (nth middle-position items) (/ (+ (nth middle-position items) (nth (- middle-position 1) items)) 2)))) (defun decode-integer-multiples (integer multiples) (declare (integer integer) (list multiples)) (let ((answer nil)) (dolist (multiple multiples) (when (zerop integer) (unless answer (push integer answer)) (return)) (multiple-value-bind (whole mod) (truncate integer multiple) (push mod answer) (setf integer whole))) (nreverse answer))) ;; TODO - not constants? (deflexical *valid-number-string-characters* "0123456789.-+deDE") (deflexical *valid-exponent-markers* "deDE") (deflexical *valid-sign* "+-") (defconstant *largest-prime-by-binary-width* '((2 . 3) (3 . 7) (4 . 13) (5 . 31) (6 . 61) (7 . 127) (8 . 251) (9 . 509) (10 . 1021) (11 . 2039) (12 . 4093) (13 . 8191) (14 . 16381) (15 . 32749) (16 . 65521) (17 . 131071) (18 . 262139) (19 . 524287) (20 . 1048573) (21 . 2097143) (22 . 4194301) (23 . 8388593) (24 . 16777213) (25 . 33554393) (26 . 67108859) (27 . 134217689) (28 . 268435399) (29 . 536870909) (30 . 1073741789) (31 . 2147483647) (32 . 4294967291) (33 . 8589934583) (34 . 17179869143) (35 . 34359738337) (36 . 68719476731) (37 . 137438953447) (38 . 274877906899) (39 . 549755813881) (40 . 1099511627689) (41 . 2199023255531) (42 . 4398046511093) (43 . 8796093022151) (44 . 17592186044399) (45 . 35184372088777) (46 . 70368744177643) (47 . 140737488355213) (48 . 281474976710597) (49 . 562949953421231) (50 . 1125899906842597) (51 . 2251799813685119) (52 . 4503599627370449) (53 . 9007199254740881) (54 . 18014398509481951) (55 . 36028797018963913) (56 . 72057594037927931) (57 . 144115188075855859) (58 . 288230376151711717) (59 . 576460752303423433) (60 . 1152921504606846883) (61 . 2305843009213693951) (62 . 4611686018427387847) (63 . 9223372036854775783) (64 . 18446744073709551557))) (defconstant *checksum-implementation-width* (truncate (log (abs most-negative-fixnum) 2)) "[Cyc] How many bits the high and the low part represent.") (defconstant *checksum-base* (cdr (assoc *checksum-implementation-width* *largest-prime-by-binary-width*)) "[Cyc] Largest prime smaller than 2^implementation-width.") (defconstant *checksum-initial-value-sum* 1) (defconstant *checksum-initial-value-length* 0) (defparameter *checksum-sum* 1) (defparameter *checksum-length* 0) (defparameter *hex-to-dec-table* '((#\a 10) (#\A 10) (#\b 11) (#\B 11) (#\c 12) (#\C 12) (#\d 13) (#\D 13) (#\e 14) (#\E 14) (#\f 15) (#\F 15)))
17,558
Common Lisp
.lisp
332
38.262048
408
0.559958
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
003bf0dfbb0778cc8d2c79408861b10a7bd3ee128d10d5a58b3c0e19c9a85b59
6,751
[ -1 ]
6,752
file-vector.lisp
white-flame_clyc/larkc-cycl/file-vector.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) #| A fvector is saved over 2 files: The index file holds 4-byte offset pointers into the data stream. The data stream is a concatenation of presumably arbitrary-length binary items. This seems limited to holding a bit over 4GiB of data. Reads are performed by having this position the data-stream to the selected index, and then using external cfasl stuff on the data-stream. Unfortunately, writing seems to be missing-larkc. Presumably, data items are mutated by appending the end of the data stream if they don't fit in the prior value's footprint, then updating the index entry to point to it. However, this would require eventual vacuuming. Hmm, there doesn't seem to be any place in the struct or index file to hold the footprint of the prior object, so it would actually have to be incompatibly reworked to add that in somehow. But an append-only system would function without issue. |# (defstruct fvector data-stream index-stream) (defun* get-file-vector-data-stream (fvector) (:inline t) (fvector-data-stream fvector)) (defun new-fvector (data-stream index-stream) (make-fvector :data-stream data-stream :index-stream index-stream)) (defun file-vector-p (object) "[Cyc] Return T iff OBJECT is a FILE-VECTOR datastructure." (fvector-p object)) (defun new-file-vector (data-filename index-filename &optional (direction :input)) (with-open-file (data-stream data-filename :element-type '(unsigned-byte 8) :direction direction) (with-open-file (index-stream index-filename :element-type '(unsigned-byte 8) :direction direction) (create-file-vector data-stream index-stream)))) (defun create-file-vector (data-stream index-stream) (new-fvector data-stream index-stream)) (defun close-file-vector (fvector) "[Cyc] Close the streams associated wihth the file vector under question." (close (fvector-data-stream fvector)) (close (fvector-index-stream fvector)) fvector) (defun file-vector-length (fvector) "[Cyc] Return the FIXNUMP number of entries in the file vector." (fvector-raw-byte-size-to-length (file-length (fvector-index-stream fvector)))) (defun file-vector-length-from-index (index-filename) "[Cyc] A helper function that allows getting the index without allocating the file-vector object." (unless (probe-file index-filename) (error "Invalid index filename ~a." index-filename)) (with-open-file (stream index-filename) (fvector-raw-byte-size-to-length (file-length stream)))) (defun* fvector-raw-byte-size-to-length (bytes) (:inline t) (declare (fixnum bytes)) (ash bytes -2)) (defun position-file-vector (fvector &optional index) "[Cyc] Position the data stream of the file vector. If an INDEX is supplied, the data stream is positioned to the data offset stored in the index file for that nth entry. If no index is supplied, it is positioned to th enext value in the index-stream (e.g. in the case of a loop)." (let ((data-stream (fvector-data-stream fvector))) (set-file-position data-stream (read-file-vector-index-entry fvector index)) data-stream)) (defun read-file-vector-index-entry (fvector &optional index) "[Cyc] Fetch a specific entry from the file vector index. move first to the specified INDEX if provided. Returns the NON-NEGATIVE-INTEGER-P file position in the data stream." (when index (position-file-vector fvector index)) ;; Read big endian, the opposite order of CFASL-INPUT-INTEGER (read-32bit-be (fvector-index-stream fvector)))
4,951
Common Lisp
.lisp
85
54.329412
283
0.760671
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
80e176c8cee4280c24fa48fd13deaa50da11f61b81b584c4c1237c6cb85815cc
6,752
[ -1 ]
6,753
narts-high.lisp
white-flame_clyc/larkc-cycl/narts-high.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun naut-p (object) "[Cyc] Return T iff OBJECT is a datastructure implementing a non-atomic unreified term (NAUT). By definition, this satisfies CYCL-NAT-P but not NART-P." (and (possibly-naut-p object) (cycl-nat-p object))) (defun find-nart (nart-hl-formula) "[Cyc] Return the nart implementing NART-HL-FORMULA, or NIL if none is present. Subsitutions for existing sub-NARTs are performed." (let ((nart (nart-substitute nart-hl-formula))) (and (nart-p nart) nart))) '(defun remove-dependent-narts (fort) "[Cyc] Remove all current NARTs which are functions of FORT." (dolist (dependent (dependent-narts fort)) (missing-larkc 30883))) (defun nart-expand (object) "[Cyc] Recursively expand all NARTs in OBJECT into their EL forms (NAUTs)." (if (tree-find-if #'nart-p object) (transform object #'nart-p) object)) (defun nart-substitute (object) "[Cyc] Substitute into OBJECT as many NARTs as possible. If the entire formula can be converted to a NART, it will. Returns OBJECT itself if no substitutions can be made." (if (possibly-naut-p object) (nart-substitute-recursive object) object)) (defun nart-substitute-recursive (tree) (if (subl-escape-p tree) tree (let ((result tree)) (if (contains-nat-formula-as-element? tree) (let ((new-tree (copy-list tree))) (do ((list new-tree)) ((atom list) (setf result new-tree)) (let ((arg (car list))) (when (nat-formula-p arg) (let ((sub-nart (nart-substitute-recursive arg))) (when sub-nart (rplaca list sub-nart))))))) (setf result tree)) (let ((nart (nart-lookup result))) (if (nart-p nart) nart result))))) (defun contains-nat-formula-as-element? (list) "[Cyc] Return T iff LIST contains at least one element that could be reified as a nart. It does not consider whether LIST itself could be reified as a nart, and it does not look deeper than one level of nesting." (do ((rest list (cdr rest))) ((atom list)) (when (nat-formula-p (car rest)) (return t)))) (defun nart-lookup (nart-hl-formula) "[Cyc] Return the NART implementing NART-HL-FORMULA, or NIL if none is present. No substitutions for sub-NARTs are performed." (if (and (not *bootstrapping-kb*) (or (not (reifiable-functor? (nat-functor nart-hl-formula))) (not (fully-bound-p nart-hl-formula)))) nil (missing-larkc 871))) (defparameter *nart-dump-id-table* nil) (defun find-nart-by-dump-id (dump-id) "[Cyc] Return the NART with DUMP-ID during a KB load." (find-nart-by-id dump-id))
4,171
Common Lisp
.lisp
91
39.857143
214
0.690217
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
790c520afafc0a748910df3f73d740b7ac10d07900e06f67961e82ec727402cc
6,753
[ -1 ]
6,754
clause-strucs.lisp
white-flame_clyc/larkc-cycl/clause-strucs.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defstruct (clause-struc (:conc-name "CLS-")) id cnf assertions) (defmethod sxhash ((object clause-struc)) (declare (ignore object)) ;; TODO - simple ID accessor? why is this missing-larkc? reconstructable (missing-larkc 11340)) (deflexical *clause-struc-free-list* nil "[Cyc] Free list for CLAUSE-STRUC objects.") (deflexical *clause-struc-free-lock* (bt:make-lock "CLAUSE-STRUC resource lock") "[Cyc] Lock for CLAUSE-STRUC object free list.") (defun make-static-clause-struc () "[Cyc] Make a new CLAUSE-STRUC in the static area." (make-clause-struc)) (defun init-clause-struc (clause-struc) (setf (cls-id clause-struc) (setf (cls-cnf clause-struc) (setf (cls-assertions clause-struc) nil))) clause-struc) ;; TODO - collapse resourcing into a macro (defun get-clause-struc () "[Cyc] Get a CLAUSE-STRUC from the free list, or make a new one if needed." (if (not *structure-resourcing-enabled*) (init-clause-struc (if *structure-resourcing-make-static* (make-static-clause-struc) (make-clause-struc))) (missing-larkc 11349))) (defun* reset-clause-struc-id (clause-struc new-id) (:inline t) "[Cyc] Primitively change the clause-struc id for CLAUSE-STRUC to NEW-ID." (setf (cls-id clause-struc) new-id)) (defun* clause-struc-cnf (clause-struc) (:inline t) "[Cyc] Return the CNF of CLAUSE-STRUC." (cls-cnf clause-struc)) (defun* reset-clause-struc-assertions (clause-struc new-assertions) (:inline t) "[Cyc] Primitively set the assertions for CLAUSE-STRUC to NEW-ASSERTIONS." (setf (cls-assertions clause-struc) new-assertions)) (defun* find-clause-struc-by-id (id) (:inline t) "[Cyc] Return the clause-struc with ID, or NIL if not present." (lookup-clause-struc id)) (defun make-clause-struc-shell (cnf &optional id) (unless id (missing-larkc 11351)) (let ((clause-struc (get-clause-struc))) (register-clause-struc-id clause-struc id) (setf (cls-cnf clause-struc) cnf) clause-struc)) (defun* create-sample-invalid-clause-struc () (:inline t) "[Cyc] Create a sample invalid clause-struc." (get-clause-struc)) (defglobal *clause-struc-from-id* nil "[Cyc] The ID -> CLAUSE-STRUC mapping table.") (defun* clause-struc-table () (:inline t) *clause-struc-from-id*) (defun setup-clause-struc-table (size exact?) (unless *clause-struc-from-id* (setf *clause-struc-from-id* (new-id-index size 0)))) (defun finalize-clause-strucs (&optional max-clause-struc-id) (set-next-clause-struc-id max-clause-struc-id) (unless max-clause-struc-id (optimize-id-index *clause-struc-from-id*))) (defun free-all-clause-strucs () (do-id-index (id clause-struc (clause-struc-table) :progress-message "Freeing clause strucs") (missing-larkc 11347)) (clear-clause-struc-table)) (defun* clear-clause-struc-table () (:inline t) (clear-id-index *clause-struc-from-id*)) (defun set-next-clause-struc-id (&optional max-clause-struc-id) (let ((next-id (1+ (or max-clause-struc-id (let ((max -1)) (do-id-index (id clause-struc (clause-struc-table)) (setf max (max max (missing-larkc 11338)))) max))))) (set-id-index-next-id *clause-struc-from-id* next-id))) (defun register-clause-struc-id (clause-struc id) (reset-clause-struc-id clause-struc id) (id-index-enter *clause-struc-from-id* id clause-struc)) (defun* lookup-clause-struc (id) (:inline t) (id-index-lookup *clause-struc-from-id* id)) ;; TODO - these dump-id-tables are scattered around, but unused. Part of serialization identity? (defparameter *clause-struc-dump-id-table* nil)
5,177
Common Lisp
.lisp
110
42.090909
97
0.706783
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
1d33fc139bfeaa3ddf56397f3b2b7a9a5267f2d004665cbe19e3069ef9ea9b94
6,754
[ -1 ]
6,755
function-terms.lisp
white-flame_clyc/larkc-cycl/function-terms.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun term-of-unit-assertion-p (object) (when (gaf-assertion? object) (eq #$termOfUnit (gaf-predicate object)))) (defun nat-formula-p (object) "[Cyc] Return T iff OBJECT could be interpreted as a nat formula." (possibly-naut-p object)) (defun* tou-assertion? (assertion) (:obsolete t) "[Cyc] Obsolete." (term-of-unit-assertion-p assertion)) (defun term-functional-complexity (object) "[Cyc] Return the maximum functional nesting depth of OBJECT." (with-all-mts (term-functional-complexity-internal object))) (defpolymorphic term-functional-complexity-internal (object) 0) (defmethod term-functional-complexity-internal ((object constant)) 0) (defmethod term-functional-complexity-internal ((object nart)) (missing-larkc 10746)) (defmethod term-functional-complexity-internal ((object cons)) "[Cyc] Fancy way of returning max term functional complexity within a NART." (destructuring-bind (function &rest args) object (if (and (fort-p function) (not (non-predicate-function? function))) 0 (let ((arg-max-complexity (term-functional-complexity-internal function))) (dolist (arg args) (let ((arg-complexity (term-functional-complexity-internal arg))) (setf arg-max-complexity (max arg-max-complexity arg-complexity)))) (1+ arg-max-complexity))))) ;; TODO - no default implementation, only specialized methods? so defgeneric instead of defpolymorphic for here (defgeneric term-relational-complexity-internal (object)) (defmethod term-relational-complexity-internal ((object constant)) 0) (defmethod term-relational-complexity-internal ((object nart)) (missing-larkc 10766)) (defmethod term-relational-complexity-internal ((object cons)) (missing-larkc 10764)) (defun naut-to-nart (obj) "[Cyc] If OBJ is a ground NAUT (EL nat), convert it to an HL nart and return it, else return OBJ." (if (possibly-naut-p obj) (or (find-nart obj) obj) obj))
3,392
Common Lisp
.lisp
71
43.71831
112
0.749012
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
9a71fadd6aa6e622c63c2a504b3b26b6b61e5f8d6e5ece552319397d1ca7901c
6,755
[ -1 ]
6,756
cache.lisp
white-flame_clyc/larkc-cycl/cache.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defstruct cache (capacity 0 :type (and fixnum (integer 0))) map head-entry) (defun* cache-contains-key-p (cache key) (:inline t) "[Cyc] Checks whether the key is currently associated with an entry in the cache. Other than GET, this does not change the ordering of teh entries in the cache. CACHE: the cache within which to check for an association KEY: the key to be checked for association returns T if the key has an association, NIL otherwise" (nth-value 1 (gethash key (cache-map cache)))) (defstruct cache-entry newer key value older) (defparameter *cache-entries-preallocate?* nil "[Cyc] When T, preallocate all of the cache entries and resource them") (defun new-cache (capacity &optional (test #'eql)) "[Cyc] Creates a new cache with the specified capacity and test function CAPACITY: the maximal number of entries CACHE can hold" (declare (fixnum capacity)) (let* ((head-entry (make-cache-entry)) (cache (make-cache :capacity capacity :map (make-hash-table :size capacity :test test) :head-entry head-entry))) (setf (cache-entry-newer head-entry) head-entry) (setf (cache-entry-older head-entry) head-entry) (when *cache-entries-preallocate?* (set-cache-free-list cache :resourced) (dotimes (i capacity) (resource-cache-entry cache (make-cache-entry)))) cache)) (defun new-preallocated-cache (capacity &optional (test #'eql)) "[Cyc] Creates a new cache under preallocation strategy CAPACITY: the maximal number of entries CACHE can hold" (let ((*cache-entries-preallocate?* t)) (new-cache capacity test))) (defun cache-full-p (cache) "[Cyc] Returns true if CACHE is full, NIL otherwise" (>= (cache-size cache) (cache-capacity cache))) (defun cache-empty-p (cache) "[Cyc] Returns true if CACHE is empty, NIL otherwise" (eq (cache-newest cache) (cache-head-entry cache))) (defun cache-get (cache key) "[Cyc] Returns the entry associated with KEY in CACHE returns (i) the value assocaited with KEY in CACHE (ii) a boolean value indicating whether there was an entry for KEY in CACHE" (cache-get-int cache key nil t)) (defun cache-get-without-values (cache key &optional default) "[Cyc] Returns the entry associated with KEY in CACHE returns the value associated with KEY in CACHE, or DEFAULT if there was no such entry for KEY in CACHE" (cache-get-int cache key default nil)) ;; TODO - split this into 2 versions based on return-entry-p, these tests are statically resolvable (defun cache-get-int (cache key default return-entry-p) (let ((entry (gethash key (cache-map cache)))) (if (not entry) (if return-entry-p (values nil nil) default) (progn (cache-queue-requeue cache entry) (if return-entry-p (values (cache-entry-value entry) t) (cache-entry-value entry)))))) (defun cache-set (cache key value) "[Cyc] Associates KEY with VALUE in CACHE returns (i) the value previously associated with KEY in CACHE (ii) a boolean value indicating whether there was an entry previously associated with KEY in CACHE" (cache-set-int cache key value t)) (defun cache-set-without-values (cache key value) "[Cyc] Associates KEY with VALUE in CACHE returns the value previously associated with KEY in CACHE" (cache-set-int cache key value nil)) ;; TODO DESIGN - the cache test for setting when it's full goes missing-larkc, which invalidates a fundamental use of the cache in the first place. (defun cache-set-return-dropped (cache key value) "[Cyc] Associates KEY with VALUE in CACHE return 0 the key that was dropped from the cache, else NIL return 1 the values that was dropped from the cache, else NIL return 2 non-NIL iff a key/value association was dropped from the cache." (let ((oldest-key nil) (oldest-value nil) (dropped nil)) (when (and (cache-full-p cache) (eq :unknown (cache-get-without-values cache key :unknown))) (missing-larkc 31599)) (cache-set-without-values cache key value) (values oldest-key oldest-value dropped))) (defun cache-set-int (cache key value return-old-entry) (declare (ignore return-old-entry)) (let ((old-entry (gethash key (cache-map cache))) (previous nil)) (if old-entry (progn (setf previous (cache-entry-value old-entry)) (setf (cache-entry-value old-entry) value) (cache-queue-requeue cache old-entry)) (let ((entry nil)) (if (cache-full-p cache) ;; TODO DESIGN - bump older cache entries (missing-larkc 31600) (setf entry (get-new-cache-entry cache))) (setf (cache-entry-key entry) key) (setf (cache-entry-value entry) value) (setf (gethash key (cache-map cache)) entry) (cache-queue-enqueue cache entry))) ;; Based on return-old-entry, this would return 1 value or 2. It's faster in SBCL to always return the same number of values. (values previous old-entry))) (defun cache-remove (cache key) "[Cyc] Removes the mapping for KEY from CACHE return (i) the value previously associated with KEY in CACHE (ii) a boolean value indicating whether a value was previously associated with KEY in CACHE" (let ((entry (gethash key (cache-map cache))) (value nil)) (when entry (cache-queue-remove cache entry) (remhash key (cache-map cache)) (setf value (cache-entry-value entry))) (values value entry))) (defun cache-clear (cache) "[Cyc] Removes all entries from CACHE, either individually (if precached) or aggressively" (if (is-cache-preallocated-p cache) (until (cache-empty-p cache) ;; TODO - fetches oldest, then (cache-remove cache (cache-entry-key oldest)) (missing-larkc 31601)) (let ((head-entry (cache-head-entry cache))) (setf (cache-entry-newer head-entry) head-entry) (setf (cache-entry-older head-entry) head-entry) (clrhash (cache-map cache)))) cache) (defun cache-size (cache) "[Cyc] Returns the number of entries in CACHE" (hash-table-count (cache-map cache))) ;; Implementation taken from kb-object-manager's swap-out-all-pristine-kb-objects-int ;; Absorbs all the do-cache-* helpers into itself (defmacro do-cache ((id value cache &optional (order :newest)) &body body) (alexandria:with-gensyms (head entry) `(let* ((,head (cache-head-entry ,cache)) (,entry ,head)) (until (progn (setf ,entry ,(ecase order (:newest `(cache-entry-older ,entry)) (:oldest `(cache-entry-newer ,entry)))) (eq ,entry ,head)) (let ((,id (cache-entry-key ,entry)) (,value (cache-entry-value ,entry))) (declare (ignorable ,id ,value)) ,@body))))) (defconstant *cfasl-opcode-cache* 63) (defun cache-newest (cache) "[Cyc] Returns the entry of CACHE that was added most recently" (cache-entry-older (cache-head-entry cache))) (defun cache-queue-remove (cache entry) "[Cyc] Removes ENTRY from the CACHE's priority queue" (cache-queue-unlink entry) (possibly-resource-cache-entry cache entry) cache) (defun cache-queue-requeue (cache entry) "[Cyc] Update the cache queue so that the entry becomes the newest ENTRY" (cache-queue-unlink entry) (cache-queue-append cache entry)) (defun cache-queue-enqueue (cache entry) "[Cyc] Enqueues ENTRY onto CACHE's priority queue" (cache-queue-append cache entry)) (defun cache-queue-append (cache entry) "[Cyc] Add ENTRY onto CACHE's priority queue at the end" (setf (cache-entry-newer entry) (cache-head-entry cache)) (setf (cache-entry-older entry) (cache-newest cache)) (setf (cache-entry-newer (cache-newest cache)) entry) (setf (cache-entry-older (cache-head-entry cache)) entry) cache) (defun cache-queue-unlink (entry) "[Cyc] Remove entry from its neighbors" (setf (cache-entry-newer (cache-entry-older entry)) (cache-entry-newer entry)) (setf (cache-entry-older (cache-entry-newer entry)) (cache-entry-older entry)) entry) (defun is-cache-preallocated-p (cache) (let ((free-list (cache-free-list cache))) (or (eq :resourced free-list) (cache-entry-p free-list)))) (defun get-new-cache-entry (cache) "[Cyc] Fetch an empty entry from the free list or allocate a new one." (or (unresource-cache-entry cache) (make-cache-entry))) (defun cache-free-list (cache) "[Cyc] Returns the resourced list of cache entries." (cache-entry-key (cache-head-entry cache))) (defun set-cache-free-list (cache head) "[Cyc] Set the head of the cache free list, containing the resourced cache entries" (setf (cache-entry-key (cache-head-entry cache)) head) cache) (defun possibly-resource-cache-entry (cache entry) "[Cyc] Decide whether to put this entry onto the free list of teh cache" (when (is-cache-preallocated-p cache) (resource-cache-entry cache entry)) cache) (defun resource-cache-entry (cache entry) "[Cyc] Put the entry onto the free list of the cache." (scrub-cache-entry entry) (setf (cache-entry-newer entry) (cache-free-list cache)) (set-cache-free-list cache entry)) (defun unresource-cache-entry (cache) "[Cyc] Get an ENTRY from the free list of CACHE if you can; return NIL otherwise." (let ((free-list (cache-free-list cache)) (entry nil)) (when (cache-entry-p free-list) (setf entry free-list) (set-cache-free-list cache (cache-entry-newer entry)) (setf (cache-entry-newer entry) nil)) entry)) (defun scrub-cache-entry (entry) "[Cyc] Clean up all slots to prevent any loitering." (setf (cache-entry-value entry) (setf (cache-entry-key entry) (setf (cache-entry-newer entry) (setf (cache-entry-older entry) nil)))) entry)
11,386
Common Lisp
.lisp
241
41.784232
162
0.700749
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
d66a6311778edb15d60c7fb78b723f5a953fc6f6af1ad5dee36b661e1512ee2a
6,756
[ -1 ]
6,757
constant-completion-high.lisp
white-flame_clyc/larkc-cycl/constant-completion-high.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun valid-constant-name-char-p (char) "[Cyc] Return T iff CHAR is a character which is allowed in a valid constant name." (declare (character char)) (or (alphanumericp char) (find char "-_:"))) (defun valid-constant-name-p (string) "[Cyc] Return T iff STRING is a valid name for a constant." (and (stringp string) (>= (length string) 2) (not (find-if #'invalid-constant-name-char-p string)))) (defun invalid-constant-name-char-p (char) "[Cyc] Return T iff CHAR is a character which is not allowed in a valid constant name." (not (valid-constant-name-char-p char))) (defparameter *require-case-insensitive-name-uniqueness* t "[Cyc] Do we require that constant names be case-insensitively unique?") (defun constant-name-case-collisions (string) "[Cyc] Return a list of constants whose names differ from STRING only by case." (check-type string 'valid-constant-name-p) (let ((uses (constant-complete string nil t))) (delete string uses :test #'equal :key #'constant-name))) (defun constant-name-case-collision (string) "[Cyc] Return a constant whose name differs from STRING only by case." (check-type string 'valid-constant-name-p) (first (constant-name-collisions string))) (defun constant-complete-exact (string &optional (start 0) end) "[Cyc] Return a valid constant whose name exactly matches STRING. Optionally the START and END character positions can be specified, such that the STRING matches characters between the START and END range. If no constant exists, return NIL." (declare (string string) (fixnum start)) (kb-constant-complete-exact string start end)) (defun constant-complete (prefix &optional case-sensitive? exact-length? (start 0) end) "[Cyc] Return all valid constants with PREFIX as a prefix of their name. When CASE-SENSITIVE? is non-NIL, the comparison is done in a case-sensitive fashion. When EXACT-LENGTH? is non-NIL, the prefix must be the entire string. Optionally the START and END character positions can be specified, such that the PREFIX matches characters between the START and END range. If no constant exists, return NIL." (kb-constant-complete prefix case-sensitive? exact-length? start end)) (defun new-constant-completion-iterator (&optional (forward? t) (buffer-size 1)) (kb-new-constant-completion-iterator forward? buffer-size)) (defun map-constants-in-completions (function) (let ((iterator (new-constant-completion-iterator))) (map-iterator function iterator)))
3,895
Common Lisp
.lisp
67
54.791045
243
0.763435
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
4200b308db8ae2e73d41291e00d2db12308979105ee08e23d79b9808e117686e
6,757
[ -1 ]
6,758
cfasl-kernel.lisp
white-flame_clyc/larkc-cycl/cfasl-kernel.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defparameter *perform-cfasl-externalization* nil) (defun* cfasl-externalization-mode? () (:inline t) *perform-cfasl-externalization*) (defun cfasl-set-mode-externalized () "[Cyc] Switch this connection into external setting." (setf *perform-cfasl-externalization* t)) (defun cfasl-server-handler (in-stream out-stream) (cfasl-server-top-level in-stream out-stream)) (defparameter *cfasl-kernel-standard-output* nil "[Cyc] The standard output stream for debugging within a task-processor-request.") (defun cfasl-server-toplevel (in-stream out-stream) (let ((*cfasl-common-symbols* nil)) (cfasl-set-common-symbolscommon-symbols nil) (let ((*perform-cfasl-externalization* nil) (*generate-readable-fi-results* nil) (*default-api-input-protocol* 'read-cfasl-request) (*default-api-validate-method* 'validate-cfasl-request) (*default-api-output-protocol* 'send-cfasl-result) (*cfasl-kernel-standard-output* *standard-output*)) (api-server-top-level in-stream out-stream)))) (defun cfasl-quit () "[Cyc] Explicity quit this cfasl connection." (api-quit)) (defun cfasl-port () "[Cyc] Returns the local cfasl-port according to defined system parameters." (+ *base-tcp-port* *cfasl-port-offset*)) (defun read-cfasl-request (in-stream &optional (eof-error-p t) (eof-value :eof)) ;; TODO - this Java body catches an error message, tests for its presence, but does literally nothing if one is caught. This might be an ignore-errors expansion, but I think I saw one of those elsewhere where it was clear without extra claptrap like this. Just using ignore-errors for now anyway as it seems functionally equivalent. (ignore-errors (cfasl-input in-stream eof-error-p eof-value))) (defun validate-cfasl-request (api-request) (unless (proper-list-p api-request) (error "Invalid API Request: ~s is not a proper list" api-request)) (unless (or *eval-in-api?* (valid-api-function-symbol (car (api-request)))) (error "Invalid API Request: ~s is not a valid API function symbol" (car api-request)))) (defun send-cfasl-result (out-stream cfasl-result &optional error) (when error (setf cfasl-result (make-cfasl-api-exception cfasl-result))) (cfasl-output (null error) out-stream) (if (cfasl-externalization-mode?) (cfasl-output-externalized cfasl-result out-stream) (cfasl-output cfasl-result out-stream)) (force-output out-stream) cfasl-result) (defun make-cfasl-api-exception (string) (list 'cyc-exception :message string)) (defparameter *cfasl-eof-exception* (make-cfasl-api-exception "EOF occurred on CFASL API stream")) (defun task-processor-request (request id priority requestor client-bindings &optional uuid-string) "REQUEST: consp for evaluation ID: integer PRIORITY integer REQUESTOR string CLIENT-BINDINGS: consp of (var value) pairs UUID-STRING: identifies the clietn to which the response will be sent Submits the REQUEST form to the task request queue with ID, PRIORITY, REQUESTOR, BINDINGS, and OUT-STREAM." (let ((server-bindings (list* (list '*use-local-queue?* nil) (list '*the-cyclist* (the-cyclist)) (list '*ke-purpose* *default-ke-purpose*) '((*eval-in-api-env* nil) (*eval-in-api-level* 0) (*eval-in-api-traced-fns* nil) (*eval-in-api-trace-log* "") (*ignore-warns?* t) (*ignore-breaks?* t) (*silent-progress?* t) (*continue-cerror?* t) (*standard-output* *null-output*) (*error-output* *null-output*) (*package* (find-package :cyc)))))) (api-task-processor-request request id priority requestor (append server-bindings client-bindings) uuid-string)))
5,513
Common Lisp
.lisp
100
46.84
336
0.680349
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
5228c022f9d63dda0b9db1bbb37d29c565e3cdf3b4538e159dbac4fe73f838af
6,758
[ -1 ]
6,759
assertion-handles.lisp
white-flame_clyc/larkc-cycl/assertion-handles.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defglobal *assertion-from-id* nil ;; This is an id-index "[Cyc] The ID -> ASSERTION mapping table.") (defun* do-assertions-table () (:inline t) *assertion-from-id*) (defun setup-assertion-table (size exact?) (declare (ignore exact?)) (unless *assertion-from-id* (setf *assertion-from-id* (new-id-index size 0)) t)) (defun finalize-assertions (&optional max-assertion-id) (set-next-assertion-id max-assertion-id) (unless max-assertion-id (missing-larkc 30896))) (defun clear-assertion-table () (clear-id-index *assertion-from-id*)) (defun assertion-count () "[Cyc] Return the total number of assertions." (if *assertion-from-id* (id-index-count *assertion-from-id*) 0)) (defun* lookup-assertion (id) (:inline t) (id-index-lookup *assertion-from-id* id)) (defun set-next-assertion-id (&optional max-assertion-id) (let ((max -1)) (if max-assertion-id (setf max max-assertion-id) (do-id-index (id assertion (do-assertions-table) :progress-message "Determining maximum assertion ID") (setf max (max max (assertion-id assertion))))) (let ((next-id (+ max 1))) (set-id-index-next-id *assertion-from-id* next-id) next-id))) (defun register-assertion-id (assertion id) "[Cyc] Note that ID will be used as the id for ASSERTION." (reset-assertion-id assertion id) (id-index-enter *assertion-from-id* id assertion) assertion) (defun deregister-assertion-id (id) "[Cyc] Note that ID is not in use as an assertion id." (id-index-remove *assertion-from-id* id)) (defun make-assertion-id () "[Cyc] Return a new integer id for an assertion." (id-index-reserve *assertion-from-id*)) (defstruct (assertion (:conc-name as-)) id) (defparameter *print-assertions-in-cnf* nil) (defmethod sxhash ((object assertion)) (let ((id (as-id object))) (if (integerp id) id 23))) (defun* get-assertion () (:inline t) "[Cyc] Make a new assertion shell, potentially in static space." (make-assertion)) (defun* free-assertion (assertion) (:inline t) "[Cyc] Invalidate ASSERTION." (setf (as-id assertion) nil)) (defun valid-assertion-handle? (object) "[Cyc] Return T iff OBJECT is a valid assertion handle." (and (assertion-p object) (assertion-handle-valid? object))) (defun* valid-assertion? (assertion &optional robust?) (:inline t) "[Cyc] Return T if ASSERTION is a valid assertion." (declare (ignore robust?)) (valid-assertion-handle? assertion)) (defun make-assertion-shell (&optional id) (unless id (setf id (make-assertion-id))) (check-type id #'fixnump) (let ((assertion (get-assertion))) (register-assertion-id assertion id) assertion)) (defun* create-sample-invalid-assertion () (:inline t) "[Cyc] Create a sample invalid-assertion." (get-assertion)) (defun free-all-assertions () (do-id-index (id assertion (do-assertions-table) :progress-message "Freeing assertions") (free-assertion assertion)) (clear-assertion-table) (clear-assertion-content-table)) (defun* assertion-id (assertion) (:inline t) "[Cyc] Return the id of this ASSERTION." (as-id assertion)) (defun* reset-assertion-id (assertion new-id) (:inline t) "[Cyc] Primitively change the assertion id for ASSERTION to NEW-ID." (setf (as-id assertion) new-id)) (defun* assertion-handle-valid? (assertion) (:inline t) (integerp (as-id assertion))) (defun* find-assertion-by-id (id) (:inline t) "[Cyc] Return the assertion with ID, or NIL if not present." (lookup-assertion id))
4,983
Common Lisp
.lisp
120
37.716667
78
0.719295
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
80eb9c66ed8647c17c37b75810a74a4ef6a6f5ba9c7640b0b7102f694d331a04
6,759
[ -1 ]
6,760
el-utilities.lisp
white-flame_clyc/larkc-cycl/el-utilities.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# ;; TODO DESIGN - a lot of tools pass around argument numbers, which means constantly having to iterate a list, instead of simply passing the element value itself. Eventually switch to the latter. (in-package :clyc) (defun el-formula-with-operator-p (formula operator) "[Cyc] Return T iff OBJECT isa formula whose arg0 is OPERATOR." (and (el-formula-p formula) (equal operator (formula-arg0 formula)))) (defun make-ist-sentence (mt sentence) "[Cyc] Return a new #$ist sentence of the form (#$ist MT SENTENCE)." (make-binary-formula #$ist mt sentence)) (defun unmake-ternary-formula (formula) "[Cyc] Assumes that FORMULA is a ternary formula. Returns four values: the operator of FORMULA, its arg1, its arg2, and its arg3." (values (formula-arg0 formula) (formula-arg1 formula) (formula-arg2 formula) (formula-arg3 formula))) (defun possibly-formula-with-sequence-variables? (formula) "[Cyc] Return T iff FORMULA might have a sequence variable. This is suitable for fast-fails." (tree-find-if #'dotted-list-p formula)) (defun sentence-free-sequence-variables (sentence &optional bound-vars (var? #'cyc-var?)) "[Cyc] Returns the free variables in SENTENCE that occur as sequence variables." (when (possibly-formula-with-sequence-variables? sentence) (let* ((seqvar (sequence-var sentence)) (result (and seqvar (not (member? seqvar bound-vars)) (list seqvar)))) (cond ((member? sentence bound-vars) result) ((funcall var? sentence) result) ((atom sentence) result) ((el-negation-p sentence) (append result (sentence-free-sequence-variables (sentence-arg1 sentence) bound-vars var?))) ((or (el-conjunction-p sentence) (el-disjunction-p sentence)) (dolist (arg (sentence-args sentence :ignore)) (dolist (var (sentence-free-sequence-variables arg bound-vars var?)) (pushnew var result))) result) ((or (el-implication-p sentence) (el-exception-p sentence)) (setf result (append result (sentence-free-sequence-variables (sentence-arg1 sentence) bound-vars var?))) (dolist (var (sentence-free-sequence-variables (sentence-arg2 sentence) bound-vars var?)) (pushnew var result)) (nreverse result)) ((possibly-el-quantified-sentence-p sentence) (append result (sentence-free-sequence-variables (quantified-sub-sentence sentence) (cons (quantified-var sentence) bound-vars) var?))) ((mt-designating-literal? sentence) (let* ((mt (designated-mt sentence)) (mt? (mt? mt)) (subsentence (designated-sentence sentence)) (result nil)) ;; TODO - expansion from mt-relevance-macros.lisp (let ((mt-var (and mt? mt))) (let ((*relevant-mt-function* (possibly-in-mt-determine-function mt-var)) (*mt* (possibly-in-mt-determine-mt mt-var))) (setf result (sentence-free-sequence-variables subsentence bound-vars var?)))) (if mt? result (append result (naut-free-sequence-variables mt bound-vars var?))))) ;; TODO - next 2 cond clauses have the same body. double check and merge? ((atomic-sentence? sentence) (append result (literal-free-sequence-variables sentence bound-vars var?))) ((and (el-formula-p sentence) (funcall var? (sentence-arg0 sentence))) (append result (literal-free-sequence-variables sentence bound-vars var?))) ((relation-expression? sentence) (append result (relation-free-sequence-variables sentence bound-vars var?))) (t result))))) (defun literal-free-sequence-variables (literal &optional old-bound-vars (var? #'cyc-var?)) (relation-free-sequence-variables literal old-bound-vars var?)) (defun relation-free-sequence-variables (relation &optional old-bound-vars (var? #'cyc-var?)) (cond ((not (possibly-formula-with-sequence-varaibles? relation)) nil) ((member? relation old-bound-vars) nil) ((funcall var? relation) nil) ((el-negation-p relation) (relation-free-sequence-variables (formula-arg1 relation) old-bound-vars var?)) ((el-formula-p relation) (let* ((reln (formula-arg0 relation)) (new-bound-vars (scoped-vars relation var?)) (bound-vars (union old-bound-vars new-bound-vars)) (psn 0) (sequence-var (sequence-var relation var?)) (ans nil)) (when (and sequence-var (not (member? sequence-var bound-vars))) (push sequence-var ans)) (dolist (term (formula-terms relation :ignore)) (cond ;; Lots of empty terms here, but still fall through to the post-cond behavior ((member? term bound-vars)) ((and (proper-list-p term) (subsetp term bound-vars))) ((leave-variables-at-el-for-arg? reln psn)) ((funcall var? term)) ((and (within-tou-gaf?) (eq psn 2))) ;; These have actual bodies, but I don't think the return value matters ((unreified-skolem-term? term) (let ((seqvar (sequence-var (second term)))) (and (not (member? seqvar bound-vars)) (funcall var? seqvar) (pushnew seqvar ans)))) ((naut? term) (dolist (var (naut-free-sequence-variables term bound-vars var?)) (pushnew var ans))) ((or (sentence? term) (expression-find-if #'scoping-relation-expression? term nil)) (dolist (var (sentence-free-sequence-variables term bound-vars var?)) (pushnew var ans)))) (incf psn)) (nreverse ans))))) (defun naut-free-sequence-variables (naut &optional old-bound-vars (var? #'cyc-var?)) (relation-free-sequence-variables naut old-bound-vars var?)) (defun designated-sequence (literal) "[Cyc] Returns EL-FORMULA-P or NIL; the designated CYcL sentence in LITERAL." (literal-arg literal (sentence-designation-argnum literal))) (defun sentence-designation-argnum (literal) "[Cyc] Returns INTEGERP or NIL; which arg position of LITERAL contains the designated CycL sentence." (let ((pred (literal-predicate literal))) (if (eq #$ist pred) 2 (fpred-value-in-any-mt pred #$sentenceDesignationArgnum)))) (defun designated-mt (literal) "[Cyc] Return HLMT-P or NIL: the designated microtheory in LITERAL." (literal-arg literal (mt-designation-argnum literal))) (defun mt-designation-argnum (literal) (let ((pred (literal-predicate literal))) (if (eq #$ist pred) 1 (fpred-value-in-any-mt pred #$microtheoryDesignationArgnum)))) (defun occurs-as-sequence-variable? (var sentence) "[Cyc] Returns T iff VAR occurs as a sequence variable in SENTENCE." (member? var (sentence-sequence-variables sentence))) (defun sentence-sequence-variables (formula &optional (var? #'cyc-var?)) (let* ((seqvar (sequence-var formula var?)) (seqvars (and seqvar (list seqvar)))) (when (el-formula-p formula) (dolist (term (formula-terms formula :ignore)) (setf seqvars (append seqvars (sentence-sequence-variables term))))) (fast-delete-duplicates seqvars))) (defun unmake-binary-formula (formula) "[Cyc] Assumes that FORMULA is a binary formula. Returns three values: the operator of FORMULA, its arg1, and its arg2." (values (formula-arg0 formula) (formula-arg1 formula) (formula-arg2 formula))) (defun sentence-free-term-variables (formula &optional bound-vars (var? #'cyc-var?)) "[Cyc] Returns the free variables in FORMULA that occur as term variables (the counterpart of sequence variables)." (sentence-free-variables formula bound-vars var? nil)) (defun formula-denoting-collection? (collection) "[Cyc] Returns T iff the instances of COLLECTION are constrained to be CycL formulas." (genl? collection #$CycLFormula *anect-mt*)) (defun sentence-denoting-collection? (collection) "[Cyc] Returns T iff the instances of COLLECTION are constrained to be CycL sentences." (genl? collection #$CycLSentence *anect-mt*)) (defun user-defined-logical-operator-p (object) "[Cyc] Returns T iff OBJECT is one of the user-defined bounded logical operators." (and (fort-p object) (not (cyc-const-logical-operator-p object)) (logical-connective-p object))) (defun el-negation-p (object) "[Cyc] Returns T iff OBJECT is a unary formula whose arg0 is the constant #$not. The formula is not required to be well-formed." (and (el-formula-with-operator-p object #$not) (el-unary-formula-p object))) (defun el-disjunction-p (object) "[Cyc] Returns T iff OBJECT is a formula whose arg0 is the constant #$or. The formula is not required to be well-formed." (el-formula-with-operator-p object #$or)) (defun el-conjunction-p (object) "[Cyc] Returns T iff OBJECT is a formula whose arg0 is the constant #$and. The formula is not required to be well-formed." (el-formula-with-operator-p object #$and)) (defun el-implication-p (object) "[Cyc] Returns T iff OBJECT is an implication, i.e. a binary formula whose arg0 is #$implies. Note that OJBECT does not need to be well-formed." (and (el-formula-with-operator-p object #$implies) (el-binary-formula-p object))) (defun cyc-const-general-implication-operator-p (object) "[Cyc] Return T iff OBJECT is a Cyc EL implication operator (#$implies or #$equiv)." (or (eq #$implies object) (eq #$equiv object))) (defun el-general-implication-p (object) "[Cyc] Return T iff OBJECT is an implicative formula, i.e. a binary formula whose arg0 is #$implies or #$equiv. Note that OBJECT does not need to be well-formed." (and (el-formula-p object) (cyc-const-general-implication-operator-p (formula-arg0 object)) (el-binary-formula-p object))) (defun el-universal-p (object) "[Cyc] Return T iff OBJECT is a universally quantified formula, i.e. one whose arg0 is #$forAll. Note that OBJECT does not need to be well-formed." (and (el-formula-with-operator-p object #$forAll) (el-binary-formula-p object) (el-var? (formula-arg1 object)))) (defun cycl-universal-p (object) "[Cyc] Like EL-UNIVERSAL-P but admits more terms as variables, e.g. HL variables." (and (el-formula-with-operator-p object #$forAll) (el-binary-formula-p object) (cyc-var? (formula-arg1 object)))) (defun el-existential-p (object) "[Cyc] Return T iff OBJECT is an exitentially quantified formula, i.e. one whose arg0 is #$thereExists, whose arg1 is an el variable, and also has an arg2. NOte that arg2 does not need to be well-formed." (and (el-formula-with-operator-p object #$thereExists) (el-binary-formula-p object) (el-var? (formula-arg1 object)))) (defun el-existential-min-p (object) "[Cyc] Return T iff OBJECT is a ternary formula whose arg0 is #$thereExistAtLeast. Note that OBJECT does not need to be well-formed." (and (el-formula-with-operator-p object #$thereExistAtLeast) (missing-larkc 30544))) (defun el-existential-max-p (object) "[Cyc] Return T iff OBJECT is a ternary formula whose arg0 is #$thereExistAtMost. Note that OBJECT does not need to be well-formed." (and (el-formula-with-operator-p object #$thereExistAtMost) (missing-larkc 30545))) (defun el-existential-exact-p (object) "[Cyc] Return T iff OBJECT is a ternary formula whose arg0 is #$thereExistExactly. Note that OBJECT does not need to be well-formed." (and (el-formula-with-operator-p object #$thereExistExactly) (missing-larkc 30546))) (defconstant *cyc-const-unary-logical-ops* (list #$not) "[Cyc] Used in the syntax checker.") (defun cyc-const-unary-logical-op-p (object) "[Cyc] Return T iff OBJECT is one of the predefined unary operators." (eq object #$not)) (defconstant *cyc-const-binary-logical-ops* (list #$implies #$xor #$equiv) "[Cyc] Used in the syntax checker.") (defun cyc-const-binary-logical-op-p (object) "[Cyc} Return T iff OBJECT is one of the predefined binary operators." (or (eq object #$implies) (eq object #$xor) (eq object #$equiv))) (defconstant *cyc-const-ternary-logical-ops* nil "[Cyc] Used in the syntax checker.") (defun* cyc-const-ternary-logical-op-p (object) (:ignore t) "[Cyc] Return T iff OBJECT is one of the predefined ternary operators." nil) (defconstant *cyc-const-quaternary-logical-ops* nil "[Cyc] Used in the syntax checker.") (defun* cyc-const-quaternary-logical-op-p (object) (:ignore t) "[Cyc] Return T iff OBJECT is one of the predefined quaternary operators." nil) (defconstant *cyc-const-quintary-logical-ops* nil "[Cyc] Used in the syntax checker.") (defun* cyc-const-quintary-logical-op-p (object) (:ignore t) "[Cyc] Return T iff OBJECT is one of the predefined quintary operators." nil) (defconstant *cyc-const-variable-arity-logical-ops* (list #$and #$or) "[Cyc] Used in the syntax checker.") (defun cyc-const-variable-arity-logical-op-p (object) "[Cyc] Return T iff OBJECT is one of the predefined variable-arity-operators." (or (eq object #$and) (eq object #$or))) (defun cyc-const-existential-p (object) "[Cyc] Return T iff OBJECT is #$thereExists" (eq object #$thereExists)) (defun cyc-const-universal-p (object) "[Cyc] Return T iff OBJECT is #$forAll." (eq object #$forAll)) (defconstant *cyc-const-regular-quantifiers* (list #$thereExists #$forAll)) (defun cyc-const-regular-quantifier-p (object) "[Cyc] Return T iff OBJECT is one of the predefined regular quantifiers." (or (cyc-const-existential-p object) (cyc-const-universal-p object))) (defun possibly-el-regularly-quantified-sentence-p (object) "[Cyc] Return T iff OBJECT is a binary sentence whose arg0 is one of the predefined regular quantifiers (#$forAll or #$thereExists)." (and (el-binary-formula-p object) (cyc-const-regular-quantifier-p (sentence-arg0 object)))) (defconstant *cyc-const-bounded-existentials* (list #$thereExistsExactly #$thereExistAtMost)) (defun cyc-const-bounded-existential-operator-p (object) "[Cyc] Return T iff OBJECT is one of th epredefined bounded existentials." (or (eq object #$thereExistExactly) (eq object #$thereExistAtMost) (eq object #$thereExistAtLeast))) (defun user-defined-bounded-existential-operator-p (object) "[Cyc] Return T iff OBJECT is one of the user-defined bounded existential quantifiers." (and (fort-p object) (cyc-const-bounded-existential-operator-p object) (bounded-existential-quantifier-p object))) (defun el-bounded-existential-p (object) "[Cyc] Return T iff OBJECT is a ternary formula whose arg0 is one of the predefined bounded existential quantifiers." (and (el-formula-p object) (cyc-const-bounded-existential-operator-p (formula-arg0 object)) (missing-larkc 30547))) (defun cyc-const-general-existential-operator-p (object) "[Cyc} Return T iff OBJECT is one fo the predefined existentials, either regular or bounded." (or (eq object #$thereExists) (cyc-const-bounded-existential-operator-p object))) (defun cyc-const-quantifier-p (object) "[Cyc] Return T iff OBJECT is one of the predefined quantifiers, either regular or bounded." (or (cyc-const-regular-quantifier-p object) (cyc-const-bounded-existential-operator-p object))) (defun possibly-el-quantified-sentence-p (object) "[Cyc] Return T iff OBJECT is either a regularly quantified formula or a bounded existential formula." (or (possibly-el-reguarly-quantified-sentence-p object) (el-bounded-existential-p object))) (defun cyc-const-logical-operator-p (object) "[Cyc] Return T iff OBJECT is any of the predefined logical operators." (or (cyc-const-unary-logical-op object) (cyc-const-ternary-logical-op-p object) (cyc-const-quaternary-logical-op-p object) (cyc-const-quintary-logical-op-p object) (cyc-const-variable-arity-logical-op-p object))) (defconstant *cyc-const-tense-operators* (list #$was #$hasAlwaysBeen #$willBe #$willAlwaysBe)) (defconstant *cyc-const-metric-tense-operators* (list #$was-Metric #$willBe-Metric)) (defun cyc-const-tense-operator-p (object) (or (eq object #$was) (eq object #$hasAlwaysBeen) (eq object #$willBe) (eq object #$willAlwaysBe))) (defun cyc-const-metric-tense-operator-p (object) (or (eq object #$was-Metric) (eq object #$willBe-Metric))) (defun cyc-const-generalized-tense-operator-p (object) (or (cyc-const-tense-operator-p object) (cyc-const-metric-tense-operator-p object))) (defun cyc-const-sentential-relation-p (object) "[Cyc] Return T iff OBJECT is any of the predefined logical operators or quantifiers, either regular or bounded." (or (cyc-const-logical-operator-p object) (cyc-const-quantifier-p object))) (defun el-logical-operator-formula-p (object) "[Cyc] Return T iff OBJECT is an EL formula with a logical operator as its arg0." (and (el-formula-p object) (cyc-const-logical-operator-p (formula-operator object)))) (defun el-unary-formula-p (object) "[Cyc] Return T iff OBJECT is a formula of arity 1. OBJECT is not required to be well-formed." (and (el-formula-p object) (formula-arity= object 1))) (defun el-binary-formula-p (object) "[Cyc] Return T iff OBJECT is a formula of arity 2. OBJECT is not required to be well-formed." (and (el-formula-p object) (formula-arity= object 2))) ;; TODO - subl -> cl (defun subl-escape-p (object) "[Cyc] Return T iff OBJECT is an escape to SubL, which should not be analyzed recursively." (and (el-formula-p object) (or (expand-subl-fn-p object) (subl-quote-p object)))) ;; TODO - subl -> cl (defun expand-subl-fn-p (object) "[Cyc] Return T iff OBJECT is an escape to SUbL using #$ExpandSubLFn." (and (eq #$ExpandSubLFn (formula-operator object)) (listp (formula-arg1 object)) (cyc-subl-template (formula-arg2 object)))) (defun subl-quote-p (object) "[Cyc] Return T iff OBJECT is an escape to SubL using #$SubLQuoteFn." (and (eq #$SubLQuoteFn (formula-operator object)) (formula-arity= object 1) (cyc-subl-template (formula-arg1 object)))) (defun epsilon-p (object) "[Cyc] Return T iff OBJECT is NIL (epsilon)." (null object)) (defconstant *cyc-const-exception-operators* (list #$exceptFor #$exceptWhen) "[Cyc] Used in the precanonicalizer.") (defun cyc-const-exception-operator-p (object) "[Cyc] Return T iff OBJECT is one of the predefined exception operators." (or (eq object #$exceptFor) (eq object #$exceptWhen))) (defconstant *cyc-const-pragmatic-requirement-operators* (list #$pragmaticRequirement) "[Cyc] Used in the precanonicalizer.") (defun* cyc-const-pragmatic-requirement-operator-p (object) (:inline t) "[Cyc] Return T iff OBJECT is one fo the predefined exception operators." (eq object #$pragmaticRequirement)) (defun el-pragmatic-requirement-operator-p (object) (and (cyc-const-pragmatic-requirement-operator-p (formula-operator object)) (el-binary-formula-p object))) (defun el-meets-pragmatic-requirement-p (object) "[Cyc] Assumes that #$meetsPragmaticRequirement is a binary operator. Return T iff OBJECT is a binary formula whose arg0 is #$meetsPragmaticRequirement." (and (el-binary-formula-p object) (eq #$meetsPragmaticRequirement (formula-operator object)))) (defun el-implicit-meta-literal-sentence-p (object) "[Cyc] Return T iff OBJECT is an EL setence which indicates an implicit meta-literal. The two kinds of EL sentences which indicate implicit meta-literals are EL exceptions (e.g. #$exceptWhen, #$exceptFor) and pragmatic requirements (#$pragmaticRequirement)." (or (el-exception-p object) (el-pragmatic-requirement-p object))) (defun elf-p (object) "[Cyc] Return T iff OBJECT is a candidate EL formula (not necessarily well-formed). 'formula' refers to a formula in the grammar, not a formula in the logic. FOr example, a non-atomic term is a formula in the grammar, but not a formula in the logic. Note that #$True and #$False are not considered formulas by this definition." (consp object)) (defun el-formula-p (object) "[Cyc] Return T iff OBJECT is a candidate EL formula (not necessarily well-formed). 'formula' refers to a formula in the grammar, not a formula in the logic. FOr example, a non-atomic term is a formula in the grammar, but not a formula in the logic. Note that #$True and #$False are not considered formulas by this definition." (elf-p object)) (defun possibly-fo-naut-p (object) "[Cyc] A quick test for whether OBJECT could possibly be a first order NAUT. It is certainly not guaranteed that OBJECT is a first order NAUT just because this function returns T." (and (el-formula-p object) (fort-p (el-formula-operator object)))) (defun possibly-naut-p (object) "[Cyc] A quick test for whether OBJECT could possibly be a NAUT. IT is certainly not guaranteed that OBJECT is a NAUT just because this function returns T." (el-formula-p object)) (defun possibly-sentence-p (object) "[Cyc] A quick test for whether OBJECT could possibly be a CycL setence. It is certainly not guaranteed that OBJECT is a CycL sentence just because this function returns T. Passing this test should guarantee that applying the sentence accessors will not trigger an error." (el-formula-p object)) (defun possibly-atomic-sentence-p (object) "[Cyc] A quick test for whether OBJECT could possibly be an atomic CycL sentence. It is certainly not guaranteed that OBJECT is an atomic CycL sentence just because this function returns T." (el-formula-pl object)) (defun contains-subformula-p (object) "[Cyc] Returns T iff OBJECT si an EL formula which contains an EL subformula." (when (el-formula-p object) (dolist (term (formula-terms object :ignore)) (when (el-formula-p term) (return t))))) (defun el-empty-list-p (obj) (or (eq obj #$TheEmptyList) (and (el-formula-p obj) (not (formula-with-sequence-var? obj)) (eq (formula-operator obj) #$TheList) (null (formula-args obj))))) (defun el-extensional-set-p (object) (or (el-empty-set-p object) (el-non-empty-set-p object))) (defun el-empty-set-p (object) (or (eq object #$TheEmptySet) (and (el-formula-p object) (not (formula-with-sequence-var? object)) (eq (formula-operator object) #$TheSet) (null (formula-args object))))) (defun el-non-empty-set-p (object) (and (el-formula-p object) (eq (formula-operator object) #$TheSet) (formula-args object :include))) (defun el-sequence-p (object) "[Cyc] Return T iff OBJECT is an EL sequence." (consp object)) (defun ground? (expression &optional (var? #'cyc-var?)) "[Cyc] Returns whether EXPRESSION is free of any variables?" (null (expression-find-if var? expression nil))) (defun hl-ground-tree-p (tree) (fully-bound-p tree)) (defun closed? (expression &optional (var? #'cyc-var?)) "[Cyc] Is EXPRESSION free of any free variables? (includes GROUND? check for efficiency)" (or (ground? expression var?) (no-free-variables? expression var?))) (defun no-free-variables? (expression &optional (var? #'cyc-var?)) "[Cyc] Is EXPRESSION free of any free varaibles? (excludes GROUND? check for efficiency)" (null (literal-free-variables expression nil var?))) (deflexical *standard-single-letter-el-var-names* '(?x ?y ?z ?w ?v ?u ?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m ?n ?o ?p ?q ?r ?s ?t)) (defun sequence-term (formula) "[Cyc] Returns the sequence term in FORMULA, if there is one. Otherwise returns NIL. For example, (sequence-term (<pred> ?X ?Y . <term>)) returns <term>. However, it will not return nested sequence terms; e.i. (sequence-var (#$and <form1> (<pred> ?X ?Y . <term>))) will return NIL." (when *el-supports-dot-syntax?* (cond ((el-formula-p formula) (cdr (last formula))) ;; If it's nart-p, also return nil, but that's implicit. ))) (defun sequence-var (relation &optional (var? #'cyc-var?)) "[Cyc] Returns the sequence variable in RELATION, if there is one. Otherwise returns NIL. For example, (sequence-var (<pred> ?X ?Y . ?Z)) returns ?Z. However, it will nto return nested sequence variables; i.e. (sequence-var (#$and <form1> (<pred> ?X ?Y . ?Z))) will return NIL." (let ((seqterm (sequence-term relation))) (when seqterm (cond ((eq var? #'cyc-var?) (and (cyc-var? seqterm) seqterm)) ((funcall var? seqterm) seqterm))))) (defun sequence-non-var (relation &optional (var? #'cyc-var?)) "[Cyc] Returns the part of RELATION that should be a sequence variable by its syntax, but isn't. Returns NIL if there is no such ill-formed thing in RELATION." (let ((seqterm (sequence-term relation))) (and seqterm (funcall var? seqterm) seqterm))) (defun maybe-add-sequence-var-to-end (seqvar formula) "[Cyc] Return FORMULA with SEQVAR added to the end, if SEQVAR is non-nil. Otherwise returns FORMULA unadulterated. Example: (maybe-add-sequence-var-to-end ?X (#$different #$Muffet #$Pace)) => (#$different #$Muffet #$Pace . ?X) Example: (maybe-add-sequence-var-to-end NIL (#$different #$Muffet #$Pace)) => (#$different #$Muffet #$Pace)" (if seqvar (missing-larkc 9016) formula)) (defun formula-with-sequence-term? (formula) (sequence-term formula)) (defun el-formula-without-sequence-term? (formula) (proper-list-p formula)) (defun formula-with-sequence-var? (formula) (sequence-var formula)) (defun formula-with-sequence-non-var? (formula) "[Cyc] Return T iff FORMULA contains someting in sequence variable position, but it's not a variable." (sequence-non-var formula)) (defun ignore-sequence-vars (formula) "[Cyc] e.g. transforms (<pref> ?X ?Y . ?Z) into (<pred> ?X ?Y)." (if (sequence-var formula) (missing-larkc 30664) formula)) (defun term-is-one-of-args? (term formula) (dolist (arg (formula-args formula :ignore)) (when (equal term arg) (return t)))) (defun formula-arity (formula &optional (seqvar-handling :ignore)) "[Cyc] Returns the arity of FORMULA (the number of arguments). This will be an integer if FORMULA is an EL formula, NART or assertion, and NIL otherwise (e.g. the arity of #$True is NIL). The operator itself does not count as an argument. If SEQVAR-HANDLING is :REGULARIZE, then sequence variables count as a single argument. Hence, (#$and <form1> <form2> <form3>) is a formula of arity 3, and (#$and <form1> <form2> <form3> . ?SEQ) is a formula of arity 4. If SEQVAR-HANDLING is :IGNORE< then sequence variables don't count, so both of those would be arity 3. Don't pass it :INCLUDE." (when (possibly-cycl-formula-p formula) (length (formula-args formula seqvar-handling)))) (defun expression-arity (relational-expression &optional (seqvar-handling :ignore)) (formula-arity relational-expression seqvar-handling)) (defun formula-length (formula &optional (seqvar-handling :ignore)) "[Cyc] Returns the length of the formula. In other words, the number of terms. This is one greater than the arity. If SEQVAR-HANDLING is :REGULARIZE, then sequence variables count as a single argument. If SEQVAR-HANDLING is :IGNORE, then sequence variables don't count at all." (length (formula-terms formula seqvar-handling))) (defun formula-arity< (formula arity &optional (seqvar-handling :ignore)) "[Cyc] Return T iff FORMULA's arity is less than ARITY." (and (possibly-cycl-formula-p formula) (positive-integer-p arity) (length< (formula-args formula seqvar-handling) arity nil))) (defun formula-arity> (formula arity &optional (seqvar-handling :ignore)) "[Cyc] Return T iff FORMULA's arity is greater than ARITY." (and (possibly-cycl-formula-p formula) (integerp arity) (length> (formula-args formula seqvar-handling) arity nil))) (defun formula-arity>= (formula arity &optional (seqvar-handling :ignore)) "[Cyc] Return T iff FORMULA's arity is greater than or equal to ARITY." (and (possibly-cycl-formula-p formula) (integerp arity) (length>= (formula-args formula seqvar-handling) arity nil))) (defun el-formula-arity>= (el-formula arity &optional (seqvar-handling :ignore)) "[Cyc] Return T iff EL_FORMULA's arity is greater than or equal to ARITY." (and (el-formula-p el-formula) (integerp arity) (length>= (el-formula-args el-formula seqvar-handling) arity nil))) (defun formula-arity= (formula arity &optional (seqvar-handling :ignore)) "[Cyc] Return T iff FORMULA's arity is equal to ARITY." (and (possibly-cycl-formula-p formula) (integerp arity) (length= (formula-args formula seqvar-handling) arity nil))) (defun first-in-sequence (sequence) "[Cyc] Returns the first element of SEQUENCE." (car sequence)) (defun rest-of-sequence (sequence) "[Cyc] Returns (as a list or a variable) all elements but the first of SEQUENCE." (rest sequence)) (defun sentence-quantifier (sentence) "[Cyc] If SENTENCE is a quantified sentence, returns teh quantifier. Otherwise returns NIL." (when (possibly-el-quantified-sentence-p sentence) (sentence-arg0 sentence))) (defun quantified-var (sentence) "[Cyc] Returns the quantified variable in a quantified sentence. Returns NIL if SENTENCE is not a quantified sentence. e.g. (quantified-var (#$forAll ?X <form1>)) would return ?X. and (quantified-var (#$thereExistsExactly 539 ?EVENT <form2>)) would return ?EVENT." (cond ((cycl-bounded-existential-sentence-p sentence) (sentence-arg2 sentence)) ((possibly-el-regularly-quantified-sentence-p sentence) (sentence-arg1 sentence)))) (defun quantified-sub-sentence (sentence) "[Cyc] Returns the quantified subsentence in a quantified sentence. Yields an error if SENTENCE is not a quantified sentence. e.g. (quantified-sub-sentence (#$forAll ?X <form1>)) would return <form1>. and (quantified-sub-sentence (#$thereExistsExactly 539 ?EVENT <form2>)) would return <form2>." (cond ((possibly-el-regularly-quantified-sentence-p sentence) (sentence-arg2 sentence)) ((cycl-bounded-existential-sentence-p sentence) (missing-larkc 29838)) (t (el-error 4 "not quantified sentence: ~s" sentence)))) (defun quantified-sub-sentence-argnum (sentence) "[Cyc] Returns the argnum that contains the quantified subsentence of SENTENCE. Yields an error and returns NIL if SENTENCE is not a quantified sentence." (quantified-sub-sentence-argnum-for-operator (sentence-arg0 sentence))) (defun quantified-sub-sentence-argnum-for-operator (operator) (cond ((cycl-regular-quantifier-p operator) 2) ((cycl-bounded-existential-quantifier-p operator) 3) (t (el-error 4 "not a known quantifier: ~s" operator)))) (defparameter *dont-enforce-subl-escape-in-symbols* t) (defun cycl-subl-symbol-symbol (object) "[Cyc] When OBJECT is a CYCL-SUBL-SYMBOL-P, returns the SubL symbol part." (cond ((cycl-subl-symbol-p object) (formula-arg1 object)) (*dont-enforce-subl-escape-in-symbols* object))) (defun list-to-elf (list) "[Cyc] Returns an EL formula constructe from the list LIST. Currently this just returns the list itself, since we implement EL formulas as lists. You can't destructively modify the returned EL formula without affecting LIST." list) (defun make-el-formula (operator args &optional sequence-var) "[Cyc} Returns a new EL formula with the operator OPERATOR, the arguments ARGS, and teh optional sequence variable SEQUENCE-VAR. This formula is destructible at the top level." (if sequence-var (append (cons operator (copy-list args)) sequence-var) (cons operator (copy-list args)))) (defun make-formula (operator args &optional sequence-var) "[Cyc] Returns a new EL formula with the operator OPERATOR, the arguments ARGS, and the optional sequence variable SEQUENCE-VAR. This formula is destructible at the top level." (make-el-formula operator args sequence-var)) (defun copy-formula (formula) "[Cyc] Returns a copy of the EL formula FORMULA." (copy-tree formula)) (defun copy-sentence (sentence) "[Cyc] Returns a copy of the EL sentence SENTENCE." (copy-tree sentence)) (defun copy-clause (clause) "[Cyc] Returns a copy of CLAUSE." (copy-tree clause)) (defun copy-expression (expression) "[Cyc] Returns a copy of EXPRESSION." (copy-tree expression)) (defun make-el-literal (predicate args &optional sequence-var) "[Cyc] Returns a new EL sentence with the operator PREDICATE and the arguments ARGS. This sentence is destructible at the top level." (make-el-formula predicate args sequence-var)) (defun make-unary-formula (operator arg) "[Cyc] Returns a new unary formula with the operator OPERATOR and the single argument ARG." (list operator arg)) (defun make-binary-formula (operator arg1 arg2) "[Cyc] Returns a new binary formula with the operator OPERATOR and the two arguments ARG1 and ARG2." (list operator arg1 arg2)) (defun make-ternary-formula (operator arg1 arg2 arg3) "[Cyc] Returns a new ternary formula with the operator OPERATOR and the three arguments ARG1, ARG2, and ARG3" (list operator arg1 arg2 arg3)) (defun make-negation (sentence) "[Cyc] Returns the negation of SENTENCE. Does not perform any simplification. i.e. just returns (#$not <sentence>)." (make-formula #$not sentence)) (defun make-disjunction (args) "[Cyc] Returns a new disjunction. Each member of the list ARGS is a disjunct in the new disjunction. e.g. (make-disjunction (<form1> <form2> <form3>)) returns (#$or <form1> <form2> <form3>)." (make-formula #$or args)) (defun make-conjunction (args) "[Cyc] Returns a new conjunction. Each member of the list ARGS is a conjunct in the new conjunction. e.g. (make-conjunction (<form1> <form2> <form3>)) returns (#$and <form1> <form2> <form3>)." (make-formula #$and args)) (defun make-universal (var sentence) "[Cyc] Returns a new universally quantified sentence of the form (#$forAll <var> <sentence>." (make-binary-formula #$forAll var sentence)) (defun make-regularly-quantified-sentence (quantifier var subsent) (make-binary-formula quantifier var subsent)) (defun map-formula-args (func formula &optional map-seqvar?) "[Cyc] Execute FUNC on each argument (in order) of FORMULA, unless it is an opaque argument. e.g. (map-formula-args #'func (#$and <form1> <form2> <form3>)) would return (#$and (func <form1>) (func <form2>) (func <form3>)). By default, FUNC is not applied to sequence variables, because they are not arguments per se; rather they are variables that can bind to argument (sub)sequences, but if MAP-SEQVAR? is T, then FUNC will be applied to sequence variables. example: (map-formula-args #'el-var? '(#$isa ?X #$Dog . ?Z)) => (#$isa T NIL . ?Z) example: (map-formula-args #'el-var? '(#$isa ?X #$Dog . ?Z) t) => (#$isa T NIL . T)" (when (el-formula-p formula) (let ((args (formula-args formula :include))) (if (consp args) (let ((new-args (car args))) (do ((arg (car args) (car remaining-args)) (remaining-args (cdr args) (cdr remaining-args)) (argnum 1 (1+ argnum))) ;; Exit test ((atom remaining-args) ;; also matches NIL ;; Return forms (push (if (opaque-arg? formula argnum) arg (funcall func arg)) new-args) (if remaining-args (let ((final-args (if (and map-seqvar? (missing-larkc 29830)) (funcall func remaining-args) remaining-args))) ;; TODO - why not append? (dolist (new-arg new-args) (push new-arg final-args)) (make-formula (formula-arg0 formula) final-args)) (make-formula (formula-arg0 formula) (nreverse new-args)))) ;; Iteration body (push (if (opaque-arg? formula argnum) arg (funcall func arg)) new-args))) formula)))) (defun nmap-formula-args (func formula &optional map-seqvar?) "[Cyc] A destructive version fo MAP-FORMULA-ARGS." (when (el-formula-p formula) (let ((args (formula-args formula :include))) (when (consp args) (do* ((curr-args args (cdr curr-args)) (arg (car curr-args) (car curr-args)) (argnum 1 (1+ argnum)) (remaining-args (cdr curr-args) (cdr curr-args))) ;; Exit test ((atom remaining-args) ;; also matches NIL ;; Return forms (rplaca curr-args (if (opaque-arg? formula argnum) arg (funcall func arg))) (when (and remaining-args map-seqvar? (missing-larkc 29833)) (rplacd curr-args (funcall func remaining-args)))) ;; Iteration body (rplaca curr-args (if (opaque-arg? formula argnum) arg (funcall func arg)))))) formula)) (defun pass-through-if-negation (function formula) "[Cyc] Return 0: FORMULA with FUNCTION applied to its arg1 iff FORMULA is a negation and its arg1 is not opaque. Return 1: Boolean, whether FORMULA was altered." (if (and (el-negation-p formula) (not (opaque-arg? formula 1))) (let ((*within-negation* t)) (values (make-negation (funcall function (formula-arg1 formula))) t)) (values formula nil))) (defun pass-through-if-disjunction (function formula) "[Cyc] Return 0: FORMULA with FUNCTION applied to its args iff FORMULA is a disjunction and its args are not opaque. Return 1: Boolean, whether FORMULA was altered." (if (el-disjunction-p formula) (let ((*within-disjunction?* t) (*within-negated-disjunction?* *within-negation?*)) (values (nmap-formula-args function formula) t)) (values formula nil))) (defun pass-through-if-conjunction (function formula) "[Cyc] Return 0: FORMULA with FUNCTION applied to its args iff FORMULA is a conjunction and its args are not opaque. Return 1: Boolean, whether FORMULA was altered." (if (el-conjunction-p formula) (values (nmap-formula-args function formula) t) (values formula nil))) (defun pass-through-if-regularly-quantified (function formula) "[Cyc] Return 0: FORMULA with FUNCTION applied to its quantified subformula iff FORMULA is a regularly quantified formula and its quantified subformula is not opaque. Return 1: Boolean, whetehr FORMULA was aletered." (if (and (possibly-el-regularly-quantified-sentence-p formula) (not (opaque-arg? formula (quantified-sub-sentence-argnum formula)))) (values (make-regularly-quantified-sentence (sentence-quantifier formula) (quantified-var formula) (funcall function (quantified-sub-sentence formula))) t) (values formula nil))) (defun pass-through-if-bounded-existential (function formula) "[Cyc] Return 0: FORMULA with FUNCTION applied to its quantified subformula iff FORMULA is a bounded existential formula and its quantified subformula is not opaque. Return 1: Boolean, whether FORMULA was altered." (declare (ignore function)) (if (and (el-bounded-existential-p formula) (not (opaque-arg? formula (quantified-sub-sentence-argnum formula)))) (missing-larkc 30588) (values formula nil))) (defun pass-through-if-junction (function formula) "[Cyc] Return 0: FORMULA with FUNCTION applied to its args iff FORMULA is a conjunction or disjunction and its args are not opaque. Return 1: Boolean, whether FORMULA was altered." (multiple-value-bind (result changed?) (pass-through-if-disjunction function formula) (if changed? (values result changed?) (pass-through-if-conjunction function formula)))) (defun pass-through-if-logical-op (function formula) "[Cyc] Return 0: FORMULA with FUNCTION applied to its args iff FORMULA is an EL formula with a logical operator as its arg0 and its args are not opaque. Return 1: Boolean, whether FORMULA was altered." (if (el-logical-operator-formula-p formula) (multiple-value-bind (result changed?) (pass-through-if-negation function formula) (if changed? (values result t) (multiple-value-bind (result-2 changed-2?) (pass-through-if-junction function formula) (if changed-2? (values result-2 t) (values (nmap-formula-args function formula) t))))) (values formula nil))) (defun pass-through-if-quantified (function formula) "[Cyc] Return 0: FORMULA with FUNCTION applied to its quantified subformula iff FORMULA is a quantified formula and its quantified subformula is not opaque. Return 1: Boolean, whether FORMULA was altered." (multiple-value-bind (result changed?) (pass-through-if-regularly-quantified function formula) (if changed? (values result t) (pass-through-if-bounded-existential function formula)))) (defun pass-through-if-logical-op-or-quantified (function formula) "[Cyc] Return 0: FORMULA with FUNCTION applied to its quantified subformula iff FORMULA is an EL formula with a quantifier or logical operator as its arg0 and its args are not opaque. Return 1: Boolean, whether FORMULA was altered." (multiple-value-bind (result changed?) (pass-through-if-logical-op function formula) (if changed? (values result t) (pass-through-if-bounded-existential function formula)))) (defun pass-through-if-relation-syntax (function formula) "[Cyc] Return 0: FORMULA with FUNCTION applied to all its terms (including the arg0) iff FORMULA is an EL formula with the syntax of a relation as its arg0 and its args are not opaque. Return 1: Boolean, whether FORMULA was altered." (multiple-value-bind (result changed?) (pass-through-if-logical-op-or-quantified function formula) (if changed? (values result t) (if (relation-syntax? formula) (values (nmap-formula-terms function formula) t) (values formula nil))))) (defun funcall-formula-arg (function formula argnum) "[Cyc] Calls FUNCTION on the ARGNUMth arg of FORMULA, unless that arg position is opaque." (let ((arg (formula-arg formula argnum))) (if (opaque-arg? formula argnum) arg (funcall function arg)))) (defun replace-formula-arg (argnum new-arg formula) "[Cyc] Replaces the ARGNUMth argument of FORMULA with NEW-ARG. This is constructive." (let ((new-terms nil) (seqvar (sequence-var formula)) (terms (formula-terms formula :ignore))) (dolistn (n arg terms) (push (if (eq n argnum) new-arg arg) new-terms)) (let* ((new-formula (nreverse new-terms)) (new-operator (formula-operator new-formula)) (new-args (formula-args new-formula))) (make-formula new-operator new-args seqvar)))) (defun nreplace-formula-arg (argnum new-arg formula) "[Cyc] Replaces the ARGNUMth argument of FORMULA with NEW-ARG. This is destructive." (let* ((seqvar (sequence-var formula)) (formula (if seqvar (missing-larkc 30665) formula)) (result (nreplace-nth argnum new-arg formula))) (if seqvar (missing-larkc 30614) result))) (defun literal-atomic-sentence (literal) "[Cyc] Returns the atomic formula within LITERAL. This will either be LITERAL itself or (if LITERAL is a negation) the atomic formula inside the negation. Assumes that LITERAL is a literal. (#$not . ?X) is not a literal." (when (el-formula-p literal) (if (el-negation-p literal) (formula-arg1 literal :regularize) literal))) (defun literal-truth (literal) (if (el-negation-p literal) :false :true)) (defun literal-sense (literal) (truth-sense (literal-truth literal))) (defun literal-args (literal &optional (seqvar-handling :ignore)) "[Cyc] Returns the arguments of LITERAL. Assumes that LITERAL is a literal. (#$not . ?X) is not a literal. If SEQVAR-HANDLING is :IGNORE, it chops off the sequence var if there is one. If SEQVAR-HANDLING is :REGULARIZE, it treats the sequence var as a regular variable. If SEQVAR-HANDLING is :INCLUDE, it returns it as a sequence var." (formula-args (literal-atomic-sentence literal) seqvar-handling)) (defun literal-arg (literal argnum &optional (seqvar-handling :ignore)) "[Cyc] Returns the ARGNUMth argument of LITERAL. An ARGNUM of 0 will return the predicate. Returns NIL if LITERAL is not a formula, or if ARGNUM is out of bounds or not an integer. Assumes that LITERAL is a literal. (#$not . ?X) is not a literal. If SEQVAR-HANDLING is :IGNORE, it will return NIL if asked for the arg position where the sequence variable is. If SEQVAR-HANDLING is :REGULARIZE, it will return the sequence variable if asked for its position. e.g. (literal-arg (<pred> <arg1> . ?SEQ) 2 :ignore) -> NIL but (literal-arg (<pred> <arg1> . ?SEQ) 2 :regularize) -> ?SEQ" (formula-arg (literal-atomic-sentence literal) argnum seqvar-handling)) (defun literal-predicate (literal &optional (seqvar-handling :ignore)) "[Cyc] Returns the predicate (the 0th argument) of LITERAL. For example, (literal-predicate (#$isa #$Muffet #$Dog)) would return #$isa. Assumes that LITERAL is a literal. (#$not . ?X) is not a literal." (literal-arg0 literal seqvar-handling)) (defun literal-arg0 (literal &optional (seqvar-handling :ignore)) "[Cyc] Returns the 0th argument (the predicate) of LITERAL. For example, (literal-arg0 (#$isa #$Muffet #$Dog)) would return #$isa. Assumes that LITERAL is a literal. (#$not . ?X) is not a literal." (declare (ignore seqvar-handling)) (formula-arg0 (literal-atomic-sentence literal))) (defun literal-arg1 (literal &optional (seqvar-handling :ignore)) "[Cyc] Returns the 1st argument of LITERAL. For example, (literal-arg1 (#$isa #$Muffet #$Dog)) would return #$Muffet. Assumes that LITERAL is a literal. (#$not . ?X) is not a literal." (literal-arg literal 1 seqvar-handling)) (defun literal-arg2 (literal &optional (seqvar-handling :ignore)) "[Cyc] Returns the 2nd argument of LITERAL. For example, (literal-arg2 (#$isa #$Muffet #$Dog)) would return #$Dog. Assumes that LITERAL is a literal. (#$not . ?X) is not a literal." (literal-arg literal 2 seqvar-handling)) (defun literal-arity (literal &optional (seqvar-handling :ignore)) "[Cyc] Returns the arity of a literal (the number of arguments). The predicate itself does not count as an argument. Assumes that LITERAL is a literal (#$not . ?X) is not a literal. For example, the arity of (#$not (#$isa #$Dog #$Collection)) would be 2, because there are 2 arguments, #$Dog and #$Collection. The #$not, if there is one, is ignored. If SEQVAR-HANDLING is :REGULARIZE, then sequence variables count as a single argument. Hence, (<pred> <form1> <form2> <form3>) is a literal of arity 3, and (<pred> <form1> <form2> <form3> . ?SEQ) is a literal of arity 4. If SEQVAR-HANDLING is :IGNORE, then sequence variables don't count, so both of those would be arity 3. Don't pass it :INCLUDE." (formula-arity (literal-atomic-sentence literal) seqvar-handling)) (defun asent-and-sense-to-literal (asent sense) (asent-and-truth-to-literal asent (sense-truth sense))) (defun asent-and-truth-to-literal (asent truth) (if (eq :false truth) (negate asent) asent)) (defun el-negative-sentences (sentences) "[Cyc] Returns all the negations in SENTENCES, which is a list of EL sentences." (remove-if-not #'el-negation-p sentences)) (defun el-positive-sentences (sentences) "[Cyc] Returns all the sentences in SENTENCES that are not negations. SENTENCES is a list of EL sentences." (remove-if #'el-negation-p sentences)) (defun unary-lit-p (literal) "[Cyc] Returns T iff LITERAL has exactly one argument. Assumes that LITERAL is a literal." (el-unary-formula-p (literal-atomic-sentence literal))) (defun binary-lit-p (literal) "[Cyc] Returns T iff LITERAL has exactly two arguments. Assumes that LITERAL is a literal." (el-binary-formula-p (literal-atomic-sentence literal))) (defun pred-lit? (literal pred) "[Cyc] Returns T iff LITERAL is positive and has PRED as its arg0. Returns NIL if LITERAL is negative or is not an EL formula." (and (el-formula-p literal) (not (el-negation-p literal)) (eq (literal-arg0 literal) pred))) (defun isa-lit? (lit) "[Cyc] Returns T iff LIT is a positive binary literal whose predicate is #$isa." (and (pred-lit? lit #$isa) (binary-lit-p lit))) (defun isa-hl-var-hl-var-lit? (lit) (and (pred-lit? lit #$isa) (binary-lit-p lit) (hl-variable-p (formula-arg1 lit)) (hl-variable-p (formula-arg2 lit)))) (defun quoted-isa-lit? (lit) "[Cyc] Returns T iff LIT is a positive binary literal whose predicate is #$quoted-isa." (and (pred-lit? lit #$quotedIsa) (binary-lit-p lit))) (defun genls-lit? (lit) "[Cyc] Returns T iff LIT is a positive binary literal whose predicate is #$genls." (and (pred-lit? lit #$genls) (binary-lit-p lit))) (defun tou-lit? (lit) "[Cyc] Returns T iff LIT is a positive binary literal whose predicate is #$termOfUnit." (and (pred-lit? lit #$termOfUnit) (binary-lit-p lit))) (defun tou-asent? (asent) "[Cyc] Returns T iff ASENT is a binary atomic sentence whose predicate is #$termOfUnit." (and (el-binary-formula-p asent) (atomic-sentence-with-pred-p asent #$termOfUnit))) (defun holds-in-lit? (literal) "[Cyc] Returns T iff LITERAL is a positive binary literal whose predicate is #$holdsIn." (and (pred-lit? literal #$holdsIn) (binary-lit-p literal))) (defun true-sentence-lit? (literal) "[Cyc] Returns T iff LITERAL is a positive unary literal whose predicate is #$trueSentence." (and (pred-lit? literal #$trueSentence) (unary-lit-p literal))) (defun forward-non-trigger-literal-lit? (literal) "[Cyc] Returns T iff LITERAL is a positive unary literal whose predicate is #$forwardNonTriggerLiteral." (and (pred-lit? literal #$forwardNonTriggerLiteral) (unary-lit-p literal))) (defun evaluate-lit? (literal &optional (var? 'cyc-var?)) "[Cyc] Returns T iff LITERAL is a positive binary literal whose predicate is #evaluate, whose arg1 is a variable, string, or number, and whose arg2 is a NAT." (and (pred-lit? literal #$evaluate) (binary-lit-p literal) (naut? (literal-arg2 literal)) (or (funcall var? (literal-arg1 literal)) (missing-larkc 30469)))) (defun ist-sentence-p (sentence) (and (possibly-sentence-p sentence) (eq #$ist (sentence-arg0 sentence)) (el-binary-formula-p sentence))) (defun ist-of-atomic-sentence-p (sentence) "[Cyc] Returns T iff SENTENCE is an #$ist around an atomic sentence." (ist-of-atomic-sentence-int sentence nil)) (defun ist-of-atomic-sentence-int (sentence pred) (declare (ignore pred)) (when (ist-sentence-p sentence) (missing-larkc 30501) ;; more body in the .java file if we're going to try to fill it in )) (defun ist-sentence-with-chlmt-p (sentence) (and (ist-sentence-p sentence) (chlmt-p (sentence-arg1 sentence)))) (defun true-sentence-p (sentence) (and (possibly-sentence-p sentence) (eq #$trueSentence (sentence-arg0 sentence)) (el-unary-formula-p sentence))) (defun true-sentence-of-atomic-sentence-p (sentence) "[Cyc] Returns T iff SENTENCE is a #$trueSentence around an atomic sentence." (when (true-sentence-p sentence) (let ((subsentence (sentence-arg1 sentence))) (when (possibly-sentence-p subsentence) (let ((predicate (sentence-arg0 subsentence))) (and (fort-p predicate) (predicate? predicate))))))) (defun kappa-asent-p (object) (and (possibly-atomic-sentence-p object) (kappa-predicate-p (atomic-sentence-predicate object)))) (defun kappa-predicate-p (object) (and (el-formula-with-operator-p object #$Kappa) (el-binary-formula-p object) (list-of-type-p #'el-var? (nat-arg1 object)))) (defun lambda-function-p (object) (and (el-formula-with-operator-p object #$Lambda) (el-binary-formula-p object) (list-of-type-p #'el-var? (nat-arg1 object)))) (defun mt-designating-literal? (literal) "[Cyc] Returns T iff LITERAL is a literal whose arg0 is a #$MicrotheoryDesignatingRelation." (with-all-mts (and (el-formula-p literal) (mt-designating-relation? (literal-arg0 literal))))) (defun valid-argnum-p (arg) "[Cyc] Returns T iff ARG could be a valid arg index for some formula, i.e. if (formula-arg <formula> ARG) is a sensible thing to try." (valid-arity-p arg)) (defun valid-arity-p (arity) "[Cyc] Returns T iff ARG could be a valid arity for some formula." (and (integerp arity) (>= arity 0))) (defun predicate-spec? (term &optional (var-func #'var-spec?)) "[Cyc] Returns T iff TERM is a predicate, a variable, or a NAT whose result is a predicate." (cond ((predicate? term) t) ((funcall var-func term) t) ((function-term? term) (let ((nat (reify-when-closed-naut term))) (if (fort-p nat) (predicate? nat) (missing-lakrc 3706)))))) (defun function-spec? (term &optional (var-func #'var-spec?)) "[Cyc] Returns T iff TERM is a denotational function, a variable, or a NAT whose result is a denotational function." (cond ((functor? term) t) ((funcall var-func term) t) ((function-term? term) (let ((nat (reify-when-closed-naut term))) (if (fort-p nat) (functor? nat) (missing-larkc 6974)))))) (defun hl-relation-expression? (object) "[Cyc] Returns T iff OBJECT is a nart." (nart-p object)) (defun relation-expression? (object) "[Cyc] Returns T iff OBJECT is either a nat or an EL formula with a predicate, variable, or logical operator as its arg0." (or (el-relation-expression? object) (hl-relation-expression? object))) (defun el-formula? (formula) "[Cyc] Returns T iff FORMULA is an EL formula with a predicate, variable, or logical operator as its arg0." (and (wf-wrt-sequence-vars? formula) (or (el-atomic-sentence? formula) (el-non-atomic-sentence? formula)))) (defun el-atomic-sentence? (formula) "[Cyc] Returns T iff FORMULA is an EL formula with a predicate (or variable) as its arg0." (atomic-sentence? formula)) (defun el-non-atomic-sentence? (formula) "[Cyc] Returns T iff FORMULA is an EL formula with a logical operator as its arg0." (and (el-formula-p formula) (logical-op? (formula-arg0 formula)))) (defun atomic-sentence? (object) "[Cyc] Returns T iff OBJECT is an EL formula with a predicate as its arg0." (and (el-formula-p object) (predicate-spec? (formula-arg0 object)) (relation-syntax? object))) (defun formula-non-var-symbols (formula &optional (var? #'cyc-var?)) (remove-if var? (flatten formula))) (defun referenced-variables (formula &optional (var? #'cyc-var?)) (formula-gather formula var?)) (defun literal-variables (relation &optional (var? #'cyc-var?) (include-sequence-vars? t)) (relation-variables relation var? include-sequence-vars?)) (defun relation-variables (literal &optional (var? #'cyc-var?) (include-sequence-vars? t)) (cond ((funcall var? literal) (list literal)) ((el-negation-p literal) (literal-variables (formula-arg1 literal) var?)) (t (let ((vars nil)) (dolistn (arg term (formula-terms literal (if include-sequence-vars? :regularize :ignore))) (cond ;; TODO - empty COND body again. ((member? term vars #'equal)) ((funcall var? term) (push term vars)) ((unreified-skolem-term? term) (push term vars)) ((naut? term) (missing-larkc 30622)) ((sentence? term) (missing-larkc 30652))) (incf arg)) ;; TODO - this can probably be nreverse? I don't think it shares structure with any input (reverse vars))))) (defun scoped-vars (formula &optional (var? #'cyc-var?)) (let ((relation (formula-operator formula)) (scoped-vars nil)) (when (fort-p relation) (dolist (position (scoping-args relation)) (let ((arg (formula-arg formula position))) (cond ;; TODO - this makes the funcall before checking for consp of arg? ((funcall var? arg) (push arg scoped-vars)) ((consp arg) (dolist (sub-arg (formula-terms arg)) (when (funcall var? sub-arg) (push sub-arg scoped-vars)))))))) (nreverse scoped-vars))) (defun wf-wrt-sequence-vars? (formula) "[Cyc] Returns T iff FORMULA has no ill-formed sequence variable syntax at the top level." (not (formula-with-sequence-non-var? formula))) (defun sentence-free-variables (sentence &optional bound-vars (var-func #'cyc-var?) (include-sequence-vars? t)) (if (and include-sequence-vars? (not (tree-find-if #'scoping-relation-p sentence)) (not (tree-find-if #'cycl-quoted-term-p sentence)) (not (tree-find-if #'expand-subl-fn-p sentence))) (set-difference (expression-gather sentence var-func) bound-vars) (sentence-free-variables-int sentence bound-vars var-func include-sequence-vars?))) (defun sentence-free-variables-int (sentence &optional bound-vars (var-func #'cyc-var?) (include-sequence-vars? t)) (cond ((and *inside-quote* (not (expression-find-if #'fast-escape-quote-term-p sentence))) nil) ((member? sentence bound-vars) nil) ((funcall var-func sentence) (list sentence)) ((atom sentence) nil) ((not (tree-find-if var-func sentence)) nil) ((el-negation-p sentence) (sentence-free-variables-int (sentence-arg1 sentence) bound-vars var-func include-sequence-vars?)) ((or (el-conjunction-p sentence) (el-disjunction-p sentence)) (let ((result nil)) (dolist (arg (sentence-args sentence (if include-sequence-vars? :regularize :ignore))) (dolist (var (sentence-free-variables-int arg bound-vars var-func include-sequence-vars?)) (pushnew var result))) result)) ((or (el-general-implication-p sentence) (el-exception-p sentence)) (let ((result (nreverse (sentence-free-variables-int (sentence-arg1 sentence) bound-vars var-func include-sequence-vars?)))) (dolist (var (sentence-free-variables-int (sentence-arg2 sentence) bound-vars var-func include-sequence-vars?)) (pushnew var result)) (nreverse result))) ((possibly-el-regularly-quantified-sentence-p sentence) (sentence-free-variables-int (quantified-sub-sentence sentence) (cons (quantified-var sentence) bound-vars) var-func include-sequence-vars?)) ((cycl-bounded-existential-sentence-p sentence) (let ((result (nreverse (sentence-free-variables-int (quantified-sub-sentence sentence) (cons (quantified-var sentence) bound-vars) var-func include-sequence-vars?))) (possible-var (missing-larkc 30558))) (when (cyc-var? possible-var) (push possible-var result)) (nreverse result))) ((mt-designating-literal? sentence) (missing-larkc 30484)) ((atomic-sentence? sentence) (literal-free-variables sentence bound-vars var-func include-sequence-vars?)) ((and (el-formula-p sentence) (funcall var-func (sentence-arg0 sentence))) (literal-free-variables sentence bound-vars var-func include-sequence-vars?)) (t (let ((result nil)) (dolist (var (formula-gather sentence var-func nil)) (unless (member? var bound-vars) (pushnew var result))) result)))) (defun literals-free-variables (literals &optional bound-vars (var? #'cyc-var?) (include-sequence-vars? t)) (let (variables) (cond ((consp literals) (dolist (literal literals) (setf variables (ordered-union variables (literal-free-variables literal bound-vars var? include-sequence-vars?))))) ((member? literals bound-vars) variables) ((funcall var? literals) (push literals variables)) (t variables)))) (defun literal-free-variables (literal &optional old-bound-vars (var? #'cyc-var?) (include-sequence-vars? t)) (relation-free-variables literal old-bound-vars var? include-sequence-vars?)) (defun relation-free-variables (relation &optional old-bound-vars (var? #'cyc-var?) (include-sequence-vars? t)) (cond ((subl-quote-p relation) nil) ((expand-subl-fn-p relation) (relation-free-variables (formula-arg1 relation) old-bound-vars var? include-sequence-vars?)) ((fast-escape-quote-term-p relation) (let ((*inside-quote* nil)) (relation-free-variables (formula-arg1 relation) old-bound-vars var? include-sequence-vars?))) ((member? relation old-bound-vars) nil) ((and (not *inside-quote*) (funcall var? relation)) (list relation)) ((fast-quote-term-p relation) (let ((*inside-quote* t)) (relation-free-variables (formula-arg1 relation) old-bound-vars var? include-sequence-vars?))) ((el-negation-p relation) (relation-free-variables (formula-arg1 relation) old-bound-vars var? include-sequence-vars?)) ((el-formula-p relation) (let* ((reln (formula-arg0 relation)) (new-bound-vars (scoped-vars relation var?)) (bound-vars (union old-bound-vars new-bound-vars)) (ans nil)) (dolistn (psn term (formula-terms relation (if include-sequence-vars? :regularize :ignore))) (cond ;; TODO - empty bodies mean do nothing on this pass? ((member? term bound-vars)) ((and (proper-list-p term) (subsetp term bound-vars))) ((and (not (and *within-query* *canonicalize-el-template-vars-during-queries?*)) (leave-variables-at-el-for-arg? reln psn))) ((and (not *inside-quote*) (funcall var? term)) (pushnew term ans)) ((and (within-tou-gaf?) (eq psn 2))) ((and (not *inside-quote*) (unreified-skolem-term? term)) (dolist (var (second term)) (when (and (not (member? var bound-vars)) (funcall var? var)) (pushnew var ans)))) ((naut? term) (dolist (var (missing-larkc 30620)) (pushnew var ans))) ((or (sentence? term) (and (expression-find-if #'scoping-relation-expression? term nil))) (dolist (var (sentence-free-variables-int term bound-vars var? include-sequence-vars?)) (pushnew var ans))) (*inside-quote*) (t (dolist (var (expression-gather term var?)) (unless (member? var bound-vars) (pushnew var ans)))))) (nreverse ans))))) (defun scoping-relation-expression? (expression) (when (relation-expression? expression) (let ((relation (formula-operator expression))) (scoping-relation-p relation)))) (defun arg-types-prescribe-unreified? (rel pos) "[Cyc] Do the arg-types applicable to arg POS of relation REL require the arg to be an unreified function?" (and (eq rel #$termOfUnit) (eq pos 2))) (deflexical *arg1-subl-list-relations* (list #$ExpandSubLFn #$SkolemFunctionFn #$SkolemFuncNFn #$Lambda #$Kappa #$initialSublists #$NestedDagFn #$SubDagFn #$UnifyFn #$DagFn)) (deflexical *arg2-subl-list-relations* (list #$initialSublists #$accessSlotForType #$ksImportationTemplate #$NestedDagFn #$SubDagFn #$UnifyFn)) (defun arg-types-prescribe-tacit-term-list? (rel pos) "[Cyc] Do the arg-types applicable to arg POS of relation REL> require the arg to be a SubL list? Note that SubL lists are deprecated except for special cases in the CycL grammar itself." (case pos (1 (member? rel *arg1-subl-list-relations*)) (2 (member? rel *arg2-subl-list-relations*)))) (defun el-error (level format-str &optional arg1 arg2 arg3) (cond ((>= *el-trace-level* level) (cerror "continue anyway" format-str arg1 arg2 arg3)) ((>= (+ 2 *el-trace-level*) level) (warn format-str arg1 arg2 arg3))))
69,469
Common Lisp
.lisp
1,324
44.426737
260
0.661824
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
4b7f0570e0f8cdfe6b219d6c3fb0ad8b1e5dfe7b84eb6c09657873232f355590
6,760
[ -1 ]
6,761
special-variable-state.lisp
white-flame_clyc/larkc-cycl/special-variable-state.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; This snapshots the values of special variables (defstruct (special-variable-state (:conc-name "SVS-")) variables values) (defun new-special-variable-state (special-variables) "[Cyc] Return a new SPECIAL-VARIABLE-STATE-P based on the current values for SPECIAL-VARIABLES." (let ((svs (make-special-variable-state :variables (copy-list special-variables) :values (make-list (length special-variables))))) (update-special-variable-state svs))) ;; TODO - weird naming convention, is this a macroexpansion? (defun* with-special-variable-state-variables (svs) (:inline t) (svs-variables svs)) (defun* with-special-variable-state-values (svs) (:inline t) (svs-values svs)) (defun update-special-variable-state (svs) "[Cyc] Update SPECIAL-VARIABLE-STATE SVS with the current binding values for all its special-variables." (update-special-variable-value-list (svs-values svs) (svs-variables-svs)) svs) (defun update-special-variable-value-list (values variables) "Performs a destructive update on the VALUES list, based on VARIABLES' values." (loop for variable in variables for rest-values on values do (rplaca rest-values (symbol-value variable))) values)
2,640
Common Lisp
.lisp
52
46.730769
106
0.760453
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
eb052a30bd8804393959b29b451048d71ee9dd6284d58247f6d342dd857dd932
6,761
[ -1 ]
6,762
constant-completion.lisp
white-flame_clyc/larkc-cycl/constant-completion.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; No macro declarations in original (defglobal *constant-names-in-code* nil) (defglobal *bogus-constant-names-in-code* nil) (defun initialize-constant-names-in-code () (when (zerop (constant-count)) (setf *constant-names-in-code* nil) (dolist (invalid-constant-name (invalid-constant-names)) (push invalid-constant-name *constant-names-in-code*))) (length *constant-names-in-code*)) (defun compute-bogus-constant-names-in-code () (when *constant-names-in-code* (noting-progress ("Computing bogus constant names in code...") (setf *bogus-constant-names-in-code* nil) (dolist (name *constant-names-in-code*) (when (uninstalled-constant-p (find-constant name)) (push name *bogus-constant-names-in-code*))) (setf *bogus-constant-names-in-code* (sort *bogus-constant-names-in-code* #'string<)))) (length *bogus-constant-names-in-code*))
2,294
Common Lisp
.lisp
45
47.066667
93
0.753597
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
60602a4ce9ecba354af6477164ff2b6dd684c8cec383b5fd4250dbe4ff2b7027
6,762
[ -1 ]
6,763
kb-control-vars.lisp
white-flame_clyc/larkc-cycl/kb-control-vars.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO - this file should probably go up pretty early in the load order (defglobal *backchain-forbidden-unless-arg-chosen* #$backchainForbiddenWhenUnboundInArg) (deflexical *kb-features* nil "[Cyc] The list of KB feature symbols") (defglobal *reformulator-kb-loaded?* nil) (defglobal *sksi-kb-loaded?* nil) (defglobal *paraphrase-kb-loaded?* nil) (defglobal *nl-kb-loaded?* nil) (defglobal *lexicon-kb-loaded?* nil) (defglobal *rtp-kb-loaded?* nil) (defglobal *rkf-kb-loaded?* nil) (defglobal *thesaurus-kb-loaded?* nil) (defglobal *quant-kb-loaded?* nil) (defglobal *time-kb-loaded?* nil) (defglobal *date-kb-loaded?* nil) (defglobal *cyc-task-scheduler-kb-loaded?* nil) (defglobal *wordnet-kb-loaded?* nil) (defglobal *cyc-secure-kb-loaded?* nil) (defglobal *planner-kb-loaded?* nil) (defglobal *kct-kb-loaded?* nil) (defun* kct-kb-loaded-p () (:inline t) "[Cyc] Is the portion of the KB necessary for KCTs loaded? There is currently no code analogue of this KB feature." *kct-kb-loaded?*) (defun* unset-kct-kb-loaded () (:inline t) (setf *kct-kb-loaded?* nil)) (defparameter *forward-inference-enabled?* t) (defparameter *forward-propagate-from-negation* nil "[Cyc] Do we allow forward propagation from negated gafs.") (defparameter *forward-propagate-to-negations* nil "[Cyc] Do we allow conclusion of negated fags in forward propagation.") (defparameter *within-forward-inference?* nil) (defun* within-forward-inference? () (:inline t) *within-forward-inference?*) (defparameter *within-assertion-forward-propagation?* nil) (defparameter *relax-type-restrictions-for-nats* nil) (defparameter *forward-inference-time-cutoff* nil "[Cyc] Amount of time we are willing to spend on each forward inference. NIL means unlimited time.") (defparameter *forward-inference-allowed-rules* :all "[Cyc] When a value other than :ALL, the list of the only rules allowed for forward inference.") (defparameter *forward-inference-environment* (create-queue) "[Cyc] Environment used for performing forward inference.") (defparameter *recursive-ist-justifications?* t "[Cyc] Do we give full justifications for ist gafs?") (defparameter *recording-hl-transcript-operations?* nil "[Cyc] Whether the HL storage modules should store the operations they perform") (defparameter *hl-transcript-operations* nil "[Cyc] A list of the operations noted by the HL storage modules") ;; TODO - these are probably part of a def* macro for the variables. Odd that flag names instead of values are put into a *features* value, but that's what the Java code seems to do. (toplevel (dolist (item '(*reformulator-kb-loaded?* *sksi-kb-loaded?* *paraphrase-kb-loaded?* *nl-kb-loaded?* *lexicon-kb-loaded?* *rtp-kb-loaded?* *rkf-kb-loaded?* *thesauraus-kb-loaded?* *quant-kb-loaded?* *time-kb-loaded?* *date-kb-loaded?* *cyc-task-scheduler-kb-loaded?* *wordnet-kb-loaded?* *cyc-secure-kb-loaded?* *planner-kb-loaded?* *kct-kb-loaded?* *forward-inference-environment*)) (pushnew item *kb-features*)))
4,690
Common Lisp
.lisp
94
44.680851
185
0.718134
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
9b1a2b0e03f42e656160b3300a9852a56808d0a550a3624d898c6a9fe0c8a86a
6,763
[ -1 ]
6,764
term.lisp
white-flame_clyc/larkc-cycl/term.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun el-fort-p (object) "[Cyc] Returns T iff OBJECT is a fort or an EL formula." (or (fort-p object) (null object) (el-formula-p object))) (defun kb-assertion? (object) (assertion-p object)) (defun kb-predicate? (symbol) (if (fort-p symbol) (predicate? symbol) (missing-larkc 31575))) (defun mt-designating-relation? (term) (and (fort-p term) (microtheory-designating-relation-p term))) (defun kb-relation? (object) (cond ((fort-p object) (relation? object)) ((naut? object) (missing-larkc 3707)))) (defun reified-skolen-term? (term) "[Cyc] e.g. (#$SKF-1234 #$Muffet" (and (el-formula-p term) (missing-larkc 31573))) (defun reified-skolem-fn-in-any-mt? (fn &optional robust? assume?) (when (fort-p fn) (or (skolem-function-p fn) (and robust? (or (pred-u-v-holds-in-any-mt #$isa fn #$SkolemFuncN) (pred-u-v-holds-in-any-mt #$isa fn #$SkolemFunction))) (and assume? (not (any-subhl-predicate-links-p fn #$isa)) (has-skolem-name? fn))))) (defun has-skolem-name? (fort) (cond ((constant-p fort) (let ((name (constant-name fort))) (when (stringp name) (starts-with name "SKF")))) ((nart-p fort) (has-skolem-name? (nat-functor fort))))) (defun fast-reified-skolem? (fort) (cond ((nart-p fort) (fast-reified-skolem? (nat-functor fort))) ((constant-p fort) (and (has-skolem-name? fort) (reified-skolem-fn-in-any-mt? fort))))) (defun fast-skolem-nart? (term) "[Cyc] Like skolem-nart except this assumes that all skolem functions begin with SKF." (when (nart-p term) (let ((functor (nat-functor term))) (when (has-skolem-name? functor) (missing-larkc 31578))))) (defun fast-skolem-nat? (term) "[Cyc] Like skolem-nart except this assumes that all skolem functions begin with SKF." (or (fast-skolem-nart? term) (and (naut-p term) (has-skolem-name? (nat-functor term))))) (defun unreified-skolem-term? (term) (unreified-skolem-fn-term? term)) (defun unreified-skolem-fn-term? (term) (when (and (proper-list-p term) (>= 5 (length term) 4)) (destructuring-bind (fn var-list var &optional seqvar num) term (declare (ignore seqvar num)) (and (skolem-fn-function? fn) (listp var-list) (el-var? var))))) (defun skolem-fn-function? (symbol) (member symbol *skolem-function-functions*)) (defun ground-naut? (naut &optional (var? #'cyc-var?)) (and (possibly-naut-p naut) (not (sequence-var naut)) (cons-tree-find-if var? naut) (naut? naut var?))) (defun hl-ground-naut? (object) "[Cyc} Returns whether OBJECT is a naut which is ground at the HL, i.e. contains no HL variables." (ground-naut? object #'variable-p)) (defun closed-naut? (object &optional (var? #'cyc-var?)) (and (naut? object var?) (closed? object var?))) (defun first-order-naut? (object) "[Cyc] is OBJECT a first-order non-atomic unreified term?" (and (possibly-naut-p object) (non-predicate-function? (nat-functor object)))) (defun naut? (nat &optional (var? #'el-var?)) (when (possibly-naut-p nat) (let* ((functor (nat-functor nat)) (naut? (funcall var? functor))) (or naut? (let ((*relevant-mt-function* 'relevant-mt-is-everything) (*mt* #$EverythingPSC)) (or (non-predicate-function? functor) (and (not (fort-p functor)) (missing-larkc 31568)))))))) (defun function-term? (term) "[Cyc] Return T iff TERM is a nat." (or (and (relation-syntax? term) (or (cyc-var? (nat-functor term)) (function-symbol? (nat-functor term))) (or (not *within-wff?*) (missing-larkc 31567))) (find-ground-naut term))) (defun function-symbol? (symbol) (if (fort-p symbol) (function? symbol) (represented-first-order-term? symbol))) (defun represented-first-order-term? (term) (and term (or (fort-p term) (cl-var? term) (function-term? term)))) (defun sentence? (formula &optional (var? #'el-var?)) (when (posibly-sentence-p formula) (let* ((predicate (formula-arg0 formula)) (sentence? (funcall var? predicate))) (or sentence? (let ((*relevant-mt-function* 'relevant-mt-is-everything) (*mt* #$EverythingPSC)) (or (sentential-relation-p predicate) (predicate? predicate) (isa-predicate? predicate))))))) (defun relation-syntax? (term &optional (var? #'cyc-var?)) (or (and *el-supports-dot-syntax?* (dotted-args? term var?) (wf-wrt-sequence-vars? term)) (proper-list-p term))) (defun dotted-args? (args &optional (var? #'cyc-var?)) (when (consp args) (let ((cdr (cdr args))) (cond ((consp cdr) (dotted-args? cdr var?)) ((null cdr) nil) (t (funcall var? cdr)))))) (defun var-spec? (object) (or (el-var? object) (kb-var? object) (permissible-keyword-var? object) (generic-arg-var? object) (unreified-skolem-term? object)))
6,658
Common Lisp
.lisp
162
34.648148
100
0.64268
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
964fbec73698f84540005b4ed307973032785787950d3f2bd9b54524b8aaa04a
6,764
[ -1 ]
6,765
arguments.lisp
white-flame_clyc/larkc-cycl/arguments.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; An abstraction over beliefs (asserted-arguments?) & deductions (defun valid-argument (argument &optional robust) "[Cyc] Return T if ARGUMENT is a valid argument. ROBUST requests more thorough checking." (or (belief-p argument) (and (deduction-p argument) (valid-deduction argument robust)))) (defun* argument-spec-type (argument-spec) (:inline t) "[Cyc] Returns the type of the argument specified by ARGUMENT-SPEC." (car argument-spec)) (deflexical *argument-types* (list :argument :belief :asserted-argument :deduction)) (deflexical *argument-type-hierarchy* '((:argument ()) (:belief (:argument)) (:asserted-argument (:belief)) (:deduction (:argument))) "[Cyc] A list of pairs of the form (ARGUMENT-TYPE list-of-proper-genls). Hardcodes the type hierarchy: ARGUMENT / \ BELIEF DEDUCTION / ASSERTED-ARGUMENT") (defun* argument-type-hierarchy () (:inline t) "[Cyc] A list of pairs of the form (ARGUMENT-TYPE list-of-proper-genls)." *argument-type-hierarchy*) (defun argument-type-proper-genls (argument-type) "[Cyc] Returns the proper genls of ARGUMENT-TYPE in the hard-coded hierarchy." (when-let ((pair (assoc argument-type (argument-type-hierarchy)))) (let* ((immediate-proper-genls (copy-list (second pair))) (recursive-proper-genls (mapcan #'argument-type-proper-genls immediate-proper-genls))) (append immediate-proper-genls recursive-proper-genls)))) (defun* argument-type-genls (argument-type) (:inline t) "[Cyc] Returns the genls of ARGUMENT-TYPE in the hard-coded hierarchy." (cons argument-type (argument-type-proper-genls argument-type))) (defun argument-truth (argument) "[Cyc] Return the truth of ARGUMENT." (if (belief-p argument) (belief-truth argument) (deduction-truth argument))) (defun argument-tv (argument) "[Cyc] Return the HL tv of ARGUMENT." (if (belief-p argument) (belief-tv argument) (tv-from-truth-strength (deduction-truth argument) (deduction-strength argument)))) (defun argument-strength (argument) "[Cyc] Return the strength of ARGUMENT." (if (belief-p argument) ;; TODO - belief-strength (missing-larkc 31879) (deduction-strength argument))) (defun remove-argument (argument assertion) "[Cyc] Remove ARGUMENT from the KB, and unhook it from ASSERTION." (if (belief-p argument) (remove-belief argument assertion) (kb-remove-deduction argument))) (defun* belief-p (object) (:inline t) "[Cyc] Return T iff OBJECT is an HL belief structure." (asserted-argument-p object)) (defun* remove-belief (belief assertion) (:inline t) (kb-remove-asserted-argument assertion belief)) (defun* belief-truth (belief) (:inline t) (asserted-argument-truth belief)) (defun* belief-tv (belief) (:inline t) (asserted-argument-tv belief)) (defun* asserted-argument-p (object) (:inline t) "[Cyc] Return T iff OBJECT is an HL asserted argument structure." (asserted-argument-token-p object)) (defun* create-asserted-argument (assertion tv) (:inline t) "[Cyc] Create an asserted argument for ASSERTION with TV." (declare (ignore assertion)) ;; TODO - doesn't this need the assertion? (asserted-argument-token-from-tv tv)) (defun* create-asserted-argument-spec (strength-spec) (:inline t) (list :asserted-argument strength-spec)) (defun* asserted-argument-spec-strength-spec (asserted-argument-spec) (:inline t) (second asserted-argument-spec)) (defun* kb-remove-asserted-argument-internal (asserted-argument) (:inline t) (declare (ignore asserted-argument)) nil) (deflexical *asserted-argument-tv-table* '((:asserted-true-mon :true-mon) (:asserted-true-def :true-def) (:asserted-unknown :unknown) (:asserted-false-def :false-def) (:asserted-false-mon :false-mon)) "[Cyc] Asserted argument -> HL TV mapping.") (deflexical *asserted-arguments* (mapcar #'first *asserted-argument-tv-table*) "[Cyc] Tokens representing the possible asserted arguments.") (defun* asserted-argument-tokens () (:inline t) *asserted-arguments*) (defun* asserted-argument-token-p (object) (:inline t) (member? object *asserted-arguments* #'eq)) (defun* asserted-argument-token-from-tv (tv) (:inline t) (car (find tv *asserted-argument-tv-table* :test #'eq :key #'second))) (defun* tv-from-asserted-argument-token (asserted-argument) (:inline t) (second (find asserted-argument *asserted-argument-tv-table* :test #'eq :key #'first))) (defun asserted-argument-tv (asserted-argument) (when (asserted-argument-token-p asserted-argument) (tv-from-asserted-argument-token asserted-argument))) (defun* asserted-argument-truth (asserted-argument) (:inline t) (tv-truth (asserted-argument-tv asserted-argument))) (defun support-p (object) "[Cyc] Return T iff OBJECT can bea support in an argument." (or (assertion-p object) (kb-hl-support-p object) (hl-support-p object))) (defun valid-support? (support &optional robust) "[Cyc] Return T if SUPPORT is a valid KB deduction support. ROBUST requests more thorough checking." (cond ((assertion-p support) (valid-assertion-p support)) ((kb-hl-support-p support) (valid-kb-hl-support? support robust)) ;; TODO - valid-hl-support-p or valid-hl-support? ((hl-support-p support) (missing-larkc 31885)))) (defun support-equal (support1 support2) (cond ((or (assertion-p support1) (assertion-p support2) (kb-hl-support-p support1) (kb-hl-support-p support2)) (eq support1 support2)) (t (equal support1 support2)))) (defun support-< (support1 support2) "[Cyc] Imposes an arbitrary but consistent total order between supports." (cond ((assertion-p support1) (if (assertion-p support2) (if (rule-assertion? support1) (if (rule-assertion? support2) (< (assertion-id support1) (assertion-id support2)) t) (if (rule-assertion? support2) nil (< (assertion-id support1) (assertion-id support2)))) t)) ((kb-hl-support-p support1) (cond ((assertion-p support2) nil) ((kb-hl-support-p support2) (< (kb-hl-support-id support1) (kb-hl-support-id support2))) (t t))) ((or (assertion-p support2) (kb-hl-support-p support2)) nil) (t (term-< support1 support2)))) (deflexical *assertion-support-module* :assertion "[Cyc] The module which denotes that an assertion is the support.") (defun support-module (support) "[Cyc] Return the module of SUPPORT." (cond ((assertion-p support) *assertion-support-module*) ((kb-hl-support-p support) (missing-larkc 11038)) (t (hl-support-module support)))) (defun support-sentence (support) "[Cyc] Return the sentence of SUPPORT." (cond ((assertion-p support) (assertion-formula support)) ((kb-hl-support-p support) (kb-hl-support-sentence support)) (t (hl-support-sentence support)))) (defun* support-formula (support) (:inline t) (support-sentence support)) (defun support-mt (support) "[Cyc] Return the microtheory of SUPPORT." (cond ((assertion-p support) (assertion-mt support)) ((kb-hl-support-p support) (missing-larkc 11039)) (t (hl-support-mt support)))) (defun* support-strength (support) (:inline t) "[Cyc] Return the strength of SUPPORT." (tv-strength (support-tv support))) (defun support-tv (support) (cond ((assertion-p support) (cyc-assertion-tv support)) ((kb-hl-support-p support) (kb-hl-support-tv support)) (t (hl-support-tv support)))) (defun canonicalize-supports (supports &optional (possibly-create-new-kb-hl-supports? t)) "[Cyc] Return a sorted list of canonicalized supports. This is not destructive." (sort (loop for support in supports collect (canonicalize-support support possibly-create-new-kb-hl-supports?)) #'support-<)) (defun canonicalize-support (support &optional (possibly-create-new-kb-hl-supports? t)) "[Cyc] Canonicalize SUPPORT. If SUPPORT is an assertion or KB HL support, this simply returns SUPPORT. Otherwise,t eh function attempts to find a KB HL support for SUPPORT or, if POSSIBLY-CREATE-NEW-KB-HL-SUPPORT? is non-NIL, it may create a new one." (if (or (assertion-p support) (kb-hl-support-p support)) support (canonicalize-hl-support support possibly-create-new-kb-hl-supports?))) (defun canonicalize-hl-support (hl-support &optional (possibly-create-new-kb-hl-supports? t)) (or (assertion-from-hl-support hl-support) (if possibly-create-new-kb-hl-supports? (find-or-possibly-create-kb-hl-support hl-support) (find-kb-hl-support hl-support)) hl-support)) (defun hl-support-p (object) "[Cyc] Does OBJECT represent an HL support?" (and (listp object) (proper-list-p object) (length= object 4) (hl-support-module-p (car object)))) ;; Make some readers. At least the java doesn't define any SET- functions. (defstruct (hl-support (:type list) (:constructor nil)) module sentence mt tv) (defun make-hl-support (hl-module sentence &optional (mt *mt*) (tv :true-def)) "[Cyc] Construct a new HL support." (list hl-module sentence mt tv)) (defun assertion-from-hl-support (hl-support) (when (eq (hl-support-module hl-support) *assertion-support-module*) (find-assertion-cycl (hl-support-sentence hl-support) (hl-support-mt hl-support)))) (defun non-empty-hl-justification-p (object) (and (proper-list-p object) (every-in-list #'support-p object))) (defun* justification-equal (justification1 justification2) (:inline t) (multisets-equal? justification1 justification2 #'support-equal)) (defun* canonicalize-hl-justification (hl-justification) (:inline t) (sort (copy-list hl-justification) #'support-<))
12,124
Common Lisp
.lisp
247
41.214575
253
0.663872
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
8a61e21da5b7221eec485edfc9c40c287af5551d461b3ef9c19c5a2c65c4d61b
6,765
[ -1 ]
6,766
api-kernel.lisp
white-flame_clyc/larkc-cycl/api-kernel.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO - this will not work as send-api-result is missing-larkc, but can be reconstituted. (defun api-server-handler (in-stream out-stream) (api-server-top-level in-stream out-stream)) (defparameter *within-api-server* nil) (defun api-server-top-level (in-stream out-stream) (let ((*package* (find-package "CLYC")) (*read-default-float-format* 'double-float) (*print-readably* nil) (*read-eval* nil) (*within-api-server* t)) (catch :api-quit (api-server-loop in-stream out-stream)))) (defun api-quit () "[Cyc] Explicitly quit this API connection." (when *within-api-server* (throw :api-quit nil))) (defparameter *default-api-input-protocol* 'default-api-input-protocol "[Cyc] The default API input protocol to use.") (defparameter *api-input-protocol* *default-api-input-protocol*) (defparameter *default-api-validate-method* 'default-api-validate-api-request "[Cyc] The default API input validator to use.") (defparameter *api-validate-method* *default-api-validate-method* "[Cyc] When non-NIL, a function which is called to validate any API request before evaluation.") (deflexical *default-api-result-method* nil) (defparameter *api-result-method* *default-api-validate-method* "[Cyc] When non-NIL, a function which is called to transform any API result before returning the output.") (defparameter *default-api-output-protocol* 'default-api-output-protocol "[Cyc] The default API output protocol to use.") (defparameter *api-output-protocol* *default-api-output-protocol*) (defparameter *api-in-stream* nil "[Cyc] The API input stream (for use by the java-api-kernel).") (defparameter *api-out-stream* nil "[Cyc] The API output stream (for use by the java-api-kernel).") (defun api-server-loop (in-stream out-stream) (let ((*use-local-queue?* nil) (*the-cyclist* (the-cyclist)) (*ke-purpose* *default-ke-purpose*) (*api-in-stream* in-stream) (*api-out-stream* out-stream) (*api-input-protocol* *default-api-input-protocol*) (*api-validate-method* *default-api-validate-method*) (*api-result-method* *default-api-result-method*) (*api-output-protocol* *default-api-output-protocol*) (*eval-in-api-env* (initialize-eval-in-api-env)) (*eval-in-api-traced-fns* nil) (*eval-in-api-trace-log* "") (*ignore-warns?* t) (*ignore-breaks?* t) (*silent-progress?* t) (*continue-cerror?* t) (*standard-output* *null-output*) (*error-output* *null-output*)) (while t (api-server-one-complete-request in-stream out-stream)))) (defun api-server-one-complete-request (in-stream out-stream) (let ((error-message nil) (api-request nil) (api-result nil)) (setf-error error-message (setf api-request (read-api-request in-stream)) (validate-api-request api-request) (record-api-request api-request)) (if (eq 'task-processor-request (car api-request)) (progn (bt:with-lock-held (*api-task-process-pool-lock*) (unless (api-task-processors-initialized-p) (initialise-api-task-processors))) (destructuring-bind (function request id priority requestor client-bindings uuid-string) api-request (declare (ignore function)) (task-processor-request request id priority requestor client-bindings uuid-string))) (progn (unless error-message (setf-error error-message (setf api-result (perform-api-request api-request)))) (if error-message (progn (send-api-result out-stream error-message t) (record-api-result error-message t)) (progn (send-api-result out-stream api-result nil) (record-api-result api-result nil))) (update-api-protocol))))) (defglobal *api-input-eof-marker* (make-symbol "API Input EOF Marker")) (defun read-api-request (in-stream) (let ((request (funcall (api-input-protocol) in-stream nil *api-input-eof-marker*))) (when (eq request *api-input-eof-marker*) (api-quit)) request)) (defun validate-api-request (api-request) (if *api-validate-method* (funcall *api-validate-method* api-request) t)) (defun valid-api-function-symbol (symbol) (and (symbolp symbol) (fboundp symbol))) (defparameter *record-api-messages?* nil) (defparameter *api-message-sink* nil "[Cyc] Either a list or a stream. If a list, the messages are stuck on the list. If a stream, the messages are output to it.") (defun record-api-request (api-request) (when *record-api-messages?* (let ((sink *api-message-sink*)) (cond ((streamp sink) (progn (prin1 api-request sink) (terpri sink) (force-output sink))) ((listp sink) (push api-request *api-message-sink*)))))) (defun record-api-result (result error?) (when *record-api-messages?* (let ((sink *api-message-sink*)) (cond ((streamp sink) (default-api-output-protocol sink result error?)) ((listp sink) (push (list error? result) *api-message-sink*)))))) (defun perform-api-request (api-request) (reset-fi-error-state) (let ((result (cyc-api-eval api-request))) (when (fi-error-signaled?) (missing-larkc 11154)) (if *api-result-method* (funcall *api-result-method* result) result))) (defun send-api-result (out-stream api-result error?) "[CYc] Send API-RESULT to OUT-STREAM respecting ERROR?" ;; TODO - this contained a nonsensical (+ 1 2)? ;; TODO - should be easy to reimplement, likely api-output-protocol? don't want to edit it in in translation yet though (on-error (funcall (missing-larkc 31555) out-stream api-result error?) (api-quit))) (defparameter *api-success-code* 200) (defparameter *api-error-code* 500) (defun default-api-output-protocol (out-stream api-result &optional error?) (let ((result-code (if error? *api-error-code* *api-success-code*))) (format out-stream "~d ~s" result-code api-result)) (missing-larkc 7458) ;;(force-output out-stream) api-result) (defparameter *new-api-input-protocol* nil) (defparameter *new-api-output-protocol* nil) (defun update-api-protocol () (when (and *new-api-input-protocol* *new-api-output-protocol*) (set-api-input-protocol *new-api-input-protocol*) (set-api-output-protocol *new-api-output-protocol*) (setf *new-api-input-protocol* nil) (setf *new-api-output-protocol* nil))) (defun set-api-input-protocol (input-protocol) (setf *api-input-protocol* input-protocol)) (defun set-api-output-protocol (output-protocol) (setf *api-output-protocol* output-protocol)) (defun api-port () "[Cyc] Returns the local api-port according to defined system parameters." (+ *base-tcp-port* *fi-port-offset*)) (deflexical *cyc-api-eof-exception* :eof)
8,445
Common Lisp
.lisp
181
40.646409
130
0.686368
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
ba9b2ec7d96b0f9818db26609dd290e25ef1943d3d3afe71cbe883aeefae2834
6,766
[ -1 ]
6,767
nart-handles.lisp
white-flame_clyc/larkc-cycl/nart-handles.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (file "nart-handles") (defglobal *nart-from-id* nil "[Cyc] The ID -> NART mapping table.") (defun* do-narts-table () (:inline t) *nart-from-id*) (defun setup-nart-table (size exact?) (declare (ignore exact?)) (unless *nart-from-id* (setf *nart-from-id* (new-id-index size 0)) t)) (defun finalize-narts (&optional max-nart-id) (set-next-nart-id max-nart-id) (unless max-nart-id (missing-larkc 30878))) (defun* clear-nart-table () (:inline t) (clear-id-index *nart-from-id*)) (defun nart-count () "[Cyc] Return the total number of NARTs." (if *nart-from-id* (id-index-count *nart-from-id*) 0)) (defun* lookup-nart (id) (:inline t) (id-index-lookup *nart-from-id* id)) (defun* new-nart-id-threshold () (:inline t) "[Cyc] Return the internal ID where new NARTs started." (id-index-new-id-threshold *nart-from-id*)) ;; The inner loop seems to have an unconditional missing-larkc, and doesn't seem to be called anyway. However, it shouldn't be hard to complete, as we have the intent message and funcname. '(defun set-next-nart-id (&optional max-nart-id) ;; TODO - this is a macroexpansion that optionally skips over tombstones. There's do-narts, do-old-narts, and do-new-narts declared, whose expansion this likely is. (let* ((max (or max-nart-id -1)) (idx (do-narts-table)) (mess "Determining maximum NART ID") (total (id-index-count idx)) (sofar 0)) (noting-percent-progress (mess) (unless (id-index-objects-empty-p idx :skip) (dovector (id nart (id-index-old-objects idx)) ()))))) (defun register-nart-id (nart id) "[Cyc] Note that ID will be used as the id for NART." (reset-nart-id nart id) (id-index-enter *nart-from-id* id nart) nart) (defstruct (nart (:conc-name "N-")) id) (defmethod sxhash ((object nart)) (let ((id (n-id object))) (if (integerp id) id 0))) (defun* get-nart () (:inline t) "[Cyc] Make a new nart shell, potentially in static space." (make-nart)) (defun valid-nart-handle? (object) "[Cyc] Return T iff OBJECT is a valid NART handle." (and (nart-p object) (missing-larkc 30862))) (defun make-nart-shell (&optional id) (unless id (missing-larkc 30861)) (let ((nart (get-nart))) (register-nart-id nart id) nart)) (defun create-sample-invalid-nart () "[Cyc] Create a sample invalid NART." (get-nart)) ;; TODO - uses same macroexpansion as set-next-nart-id, with the missing-larkc '(defun free-all-narts () ) (defun* reset-nart-id (nart new-id) (:inline t) "[Cyc] Primitively change the internal id for NART to NEW-ID." (setf (n-id nart) new-id) nart) (defun* find-nart-by-id (id) (:inline t) (lookup-nart id))
4,121
Common Lisp
.lisp
100
37.59
189
0.708438
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
2dba8a07b8c92bda00f571ab49759b819eb9fd95238798dee4a2d0bf6f1d010e
6,767
[ -1 ]
6,768
kb-macros.lisp
white-flame_clyc/larkc-cycl/kb-macros.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defparameter *forts-being-removed* nil "[Cyc] A list of forts which we are in the process of removing.") (defun some-fort-being-removed? () "[Cyc] Return T iff we are in the process of removing some fort." *forts-being-removed*)
1,636
Common Lisp
.lisp
32
47.75
77
0.775316
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
e73c62c0465c0bd45ee54661b09cb51ab600f6ebbc4d91acfdc885b1c161ccd9
6,768
[ -1 ]
6,769
constant-reader.lisp
white-flame_clyc/larkc-cycl/constant-reader.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; Clyc hoists this file up earlier in the load order, so that the #$ is available everywhere. ;; This also splits up the behavior between read-time capturing of the name, and macro-expansion time resolving of the name, which defers this code from needing its dependencies compiled in. ;; Initial external dependencies: ;; simple-reader-error ;; valid-constant-name-char-p ;; *read-suppress* ;; reader-make-constant-shell ;; *read-require-constant-exists* ;; constant-complete-exact-name ;; find-invalid-constant (defconstant *constant-reader-macro-char* #\$ "[Cyc] The character that signals the reader that what follows is to be treated as a CycL constant name.") (defun constant-reader-macro-char () "[Cyc] Returns the character that signals the reader that what follows is to be treated as a CycL constant name." *constant-reader-macro-char*) (defconstant *constant-reader-prefix* (format nil "#~c" *constant-reader-macro-char*) "[Cyc] The string that prefixes all CycL constant names") (declaim (inline stream-forbids-constant-creation)) (defun stream-forbids-constant-creation (stream) "[Cyc] Return T iff STREAM forbids the creation of constant shells for unknown constants." (declare (ignore stream)) ;; TODO DESIGN - surely some test should happen on the stream. Differentiate fundamental .lisp code from user streams. *read-require-constant-exists*) ;; TODO DESIGN - Compile-time side effects, like filling in the trie of constant names, do not get saved through to load time. The biggest issue is that we can't easily use #$ in the fundamental source code to define constants at compile-time with this setup, although it would work for interactive use after the system is up and running. For now, constants will be resolved at runtime. Later, we could try performing existence checks at load-time, but we have to ensure that the world has been loaded first. (defun sharpsign-dollar-rmf (stream ch arg) (when arg (simple-reader-error "The ~s reader macro does not take an argument." ch)) (let ((buffer (make-array '(64) :element-type 'character :adjustable t :fill-pointer 0))) (loop for next = (peek-char nil stream nil nil) while (and next (valid-constant-name-char-p next)) do (vector-push-extend (read-char stream) buffer)) (if *read-suppress* (values nil t) (let* (;; Copy from adjustable vector to a plain one (name (subseq buffer 0))) (values (or (reader-make-constant-shell name (not (stream-forbids-constant-creation stream))) (error "~s is not an existing constant" name)) t))))) (defun find-constant-by-name (name) (let ((constant (let ((*require-valid-constants* nil)) (constant-complete-exact name)))) (or constant (find-invalid-constant name)))) ;; Make a contained readtable, instead of mutating the global one '(named-readtables:defreadtable clyc (:merge :standard) (:dispatch-macro-char #\# *constant-reader-macro-char* #'sharpsign-dollar-rmf)) ;; TODO HACK - remove this later, use the named-readtable instead to scope subl-ish code (set-dispatch-macro-character #\# #\$ #'sharpsign-dollar-rmf) (defmethod make-load-form ((obj constant) &optional environment) (declare (ignore environment)) "Common Lisp support for constant literals in source code." ;; This is always allowed to create constants? `(reader-make-constant-shell ,(c-name obj) t))
4,919
Common Lisp
.lisp
82
55.256098
511
0.737917
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
d7c3c14e89bd13d865bed5d8dfedbcf810a9f790f2f5cfa18a93da3c010b343e
6,769
[ -1 ]
6,770
subl-promotions.lisp
white-flame_clyc/larkc-cycl/subl-promotions.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun function-symbol-p (obj) "[Cyc] Return T iff OBJECT is a symbol with a function definition." (and (symbolp obj) (fboundp obj))) (defun function-symbol-arglist (function-symbol) "[Cyc] Return the arglist of FUNCTION-SYMBOL" #+sbcl (sb-impl::%fun-lambda-list (symbol-function function-symbol)) #-sbcl (error "FUNCTION-SYMBOL-ARGLIST unimplemented in this CL implementation")) ;; PERFORMANCE - instead of suboptimal RSUBLIS custom implementations, just reverse the alist. However, this means macros instead of functions to take advantage of compiler optimizations (defun reverse-alist-pairs (alist) "Reverses each entry from (KEY . VALUE) to (VALUE . KEY)" (mapcar (lambda (cons) (cons (cdr cons) (car cons))) alist)) (defmacro rsublis (alist &rest rest) "[Cyc] Like SUBLIS except ALIST is interpreted as (VALUE . KEY) pairs" `(sublis (reverse-alist-pairs ,alist) ,@rest)) (defmacro nrsublis (alist &rest rest) "[Cyc] Like NSUBLIS except ALIST is interpreted as (VALUE . KEY) pairs" `(nsublis (reverse-alist-pairs ,alist) ,@rest)) (defun elapsed-universal-time (past-time &optional (current-time (get-universal-time))) (- current-time past-time)) (defun ensure-physical-pathname (pathname) "[Cyc] Convert PATHNAME to a physical pathname (performing any logical pathname translations)" (truename pathname)) (defmacro member? (item list &optional (test '#'eql) (key '#'identity)) `(member ,item ,list ,@(and test `(:test ,test)) ,@(and key `(:key ,key)))) ;; PERFORMANCE - do we assume fixnum for subl-level code? (defun* positive-integer-p (obj) (:inline t) (typep obj '(integer 1))) (defun* non-negative-integer-p (obj) (:inline t) (typep obj '(integer 0)))
3,160
Common Lisp
.lisp
63
46.492063
187
0.742009
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
eac4a47ba5ec877eae44dd61c02889f51f31099233d362e900c860d791e099d8
6,770
[ -1 ]
6,771
nart-hl-formula-manager.lisp
white-flame_clyc/larkc-cycl/nart-hl-formula-manager.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defglobal *nart-hl-formula-manager* :uninitialized "[Cyc] The KB object manager for nart-hl-formlas.") (deflexical *nart-hl-formula-lru-size-percentage* 5 "[Cyc] A wild guess.") (defun setup-nart-hl-formula-table (size exact?) (setf *nart-hl-formula-manager* (new-kb-object-manager "nart-hl-formula" size *nart-hl-formula-lru-size-percentage* #'load-nart-hl-formula-from-cache exact?))) (defun clear-nart-hl-formula-table () (clear-kb-object-content-table *nart-hl-formula-manager*)) (defun* cached-nart-hl-formula-count () (:inline t) "[Cyc] Return the number of nart-hl-formulas whose content is cached in memory." (cached-kb-object-count *nart-hl-formula-manager*)) (defun nart-hl-formulas-unbuilt? () (unless (zerop (nart-count)) (kb-object-manager-unbuilt? *nart-hl-formula-manager*))) (defun swap-out-all-pristine-nart-hl-formulas () (swap-out-all-pristine-kb-objects-int *nart-hl-formula-manager*)) (defun initialize-nart-hl-formula-hl-store-cache () (initialize-kb-object-hl-store-cache *nart-hl-formula-manager* "nart-hl-formula" "nart-hl-formula-index")) (defglobal *nart-hl-formula-table* nil)
2,843
Common Lisp
.lisp
52
45.942308
94
0.682098
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
573d1ba4b0df5e73eaa714933f2a201c3815a8f2c815d336760fe1fb7dee4446
6,771
[ -1 ]
6,772
kb-mapping.lisp
white-flame_clyc/larkc-cycl/kb-mapping.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO - all the gather-* functions cons up lists & deduplicate them. A faster, less gc pressure way of iterating? (defparameter *mapping-function* nil) (defparameter *mapping-truth* nil) (defparameter *mapping-direction* nil) (defun map-nart-arg-index (subl-function term &optional argnum cycl-function) "Apply FUNCTION to each #$termOfUnit assertion whose arg2 is a naut which mentions TERM in position ARGNUM." (catch :mapping-done (cond ((and argnum cycl-function) ;; TODO - iteration macro (when (do-nart-arg-index-key-validator term argnum cycl-function) (let ((iterator-var (new-nart-arg-final-index-spec-iterator term argnum cycl-function)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator nil)) (unwind-protect (progn (setf final-index-iterator (new-final-index-iterator final-index-spec :gaf nil nil)) (let ((done-var-25 nil) (token-var-26 nil)) (until done-var-25 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-26)) (valid-27 (not (eq token-var-26 ass)))) (when valid-27 (funcall subl-function ass)) (setf done-var-25 (not valid-27)))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator))))) (setf done-var (not valid))))))) ((and argnum (not cycl-function)) (when (do-nart-arg-index-key-validator term argnum nil) (let ((iterator-var (new-nart-arg-final-index-spec-iterator term argnum nil)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator nil)) (unwind-protect (progn (setf final-index-iterator (new-final-index-iterator final-index-spec :gaf nil nil)) (let ((done-var-28 nil) (token-var-29 nil)) (until done-var-28 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-29)) (valid-30 (not (eq token-var-29 ass)))) (when valid-30 (funcall subl-function ass)) (setf done-var-28 (not valid-30)))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator))))) (setf done-var (not valid))))))) ((and (not argnum) cycl-function) (when (do-nart-arg-index-key-validator term nil cycl-function) (let ((iterator-var (new-nart-arg-final-index-spec-iterator term nil cycl-function)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :gaf nil nil))) (unwind-protect (let ((done-var-31 nil) (token-var-32 nil)) (until done-var-31 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-32)) (valid-33 (not (eq token-var-32 ass)))) (when valid-33 (funcall subl-function ass)) (setf done-var-31 (not valid-33))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid))))))) ((and (not argnum) (not cycl-function)) (when (do-nart-arg-index-key-validator term nil nil) (let ((iterator-var (new-nart-arg-final-index-spec-iterator term nil nil)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :gaf nil nil))) (unwind-protect (let ((done-var-34 nil) (token-var-35 nil)) (until done-var-34 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-35)) (valid-36 (not (eq token-var-35 ass)))) (when valid-36 (funcall subl-function ass)) (setf done-var-34 (not valid-36))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid)))))))))) (defun map-predicate-rule-index (function pred sense &optional direction mt) (catch :mapping-done (possibly-with-just-mt (mt) (if direction ;; TODO - macro helper instance (when (do-predicate-rule-index-key-validator pred sense direction) (let ((iterator-var (new-predicate-rule-final-index-spec-iterator pred sense direction)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator nil)) (unwind-protect (progn (setf final-index-iterator (new-final-index-iterator final-index-spec :rule nil direction)) (let ((done-var-37 nil) (token-var-38 nil)) (until done-var-37 ;; macro var (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-38)) (valid-39 (not (eq token-var-38 ass)))) (when valid-39 ;; macro body (funcall function ass)) (setf done-var-37 (not valid-39)))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator))))) (setf done-var (not valid)))))) ;; TODO - another macro helper instance, different iteration via direction decision above (when (do-predicate-rule-index-key-validator pred sense nil) (let ((iterator-var (new-predicate-rule-final-index-spec-iterator pred sense nil)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator nil)) (unwind-protect (progn (setf final-index-iterator (new-final-index-iterator final-index-spec :rule nil nil)) (let ((done-var-41 nil) (token-var-42 nil)) (until done-var-41 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-42)) (valid-43 (not (eq token-var-42 ass)))) (when valid-43 (funcall function ass)) (setf done-var-41 (not valid-43)))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator))))) (setf done-var (not valid)))))))))) (defparameter *map-term-selective-test* nil) (defparameter *map-term-selective-action* nil) (defun map-mt-contents (function term &optional truth gafs-only) "[Cyc] Apply FUNCTION to each assertion with TRUTH in MT TERM. If TRUTH is NIL, all assertions are mapped. If GAFS-ONLY, then only gafs are mapped." (when (fort-p term) (if (broad-mt? term) (when (relevant-mt? term) (let ((*mapping-truth* truth)) (catch :mapping-done ;; TODO - more macro expansion that isn't part of noting-percent-progress? the totl & sofar seem to be part of calculating percentage? (let* ((idx (do-assertions-table)) (total (id-index-count idx)) (sofar 0)) (noting-percent-progress ("mapping broad mt index") ;; TODO - more macroexpansions, re gensym'd variables, but this is missing-larkc anyway (let ((idx-120 idx)) (unless (id-index-objects-empty-p idx-120 :skip) ;; peer 1 code, old objects? this is an id-index structure (let ((idx-121 idx-120)) (unless (id-index-old-objects-empty-p idx-121 :skip) ;; likely gensyms as well (let* ((vector-var (id-index-old-objects idx-121)) (backward?-var nil) (length (length vector-var))) (loop for iteration from 0 below length ;; TODO - slower than doing a different iteration, or precalculating a +1/-1 delta do (let* ((id (if backward?-var ;; backward?-var is likely a macro-generated constant (- length iteration 1) iteration)) (assertion (aref vector-var id))) (unless (and (id-index-tombstone-p assertion) (id-index-skip-tombstones-p :skip)) (when (id-index-tombstone-p assertion) (setf assertion :skip)) (note-percent-progress sofar total) (incf sofar) (missing-larkc 9466))))))) ;; peer 2 code, new objects? (let ((idx-122 idx-120)) (unless (and (id-index-new-objects-empty-p idx-122) (id-index-skip-tombstones-p :skip)) (let* ((new (id-index-new-objects idx-122)) (id (id-index-new-id-threshold idx-122)) (end-id (id-index-next-id idx-122)) (default (if (id-index-skip-tombstones-p :skip) nil :skip))) (while (< id end-id) (let ((assertion (gethash id new default))) (unless (and (id-index-skip-tombstones-p :skip) (id-index-tombstone-p assertion)) (note-percent-progress sofar total) (incf sofar) (missing-larkc 9467))) (incf id)))))))))))) (map-mt-index function term truth gafs-only)))) (defun map-mt-index (function mt &optional truth gafs-only) "[Cyc] Apply FUNCTION to each assertion with TRUTH at mt index MT. If TRUTH is nil, all assertions are mapped. If GAFS-ONLY, then only gafs are mapped." (when (fort-p mt) (let ((type (if gafs-only :gaf nil))) ;; TODO - iteration macro (when (do-mt-index-key-validator mt type) (let ((final-index-spec (mt-final-index-spec mt)) (final-index-iterator nil)) (unwind-protect (progn (setf final-index-iterator (new-final-index-iterator final-index-spec type truth nil)) (let ((done-var nil) (token-var nil)) (until done-var (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var)) (valid (not (eq token-var ass)))) (when valid (funcall function ass)) (setf done-var (not valid)))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator)))))))) (defun map-other-index (function term &optional truth gafs-only) "[Cyc] Apply FUNCTION to each assertion with TRUTH at other index TERM. If TRUTH is nil, all assertionsa re mapped. If GAFS-ONLY, then only gafs are mapped." (let ((type (if gafs-only :gaf nil))) ;; TODO - iteration macro (when (do-other-index-key-validator term type) (let ((final-index-spec (other-final-index-spec term)) (final-index-iterator nil)) (unwind-protect (progn (setf final-index-iterator (new-final-index-iterator final-index-spec type truth nil)) (let ((done-var nil) (token-var nil)) (until done-var (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var)) (valid (not (eq token-var ass)))) (when valid (when valid (when (missing-larkc 30389) (funcall function ass)))) (setf done-var (not valid)))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator))))))) (defun gather-index (term &optional remove-duplicates?) "[Cyc] Return a list of all mt-relevant assertions indexed via TERM. If REMOVE-DUPLICATES? is non-nil, assertions are guaranteed to only be listed once." (let ((result nil)) (if (auxiliary-index-p term) (if (eq term (unbound-rule-index)) (missing-larkc 30393) ;; TODO - why a ~% at the end of an error message? (cerror "So don't!" "Can't gather unknown auxilliar index ~s~%" term)) ;; TODO - iteration macro (when (do-term-index-key-validator term nil) (let ((iterator-var (new-term-final-index-spec-iterator term nil)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator nil)) (unwind-protect (progn (setf final-index-iterator (new-final-index-iterator final-index-spec nil nil nil)) (let ((done-var-126 nil) (token-var-127 nil)) (until done-var-126 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-127)) (valid-128 (not (eq token-var-127 ass)))) (when (and valid-128 (do-term-index-assertion-match-p ass final-index-spec)) (push ass result)) (setf done-var-126 (not valid-128)))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator))))) (setf done-var (not valid))))))) (if remove-duplicates? (fast-delete-duplicates result #'eq) result))) (defun gather-index-in-any-mt (term &optional remove-duplicates?) "[Cyc] Return a list of all assertions indexed via TERM. If REMOVE-DUPLICATES? is non-nil, assertions are guaranteed to only be listed once." ;; TODO - mt binding macro (let ((*relevant-mt-function* #'relevant-mt-is-everything) (*mt* #$EverythingPSC)) (gather-index term remove-duplicates?))) (defun gather-gaf-arg-index (term argnum &optional pred mt (truth :true)) "[Cyc] Return a list of all gaf assertions such that: a) TERM is its ARGNUMth argument b) if TRUTH is non-nil, then TRUTH is its truth value c) if PRED is non-nil, then PRED must be its predicate d) if MT is non-nil, then MT must be its microtheory (and PRED must be non-nil)." (let ((result nil)) (possibly-with-just-mt (mt) (if pred ;; TODO - iteration macro, contains pred as a parameter (let ((pred-var pred)) (when (do-gaf-arg-index-key-validator term argnum pred-var) (let ((iterator-var (new-gaf-arg-final-index-spec-iterator term argnum pred-var)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator nil)) (unwind-protect (progn (setf final-index-iterator (new-final-index-iterator final-index-spec :gaf truth nil)) (let ((done-var-129 nil) (token-var-130 nil)) (until done-var-129 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-130)) (valid-131 (not (eq token-var-130 ass)))) (when valid-131 (push ass result)) (setf done-var-129 (not valid-131)))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator))))) (setf done-var (not valid))))))) ;; TODO - iteration macro, again with pred (let ((pred-var nil)) (when (do-gaf-arg-index-key-validator term argnum pred-var) (let ((iterator-var (new-gaf-arg-final-index-spec-iterator term argnum pred-var)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator nil)) (unwind-protect (progn (setf final-index-iterator (new-final-index-iterator final-index-spec :gaf truth nil)) (let ((done-var-133 nil) (token-var-134 nil)) (until done-var-133 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-134)) (valid-135 (not (eq token-var-134 ass)))) (when valid-135 (push ass result)) (setf done-var-133 (not valid-135)))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator))))) (setf done-var (not valid))))))))) (fast-delete-duplicates result #'eq))) (defun gather-predicate-extent-index (pred &optional mt (truth :true)) "[Cyc] Return a list of all gaf assertions such that: a) PRED is its predicate b) if TRUTH is non-nil, then TRUTH is its truth value c) if MT is non-nil, then MT must be its microtheory." (let ((result nil)) (possibly-with-just-mt (mt) (let ((pred-var pred)) (when (do-predicate-extent-index-key-validator pred-var) (let ((iterator-var (new-predicate-extent-final-index-spec-iterator pred-var)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator nil)) (unwind-protect (progn (setf final-index-iterator (new-final-index-iterator final-index-spec :gaf truth nil)) (let ((done-var-143 nil) (token-var-144 nil)) (until done-var-143 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-144)) (valid-145 (not (eq token-var-144 ass)))) (when valid-145 (push ass result)) (setf done-var-143 (not valid-145)))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator))))) (setf done-var (not valid)))))))) (fast-delete-duplicates result #'eq))) (defun gather-function-extent-index (func) "[Cyc] Return a list of all #$termOfUnit assertions such that: FUNC is the functor of the naut arg 2." (let ((result nil)) ;; TODO - iteration macro (when (do-function-extent-index-key-validator func) (let ((final-index-spec (function-extent-final-index-spec func)) (final-index-iterator nil)) (unwind-protect (progn (setf final-index-iterator (new-final-index-iterator final-index-spec :gaf nil nil)) (let ((done-var nil) (token-var nil)) (until done-var (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var)) (valid (not (eq token-var ass)))) (when valid (push ass result)) (setf done-var (not valid)))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator))))) (fast-delete-duplicates result #'eq))) (defun gather-predicate-rule-index (pred sense &optional mt direction) "[Cyc] Returna list of all non-gaf assertions (rules) such that: a) if SENSE is :pos, it has PRED as a predicate in a positive literal b) if SENSE is :neg, it has PRED as a predicate in a negative literal c) if MT is non-nil, then MT must be its microtheory d) if DIRECTION is non-nil, then DIRECTION must be its direciton." (let ((result nil)) (possibly-with-just-mt (mt) (if direction ;; TODO - iteration macro (when (do-predicate-rule-index-key-validator pred sense direction) (let ((iterator-var (new-predicate-rule-final-index-spec-iterator pred sense direction)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator nil)) (unwind-protect (progn (setf final-index-iterator (new-final-index-iterator final-index-spec :rule nil direction)) (let ((done-var-147 nil) (token-var-148 nil)) (until done-var-147 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-148)) (valid-149 (not (eq token-var-148 ass)))) (when valid-149 (push ass result)) (setf done-var-147 (not valid-149)))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator))))) (setf done-var (not valid)))))) ;; TODO - iteration macro (when (do-predicate-rule-index-key-validator pred sense nil) (let ((iterator-var (new-predicate-rule-final-index-spec-iterator pred sense nil)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :rule nil nil))) (unwind-protect (let ((done-var-151 nil) (token-var-152 nil)) (until done-var-151 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-152)) (valid-153 (not (eq token-var-152 ass)))) (when valid-153 (push ass result)) (setf done-var-151 (not valid-153))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid)))))))) (fast-delete-duplicates result #'eq))) (defun gather-decontextualized-ist-predicate-rule-index (pred sense &optional direction) "[Cyc] Returna list of all non-gaf assertions (rules) such that: a) if SENSE is :pos, it has PRED as a predicate in a positive literal wrapped in #$ist b) if SENSE is :neg, it has PRED as a predicate in a negative literal wrapped in #$ist c) if DIRECTION is non-nil, then DIRECTION must be its direction." (let ((result nil)) (if direction ;; TODO - iteration macro (when (do-decontextualized-ist-predicate-rule-index-key-validator pred sense direction) (let ((iterator-var (new-decontextualized-ist-predicate-rule-final-index-spec-iterator pred sense direction)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :rule nil direction))) (unwind-protect (let ((done-var-155 nil) (token-var-156 nil)) (until done-var-155 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-156)) (valid-157 (not (eq token-var-156 ass)))) (when valid-157 (push ass result)) (setf done-var-155 (not valid-157))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid)))))) ;; TODO - iteration macro (when (do-decontextualized-ist-predicate-rule-index-key-validator pred sense nil) (let ((iterator-var (new-decontextualized-ist-predicate-rule-final-index-spec-iterator pred sense nil)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :rule nil nil))) (unwind-protect (let ((done-var-158 nil) (token-var-159 nil)) (until done-var-158 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-159)) (valid-160 (not (eq token-var-159 ass)))) (when valid-160 (push ass result)) (setf done-var-158 (not valid-160))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid))))))) (fast-delete-duplicates result #'eq))) (defun gather-isa-rule-index (collection sense &optional mt direction) "[Cyc] Return a list of all non-gaf assertions (rules) such that: a) if SENSE is :pos, it has a positive literal of the form (isa <whatever> COLLECTION) b) if SENSE is :neg, it has a negative literal of the form (isa <whatever> COLLECTION) c) if MT is non-nil, then MT must be its microtheory d) if DIRECTION is non-nil, then DIRECTION must be its direction." (let ((result nil)) (possibly-with-just-mt (mt) (if direction ;; TODO - iteration macro (when (do-isa-rule-index-key-validator collection sense direction) (let ((iterator-var (new-isa-rule-final-index-spec-iterator collection sense direction)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :rule nil direction))) (unwind-protect (let ((done-var-161 nil) (token-var-162 nil)) (until done-var-161 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-162)) (valid-163 (not (eq token-var-162 ass)))) (when valid-163 (push ass result)) (setf done-var-161 (not valid-163))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid)))))) ;; TODO - iteration macro (when (do-isa-rule-index-key-validator collection sense nil) (let ((iterator-var (new-isa-rule-final-index-spec-iterator collection sense nil)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :rule nil nil))) (unwind-protect (let ((done-var-165 nil) (token-var-166 nil)) (until done-var-165 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-166)) (valid-167 (not (eq token-var-166 ass)))) (when valid-167 (push ass result)) (setf done-var-165 (not valid-167))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid)))))))) (fast-delete-duplicates result #'eq))) (defun gather-quoted-isa-rule-index (collection sense &optional mt direction) "[Cyc] Return a list of all non-gaf assertions (rules) such that: a) if SENSE is :pos, it has a positive literal of the form (quotedIsa <whatever> COLLECTION) b) if SENSE is :neg, it has a negative literal of the form (quotedIsa <whatever> COLLECTION) c) if MT is non-nil, then MT must be its microtheory d) if DIRECTION is non-nil, then DIRECTION must be its direction." (let ((result nil)) (possibly-with-just-mt (mt) (if direction ;; TODO - iteration macro (when (do-quoted-isa-rule-index-key-validator collection sense direction) (let ((iterator-var (new-quoted-isa-rule-final-index-spec-iterator collection sense direction)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :rule nil direction))) (unwind-protect (let ((done-var-169 nil) (token-var-170 nil)) (until done-var-169 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-170)) (valid-171 (not (eq token-var-170 ass)))) (when valid-171 (push ass result)) (setf done-var-169 (not valid-171))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid)))))) ;; TODO - iteration macro (when (do-quoted-isa-rule-index-key-validator collection sense nil) (let ((iterator-var (new-quoted-isa-rule-final-index-spec-iterator collection sense nil)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :rule nil nil))) (unwind-protect (let ((done-var-173 nil) (token-var-174 nil)) (until done-var-173 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-174)) (valid-175 (not (eq token-var-174 ass)))) (when valid-175 (push ass result)) (setf done-var-173 (not valid-175))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid)))))))) (fast-delete-duplicates result #'eq))) (defun gather-genls-rule-index (collection sense &optional mt direction) "[Cyc] Return a list of all non-gaf assertions (rules) such that: a) if SENSE is :pos, it has a positive literal of the form (genls <whatever> COLLECTION) b) if SENSE is :neg, it has a negative literal of the form (genls <whatever> COLLECTION) c) if MT is non-nil, then MT must be its microtheory d) if DIRECTION is non-nil, then DIRECTION must be its direction." (let ((result nil)) (possibly-with-just-mt (mt) (if direction ;; TODO - iteration macro (when (do-genls-rule-index-key-validator collection sense direction) (let ((iterator-var (new-genls-rule-final-index-spec-iterator collection sense direction)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :rule nil direction))) (unwind-protect (let ((done-var-177 nil) (token-var-178 nil)) (until done-var-177 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-178)) (valid-179 (not (eq token-var-178 ass)))) (when valid-179 (push ass result)) (setf done-var-177 (not valid-179))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid)))))) ;; TODO - iteration macro (when (do-genls-rule-index-key-validator collection sense nil) (let ((iterator-var (new-genls-rule-final-index-spec-iterator collection sense nil)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :rule nil nil))) (unwind-protect (let ((done-var-181 nil) (token-var-182 nil)) (until done-var-181 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-182)) (valid-183 (not (eq token-var-182 ass)))) (when valid-183 (push ass result)) (setf done-var-181 (not valid-183))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid)))))))) (fast-delete-duplicates result #'eq))) (defun gather-genl-mt-rule-index (genl-mt sense &optional rule-mt direction) "[Cyc] Returns alist of all non-gaf assertions (rules) such that: a) if SENSE is :pos, it has a positive literal of the form (genlMt <whatever> GENL-MT) b) if SENSE is :neg, it has a negative literal of the form (genlMt <whatever> GENL-MT) c) if RULE-MT is non-nil, then RULE-MT must be its microtheory d) if DIRECTION is non-nil, then DIRECTION must be its direction." (let ((result nil)) (possibly-with-just-mt (rule-mt) (if direction ;; TODO - iteration macro (when (do-genl-mt-rule-index-key-validator genl-mt sense direction) (let ((iterator-var (new-genl-mt-rule-final-index-spec-iterator genl-mt sense direction)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :rule nil direction))) (unwind-protect (let ((done-var-185 nil) (token-var-186 nil)) (until done-var-185 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-186)) (valid-187 (not (eq token-var-186 ass)))) (when valid-187 (push ass result)) (setf done-var-185 (not valid-187))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid)))))) ;; TODO - iteration macro (when (do-genl-mt-rule-index-key-validator genl-mt sense nil) (let ((iterator-var (new-genl-mt-rule-final-index-spec-iterator genl-mt sense nil)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :rule nil nil))) (unwind-protect (let ((done-var-189 nil) (token-var-190 nil)) (until done-var-189 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-190)) (valid-191 (not (eq token-var-190 ass)))) (when valid-191 (push ass result)) (setf done-var-189 (not valid-191))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid)))))))) (fast-delete-duplicates result #'eq))) (defun gather-function-rule-index (func &optional mt direction) "[Cyc] Return a list of all non-gaf assertions (rules) such that: a) it has a negative literal of the form (termOfUnit <whatever> (FUNC . <whatever>)) b) if MT is non-nil, then MT must be its microtheory c) if DIRECTION is non-nil, then DIRECTION must be its direction." (let ((result nil)) (possibly-with-just-mt (mt) (if direction ;; TODO - iteration macro (when (do-function-rule-final-index-key-validator func direction) (let ((iterator-var (new-function-rule-final-index-spec-iterator func direction)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :rule nil direction))) (unwind-protect (let ((done-var-193 nil) (token-var-194 nil)) (until done-var-193 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-194)) (valid-195 (not (eq token-var-194 ass)))) (when valid-195 (push ass result)) (setf done-var-193 (not valid-195))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid)))))) ;; TODO - iteration macro (when (do-function-rule-final-index-key-validator func nil) (let ((iterator-var (new-function-rule-final-index-spec-iterator func nil)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :rule nil nil))) (unwind-protect (let ((done-var-197 nil) (token-var-198 nil)) (until done-var-197 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-198)) (valid-199 (not (eq token-var-198 ass)))) (when valid-199 (push ass result)) (setf done-var-197 (not valid-199))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid)))))))) (fast-delete-duplicates result #'eq))) (defun gather-exception-rule-index (rule &optional mt direction) "[Cyc] Return a list of all non-gaf assertions (rules) such that: a) it has a positive literal of the form (abnormal <whatever> RULE) b) if MT is non-nil, then MT must be its microtheory c) if DIRECTION is non-nil, then DIRECTION must be its direction." (let ((result nil)) (possibly-with-just-mt (mt) (if direction ;; TODO - iteration macro (when (do-exception-rule-index-key-validator rule direction) (let ((iterator-var (new-exception-rule-final-index-spec-iterator rule direction)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :rule nil direction))) (unwind-protect (let ((done-var-201 nil) (token-var-202 nil)) (until done-var-201 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-202)) (valid-203 (not (eq token-var-202 ass)))) (when valid-203 (push ass result)) (setf done-var-201 (not valid-203))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid)))))) ;; TODO - iteration macro (when (do-exception-rule-index-key-validator rule nil) (let ((iterator-var (new-exception-rule-final-index-spec-iterator rule nil)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :rule nil nil))) (unwind-protect (let ((done-var-205 nil) (token-var-206 nil)) (until done-var-205 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-206)) (valid-207 (not (eq token-var-206 ass)))) (when valid-207 (push ass result)) (setf done-var-205 (not valid-207))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid)))))))) (fast-delete-duplicates result #'eq))) (defun gather-pragma-rule-index (rule &optional mt direction) "[Cyc] Return a list of all non-gaf assertions (rules) such that: a) it has a positive literal of the form (meetsPragmaticRequirement <whatever> RULE) b) if MT is non-nil, then MT must be its microtheory c) if DIRECTION is non-nil, then DIRECTION must be its direction." (let ((result nil)) (possibly-with-just-mt (mt) (if direction ;; TODO - iteration macro (when (do-pragma-rule-index-key-validator rule direction) (let ((iterator-var (new-pragma-rule-final-index-spec-iterator rule direction)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :rule nil direction))) (unwind-protect (let ((done-var-209 nil) (token-var-210 nil)) (until done-var-209 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-210)) (valid-211 (not (eq token-var-210 ass)))) (when valid-211 (push ass result)) (setf done-var-209 (not valid-211))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid)))))) ;; TODO - iteration macro (when (do-pragma-rule-index-key-validator rule nil) (let ((iterator-var (new-pragma-rule-final-index-spec-iterator rule nil)) (done-var nil) (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator (new-final-index-iterator final-index-spec :rule nil nil))) (unwind-protect (let ((done-var-213 nil) (token-var-214 nil)) (until done-var-213 (let* ((ass (iteration-next-without-values-macro-helper final-index-iterator token-var-214)) (valid-215 (not (eq token-var-214 ass)))) (when valid-215 (push ass result)) (setf done-var-213 (not valid-215))))) (destroy-final-index-iterator final-index-iterator)))) (setf done-var (not valid)))))))) (fast-delete-duplicates result #'eq))) (defun gather-mt-index (term) "[Cyc] Return a list of all assertions such that TERM is its microtheory." (if (or (simple-indexed-term-p term) (and (hlmt-p term) (broad-mt? (hlmt-monad-mt term)))) (let ((*mapping-answer* nil)) ;; TODO - mt macro (let ((*relevant-mt-function* #'relevant-mt-is-eq) (*mt* term)) (map-mt-contents #'gather-assertions (hlmt-monad-mt term)) *mapping-answer*)) (missing-larkc 12735))) (defun gather-other-index (term) "[Cyc] Return a list of other assertions mentioning TERM but not indexed in any other more useful manner." (if (simple-indexed-term-p term) (let ((*mapping-answer* nil)) (map-other-index #'gather-assertions term) *mapping-answer*) (when-let ((final-index (get-other-subindex term))) (missing-larkc 31921)))) (defun gather-assertions (assertion) (when (or (not *mapping-assertion-selection-fn*) (funcall *mapping-assertion-selection-fn* assertion)) (push assertion *mapping-answer*)))
57,295
Common Lisp
.lisp
904
41.340708
149
0.499716
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
ac9f33ece0a1c6f766cbc554df2a0acdfb93d8cb29ddd34d6f8c602050e63b22
6,772
[ -1 ]
6,773
kb-indexing-macros.lisp
white-flame_clyc/larkc-cycl/kb-indexing-macros.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun* number-has-reached-cutoff? (number cutoff) (:inline t) (>= number cutoff)) (defun number-of-non-null-args-in-order (&optional arg1 arg2 arg3 arg4 arg5) "[Cyc] Stops counting if it hits a null one." (cond ((not arg1) 0) ((not arg2) 1) ((not arg3) 2) ((not arg4) 3) ((not arg5) 4) (t 5)))
1,725
Common Lisp
.lisp
38
41.894737
77
0.753301
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
8e65ff3c23de3bba47a657d4eff588d913b9e4cc5e66f2b86d849dcb3bed8785
6,773
[ -1 ]
6,774
cyc-testing.lisp
white-flame_clyc/larkc-cycl/cyc-testing.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# ;; Concatenated multiple files: ;; generic_testing - moved up because it has the defstruct ;; cyc_testing_initialization ;; cyc_testing (in-package :clyc) (defglobal *test-case-table-index* (make-hash-table) "[Cyc] An index of test case names (keywords) -> tables (lists) of (args-to-eval . expected-results) tuples.") (defglobal *ordered-test-cases* nil "[Cyc] An ordered list of test case names, in order of definition.") (deflexical *test-case-tables-by-class* (make-hash-table) "[Cyc] All the test-cases sorted by what classes they belong to.") (deflexical *generic-test-results* '(:success :failure :error :not-run :invalid) "[Cyc] The possible statuses for generic tests.") (deflexical *generic-test-verbosity-levels* '(:silent :terse :verbose :post-build) "[Cyc] The possible levels of verbosity for generic tests.") (deflexical *test-case-table-post-build-token* :tct "[Cyc] The token identifying 'test case table' in the space of post-build tests.") (defstruct (generic-test-case-table (:conc-name #:gtct-)) name tuples (test #'equal) owner classes (kb :tiny) (working? t)) (defun new-generic-test-case-table (name tuples test owner &optional classes (kb :tiny) (working? t)) ;; TODO - lots of elided type checks (make-generic-test-case-table :name name :tuples tuples :test (or test #'equal) :owner owner :classes classes :kb kb :working? working?)) (defun generic-test-case-table-name (gtct) (gtct-name gtct)) ;; ELIDED define-test-case-table-int (macro-helper to nonexistent macro) (defconstant *cfasl-wide-opcode-generic-test-case-table* 512) ;;;; FILE cyc_testing.cyc_testing_initialization (file "cyc_testing/cyc_testing_initialization") (deflexical *cyc-tests-initialized?* nil "[Cyc] Set to T after initializations have been performed. IF YOU RECOMPILE THIS (thereby setting it back to nil), IT WILL BREAK CYC-TESTING. If you start getting errors like 'FOO is not a GENERIC-TEST-CASE-TABLE-P', you need to rerun PERFORM-CYC-TESTING-INITIALIZATIONS.") (defun cyc-tests-initialized? () *cyc-tests-initialized?*) (defun perform-cyc-testing-initializations () (index-all-cyc-tests-by-name) (setf *cyc-tests-initialized?* t)) ;;;; FILE cyc_testing.cyc_testing (file "cyc-testing/cyc-testing") (defparameter *it-output-format* :standard) (defparameter *cyc-test-debug?* nil "[Cyc] Set this to T if you want to debug the tests (not catch errors)") (defparameter *run-tiny-kb-tests-in-full-kb?* t "[Cyc] Whether to run tests that only require the tiny KB in the full KB. The default is T so that it's easy to run all tests on a full KB, but should be bound to NIL when testing on both a tiny and a full KB.") (defparameter *test-real-time-pruning?* nil "[Cyc] Whether to test real-time while-inference-is-running pruning. This will force :COMPUTE-ANSWER-JUSTIFICATIONS? to NIL and will only run tests where that makes sense.") (defun testing-real-time-prining? () *test-real-time-pruning?*) (deflexical *cyc-test-verbosity-levels* (list :silent :terse :verbose) "[Cyc] The possible levels of verbosiy for Cyc tests.") (defparameter *cyc-test-filename* nil "[Cyc] Bound to the current file being loaded, so that the tests can know what file they're in") (defparameter *warn-on-duplicate-cyc-test-names?* nil "[Cyc] Whether we should warn if a test has the same name as another test. This often happens when tests are redefined or updated, so we only want to do it when we're loading tests from a clean initial state.") (deflexical *cyc-test-result-success-values* '(:success :regression-success) "[Cyc] Test results that mean that the test succeeded.") (deflexical *cyc-test-result-failure-values* '(:failure :regression-failure :abnormal :error) "[Cyc] Test results that mean that the test failed.") (deflexical *cyc-test-result-ignore-values* '(:non-regression-success :non-regression-failure :not-run :invalid) "[Cyc] Test results that mean that the test was ignored, or that the test results should be ignored, and counted as neither a success nor a failure.") (deflexical *cyc-test-result-values* (append *cyc-test-result-success-values* *cyc-test-result-failure-values* *cyc-test-result-ignore-values*) "[Cyc] All possible results for tests.") (deflexical *cyc-test-type-table* '((:iut "inference unit test") (:it "inference test") (:rmt "removal module test") (:ert "evaluatable relation test") (:tct "test case table") (:kct "KB content test")) "[Cyc] The table of known Cyc test types. Column 1 is a uniquely identifying keyword. Column 2 is a string description of the test type.") (defglobal *cyc-tests* nil "[Cyc] The master ordered list of all Cyc test objects.") (defun cyc-tests () *cyc-tests*) (defglobal *cyc-test-by-name* (make-hash-table :test #'equal) "[Cyc] An index from NAME -> Cyc Test object") (defglobal *cyc-test-by-dwimmed-name* (make-hash-table :test #'equal) "[Cyc] An index from DWIMMED-NAME -> list of Cyc Test objects") (defun index-cyc-test-by-name (ct name) (when (and *warn-on-duplicate-cyc-test-names?* (gethash name *cyc-test-by-name*)) (warn "A Cyc test named ~a already existed; overwriting" name)) (setf (gethash name *cyc-test-by-name*) ct) (push ct (gethash name *cyc-test-by-dwimmed-name*)) (when (consp name) (missing-larkc 32431)) (when (cyc-tests-initialized?) (let ((rmt (cyc-test-guts ct))) (when (funcall 'removal-module-test-p rmt) (missing-larkc 32432)))) (when (cyc-tests-initialized?) (let ((rmct (cyc-test-guts ct))) (when (funcall 'removal-module-cost-test-p rmct) (missing-larkc 32433)))) ct) (defun index-all-cyc-tests-by-name () (mapc #'index-cyc (cyc-tests))) (defstruct (cyc-test (:conc-name #:ct-)) file guts) (defun new-cyc-test (file guts) (declare ((or null string) file)) (if (cyc-tests-initialized?) (must (cyc-test-guts-p guts) "~s is not a CYC-TEST-GUTS-P" guts) (check-type guts #'generic-test-case-table-p)) (let* ((ct (make-cyc-test :file file :guts guts)) (name (if (cyc-tests-initialized?) (cyc-test-name ct) (generic-test-case-table-name guts))) (existing-ct (find-cyc-test-by-exact-name name))) (when existing-ct (setf *cyc-tests* (delete existing-ct *cyc-tests* :test #'eq)) (missing-larkc 32458)) (push-last ct *cyc-tests*) (index-cyc-test-by-name ct name) ct)) (defun cyc-test-guts (ct) (ct-guts ct)) (defun cyc-test-type (ct) (or (cyc-test-type-permissive ct) (error "Cyc-test of unexpected type ~s" ct))) (defun cyc-test-type-permissive (ct) (cyc-test-guts-type (cyc-test-guts ct))) (defun cyc-test-guts-type (guts) (cond ((generic-test-case-table-p guts) :tct) ;; TODO - lots of other specific conditions tested, all missing (t (missing-larkc 32334)))) (defun cyc-test-name (ct) "[Cyc] Names are assumed to be unique, even across type" (let ((guts (cyc-test-guts ct))) (case (cyc-test-type guts) (:it guts) (:tct (generic-test-case-table-name guts)) ;; TODO - these all have their own error codes, but I'm lazy ((:iut :rmt :tmt :rmct :ert :kct) (missing-larkc 32325)) (otherwise (error "Cyc-test of unexpected type ~s" guts))))) (defun find-cyc-test-by-exact-name (name) (gethash name *cyc-test-by-name*)) (defconstant *cfasl-wide-opcode-cyc-test* 514) (defglobal *cyc-test-files* nil "[Cyc] The master ordered list of all Cyc test file objects.") (defstruct cyc-test-file filename kb) (defglobal *most-recent-cyc-test-funs* nil "[Cyc] The most recent runs are saved here for the cases where they're not returned directly") (defglobal *most-recent-cyc-test-file-load-failures* nil "[Cyc] The Cyc test files which failed to load the last time LOAD-ALL-CYC-TESTS was evaluated.") (deflexical *tests-that-dont-work-with-real-time-pruning* (list :canonicalize-inference-answer-justifications :non-explanatory-sentence-supports :non-explanatory-variable-map-supports :true-sentence-not-canonicalization :true-sentence-of-atomic-sentence-reduction :ist-of-atomic-sentence-reduction :relation-all-instance-iterate-2 :relation-instance-all-iterate-2 :reject-previously-proven-proofs :inference-harness-overhead :tactically-unexamined-no-good-implies-strategically-unexamined-no-good :the-set-of-elements-returns-hl-narts :the-collection-of-instances-returns-hl-narts :genlpreds-lookup-generates-correct-supports :kappa-removal-works :dont-reopen-answer-link :removal-true-sentence-universal-disjunction-14a :closed-asent-with-3-children :simple-except-when :simple-except-when-residual-transformation :partial-except-when :variable-map-except-when :true-sentence-implies-var-canonicalization :exception-tms-backward-no-op :multiple-transformation-proofs-for-closed-problem :backchain-to-removal-true-sentence-universal-disjunction-1 :backchain-to-removal-true-sentence-universal-disjunction-2 :backchain-to-removal-true-sentence-universal-disjunction-3 :collection-isa-backchain-required-4 :collection-genls-backchain-required-4 :collection-backchain-required-3 :collection-backchain-required-4 :early-removal-of-8-restricted-problems-requiring-transformation :early-new-root-of-9-restricted-problems-requiring-transformation :forward-indeterminate-result :simple-forward-pragmatic-requirement :simple-forward-pragmatic-requirement-supports :nart-isa-in-right-mt :forward-problem-store-destruction-on-conflict :forward-rule-concluding-consequent-in-wrong-mt :skolemize-forward :forward-inference-with-defns :completeness-in-low-mt-doesnt-hose-forward-inference :hypothetical-mt-completeness-assertion-doesnt-hose-forward-inference :except-mt-in-mid-mt-blocks-high-mt-from-low-mt :except-mt-in-high-mt-hoses-backward-inference :cyc-assert-with-reifiable-monad-mt :forward-rule-concluding-false :skolem-result-arg :unassert-reifiable-nat-mt :unassert-nart-mt-sentence-with-nart :unassert-reifiable-nat-mt-via-tl :canonicalize-nested-mt :function-test :nat-removal :resulttype-change :meta-assertion-removal :arg-type-mt-denoting-function :max-floor-mts-of-nat :contextualized-collection-specpred-of-isa :use-defns-to-check-inference-semantically-valid-dnf :sbhl-trumps-defns :skolemize-forward-naut-genl-mt-wff-exception :one-step :two-step :two-step :two-step-arg-1 :two-step-arg-1 :many-step :cross-mt :disjunctive-syllogism :argumentation :tms-loop :reconsider-deduction :reconsider-deduction :hl-support-mt-handling :there-exists :except-when :except-when :strength-propagation :sequence-variables-inference :inference-answer-template :forward-propagate-mt :forward-propagate-mt-continue :ist-triggers-forward-inference-simple :forward-non-trigger-literal-honored :except-blocks-backward :except-blocks-forward :true-sentence-universal-disjunction-scoping :tms-reconsideration-with-backchain-forbidden :tms-for-hl-supports :assertion-direction :merge-ignores-opaque-references :mt-floors-wrt-isa-paths :min-genl-mts :min-genl-predicates :min-genls-collection :split-no-goodness-propagation :lazily-manifest-non-focals :consider-no-good-after-determining-tactics :removal-all-isa-of-type-2 :avoid-lookup-on-indeterminates :irrelevant-does-not-imply-pending :asserted-instance-of-disjoint-collections :chaining-skolem-straightforward :chaining-skolem-shallow :chaining-skolem-deep :chaining-skolem :except-decontextualized :problem-store-pruning-max-insufficient :restricted-closed-good-problems-stay-unexamined :genls-between :conjunctive-integer-between-1 :conjunctive-integer-between-2 :conjunctive-integer-between-3 :conjunctive-integer-between-4 :conjunctive-integer-between-5 :conjunctive-integer-between-6 :conjunctive-integer-between-7 :conjunctive-integer-between-8 :conjunctive-followup-additional-join-ordered :conjunctive-followup-additional-join-ordered-without-inference :circular-proofs) "[Cyc] A list of tests that will fail if :COMPUTE-ANSWER-JUSTIFICATIONS? is forced to NIL and/or if problem store pruning happens while they're running.")
13,896
Common Lisp
.lisp
190
67.178947
4,016
0.731711
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
dfd267b2ce8ebc4c7e68fe2b1353fd6c471b039b336c1029ac292319d8a950b7
6,774
[ -1 ]
6,775
memoization-state.lisp
white-flame_clyc/larkc-cycl/memoization-state.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO - I think I screwed up here, in making a combined interface. "Memoization" seems to be local to a dynamic state binding, while "Caching" is a singular global cache. I probably can ignore all the actual implementation guts of these 2 (which spends most its complexity juggling multiple return values, optional params, etc) and just reimplement the exposed interfaces. But, search for all instances of defun-memoized and check the java to see if it has calls involving "global" in its lazy cache state initialization to distinguish which one is actually being used. (defconstant *global-caching-lock* (bt:make-lock "global-caching-lock")) (defglobal *caching-mode-should-monitor* nil "[Cyc] Whether to enable cache monitoring. Need to do a retranslation after changing this.") (defglobal *cache-monitor-hash* (make-hash-table) "[Cyc] Hashtable for monitoring all caching calls.") (defglobal *cache-monitor-failure-hash* (make-hash-table) "[Cyc] Hashtable for monitoring cached calls that aren't already cached.") (defglobal *allow-function-caching-to-be-disabled* nil "[Cyc] This indicates that when evaluating the function caching macros, whether to test if the function should be disabled. Not testing for disabled is generally faster but less flexible because then you can no longer dynamically disable function caching. You'll need to do a new translation after setting this for it to take effect.") (defvar *caching-mode-enabled* :all "[Cyc] Caching mode function indicating what's enabled.") (defvar *caching-mode-disabled* nil "[Cyc] Caching mode function indicating what's disabled.") (defparameter *function-caching-enabled?* t "[Cyc] Global caching and memoization are disabled when NIL.") ;; NOTE - there were a bunch of fixed-arity sxhash_calc_N calls in here? (defmacro multi-hash (&rest hashes) "Combine fixnum hashes together, using platform-specific hashing. Should not cons." (reduce (lambda (x y) `(sb-int::mix ,x (sxhash ,y))) hashes)) ;; DESIGN - as far as I can tell, the entire point of this caching-state stuff is to eliminate the need to cons up a list containing the params as a key to pass to gethash each time the function is called. So the sxhash of the list of args is manually calculated without consing, then collisions are manually checked with the parameter values directly, using the TEST function on each parameter (note that this allows EQ or EQL slot testing within a composite key). On a cache miss, the key is consed up to register it. The zero parameter caching scheme is also broken out to its own storage slot. ;; This also stores the multiple-value-list of the calculation, instead of just a single return value. TODO DESIGN - optimizing a route for single-value returns can save consing & speed ;; If these caches are hit a ton, consing up a list key to pass to gethash would add more GC pressure, and the steps through the code from the java looks shorter than what gethash does,although there is a gethash underlying the key->collisions storage. The test seems to be part of the generated code (though I don't have a reference macro body to work from), so there's no unnecessary dispatch. I think it's worth keeping this claptrap instead of just going for gethash for the moment. As always, profiling needed. ;; Also, the caches can be selectively cleared, so having knowledge of which global variables hold the cahing states of various usages needs to remain exposed. (defstruct caching-state store zero-arg-results lock capacity func-symbol test args-length) (defun create-caching-state (lock func-symbol func-args-length &optional capacity (test #'eql) (initial-size 0)) (declare ((integer 0) initial-size) ((or null (integer 1)) capacity) ((or symbol function) test)) ;; TODO - don't quite understand this (setf test (if (= 1 func-args-length) (coerce test 'function) #'eql)) (make-caching-state :store (if capacity (new-cache capacity test) (make-hash-table :test test :size initial-size)) :lock lock :capacity capacity :func-symbol func-symbol :test test :args-length func-args-length :zero-arg-results :&memoized-item-not-found&)) (defmacro with-caching-state-lock (cs cache-form &optional hash-form) "Runs the body in the cs's lock, or plain if its lock is NIL. If the hash-form is omitted, the same form is run regardless of the store type." (alexandria:with-gensyms (lock worker) (alexandria:once-only (cs) `(let ((,lock (caching-state-lock ,cs))) ;; Wrap the body in a function that can be called from 2 places (flet ((,worker () ;; Unhygienic but useful value (let ((store (caching-state-store ,cs))) (declare (ignorable store)) ,(if hash-form `(if (caching-state-capacity ,cs) ,cache-form ,hash-form) cache-form)))) (if ,lock (bt:with-lock-held (,lock) (,worker)) (,worker))))))) (defun caching-state-get-zero-arg-results (caching-state) (with-caching-state-lock caching-state (caching-state-zero-arg-results caching-state))) (defun caching-state-set-zero-arg-results (caching-state val) (with-caching-state-lock caching-state (setf (caching-state-zero-arg-results caching-state) val))) (defun caching-state-lookup (caching-state key &optional (default :&memoized-item-not-found&)) (with-caching-state-lock caching-state (cache-get-without-values store key default) (gethash key store default))) (defun caching-state-put (caching-state key value) (with-caching-state-lock caching-state (cache-set store key value) (setf (gethash key store) value))) (defun caching-state-clear (caching-state) (with-caching-state-lock caching-state (cache-clear store) (clrhash store))) (defun caching-state-enter-multi-key-n (caching-state sxhash collisions results args-list) "[Cyc] Cache in CACHING-STATE under hash code SXHASH the fact that ARGS-LIST returns the list of values RESULTS" ;; Translates :&memoized-item-not-found& back to an empty list. ;; TODO - should we just test for EQ of that instead of LISTP? (unless (listp collisions) (setf collisions nil)) (if (not args-list) (caching-state-set-zero-arg-results caching-state results) ;; TODO - original code directly hit the slot, not using the locking version. ;; That doesn't seem safe, can it do so? (caching-state-put caching-state sxhash (cons (list args-list results) collisions)))) ;; TODO - detect no-arg as well? will probably work (suboptimally) without it, though. ;; TODO - where is clearing of its memoization registered? ;; This macroexpansion should (assuming list-utilities' num-list-cached is being implemented): ;; (defun num-list-cached (num start) ...) ;; create the name *num-list-cached-caching-state* to hold the lazily instantiated cache ;; hit the cache lookup by hashing the params without consing, and checking the list of collisions ;; define the cache-miss expression to generate the value for the params ;; draw from calls in java: ;; (create-global-caching-state-for-name name cs-variable (capacity nil) (test eql) (args-length auto) size) ;; memoization_state.register_hl_store_cache_clear_callback(..) => :clear-when :hl-store-modified ;; kb-mapping-macros simple-term-assertion-list-filtered also registers a clearing parameter from the hl-store being cleared, and :CLEAR-WHEN is in the java stuff here, surrounded by other keywords that we're going to try to use. (defmacro defun-memoized (name params (&key (capacity nil) (test 'eql) (initial-size 0) declare doc clear-when) &body calculate-cache-miss) "Define a memoized function. The body can still have a docstring & declarations." (let ((varname (symbolicate "*" name "-CACHING-STATE*")) (clear-name (symbolicate "CLEAR-" name))) (alexandria:with-gensyms (cs key collisions results) `(progn (defvar ,varname nil) ;; Might as well create the table early, instead of always doing the lazy check as the Java code did. (toplevel (create-global-caching-state-for-name ',name ',varname ,capacity ,(if (symbolp test) (list 'quote test) test) ,(length params) ,initial-size) (note-globally-cached-function ',name) ,(when clear-when (case clear-when (:hl-store-modified `(register-hl-store-cache-clear-callback #',clear-name)) (otherwise (error "Unknown defun-memoized :clear-when option: ~s" clear-when))))) ;; TODO - this would be the place to inject metrics on memoized functions (defun ,name ,params ,@(when declare `((declare ,@declare))) ,@(when doc (list doc)) (let* ((,cs ,varname) ;; Calculate the key by doing a non-consing hash construction (,key (multi-hash ,@params)) ;; The initial lookup, which will return the list of hash collisions (,collisions (caching-state-lookup ,cs ,key))) ;; Hash hit. Try to find a matching collision (when (not (eq ,collisions :&memoized-item-not-found&)) ;;(format t "~&cache hash hit ~a ~s~%" ',name (list ,@params)) (dolist (collision ,collisions) ;; Each collision is (params results). Try to match params. (let ((args (first collision))) (when (and ,@ (mapcar (lambda (param) `(,test ,param (pop args))) params)) (return-from ,name (second collision)))))) ;; Hash miss, or collision not found. Compute and store it. (let ((,results (multiple-value-list (progn ,@calculate-cache-miss)))) ;;(format t "~&cache miss ~a ~s~%" ',name (list ,@params)) (caching-state-enter-multi-key-n ,cs ,key ,collisions ,results (list ,@params)) (caching-results ,results)))))))) ;; TODO DESIGN - This doesn't deal with arg-list keys, just a singular key object passed to the hashtable. Grepping the source code, these always seem to be symbol keys. This probably maps a function to a cached-state, which seems like a pointless lookup, given that the function name itself can create a symbol-value unique to hold the caching state anyway. I'm tempted to rip all this out. (defstruct memoization-state store current-process lock name should-clone) (defun create-memoization-state (&optional name lock should-clone (test #'eql)) "[Cyc] Return a new memoization state suitable for WITH-MEMOIZATION-STATE" (declare ((or null string) name) ((or null bt:lock) lock) ((or symbol function) test)) (when (and should-clone (not lock)) (setf lock (bt:make-lock "Memoization state clone lock"))) (make-memoization-state :name name :lock lock :store (make-hash-table :test test) :current-process nil :should-clone should-clone)) ;; TODO - redundant names, clean it up (defun new-memoization-state (&optional name lock should-clone (test #'eql)) (create-memoization-state name lock should-clone test)) (defmacro with-memoization-state-lock (ms &body body) "Runs the body in the ms's lock, or plain if its lock is NIL." (alexandria:with-gensyms (lock worker) (alexandria:once-only (ms) `(let ((,lock (memoization-state-lock ,ms))) ;; Wrap the body in a function that can be called from 2 places (flet ((,worker () (let ((store (memoization-state-store ,ms))) ,@body))) (if ,lock (bt:with-lock-held (,lock) (,worker)) (,worker))))))) (defun memoization-state-lookup (memoization-state key &optional default) (with-memoization-state-lock memoization-state (gethash key store default))) (defun memoization-state-put (memoization-state key value) (with-memoization-state-lock memoization-state (setf (gethash key store) value))) (defun memoization-state-clear (memoization-state) (with-memoization-state-lock memoization-state (clrhash store))) (defparameter *memoization-state* nil "[Cyc] Current memoization state. NIL indicates no memoization is occurring.") (defun current-memoization-state () "[Cyc] Return the current memoization state, or NIL if none." *memoization-state*) (defun possibly-new-memoization-state () (or *memoization-state* (create-memoization-state))) (defun clear-all-memoization (state) (memoization-state-clear state)) (defglobal *memoized-functions* nil "[Cyc] The master list of all functiosn defined via define-memoized") (defun note-memoized-function (function-symbol) (pushnew function-symbol *memoized-functions*) function-symbol) (defglobal *globally-cached-functions* nil "[Cyc] The master list of all functions defined via define-cached or define-cached-new") (defun note-globally-cached-function (function-symbol) (pushnew function-symbol *globally-cached-functions*) function-symbol) (defun globally-cached-functions () (remove-if-not #'fboundp *globally-cached-functions*)) (defun global-cache-variables () (remove-if-not #'boundp (mapcar (lambda (name) ;; TODO - which package? (intern (format nil "*~a-CACHING-STATE*" name))) (globally-cached-functions)))) (defun global-cache-variable-values () (mapcar #'symbol-value (global-cache-variables))) (defun clear-all-globally-cached-functions () (progress-dolist (caching-state (global-cache-variable-values) "Clearing all globally cached functions") (when caching-state (caching-state-clear caching-state)))) (deflexical *cache-clear-triggers* '(:hl-store-modified :genl-mt-modified :genl-preds-modified :genls-modified :isa-modified :quoted-isa-modified) "[Cyc] The list of possible triggers which can clear caches when they are triggered. Note that :GENL-PREDS-MODIFIED is also triggered on the addition or removal of a #$genlInverse assertion.") ;; TODO - arg ordering is different than create-caching-state (defun create-global-caching-state-for-name (name cs-variable capacity test args-length size) (unless test (setf test #'eql)) (bt:with-lock-held (*global-caching-lock*) (or (symbol-value cs-variable) (set cs-variable (create-caching-state (bt:make-lock (format nil "global caching lock for ~a" name)) name args-length capacity test size))))) (defun global-caching-variable-new (name) (intern (format nil "*~a-CACHING-STATE*" name))) (defglobal *hl-store-cache-clear-callbacks* nil "[Cyc] The list of zero-arity function-spec-p's to funcall each time the HL store changes. These are intended to clear HL-store-dependent caches.") (defun register-hl-store-cache-clear-callback (callback) "[Cyc] Registers CALLBACK as a function which will be funcalled each time the HL store changes. CALLBACK is a function-spec-p which should take zero arguments." (check-type callback 'function-spec-p) (pushnew callback *hl-store-cache-clear-callbacks*) callback) (defun clear-hl-store-dependent-caches () "[Cyc] Clears all HL store dependent caches, as registered by REGISTER-HL-STORE-CACHE-CLEAR-CALLBACK." (dolist (callback *hl-store-cache-clear-callbacks*) ;; Adding in both symbol & function object support, just in case. ;; Original only checked fboundp, which requires symbols and would error on functions. ;; However, that doesn't make much sense as it had to be function-spec-p on registration, ;; and this function's fboundp thus would only fail if the symbol was FMAKUNBOUNDed after registeration. (when (function-spec-p callback) (funcall callback)))) (defglobal *mt-dependent-cache-clear-callbacks* nil "[Cyc] The list of zero-arity function-spec-p's to funcall each time the microtheory structure changes. These are intended to clear mt-dependent caches.") (defun register-mt-dependent-cache-clear-callback (callback) "[Cyc] Registers CALLBACK as a function which will be funcalled each time the microtheory structure changes. CALLBACK should take zero arguments." (check-type callback 'function-spec-p) (pushnew callback *mt-dependent-cache-clear-callbacks*) callback) (defparameter *suspend-clearing-mt-dependent-caches?* nil) (defun clear-mt-dependent-caches? () *suspend-clearing-mt-dependent-caches?*) (defglobal *genl-preds-dependent-cache-clear-callbacks* nil "[Cyc] The list of zero-arity function-spec-p's to funcall each time the genlPreds structure changes. These are intended to clear mt-dependent caches.") (defglobal *genls-dependent-cache-clear-callbacks* nil "[Cyc] The list of zero-arity function-spec-p's to funcall each time the genls structure changes. These are intended to clear mt-dependent caches.") (defglobal *isa-dependent-cache-clear-callbacks* nil "[Cyc] The list of zero-arity function-spec-p's to funcall each time the isa structure changes. These are intended to clear mt-dependent caches.") (defglobal *quoted-isa-dependent-cache-clear-callbacks* nil "[Cyc] The list of zero-arity function-spec-p's to funcall each time the quotedIsa structure changes. These are intended to clear mt-dependent caches.") (defun* caching-results (results) (:inline t) "Returns the list of results as multiple-values." ;; Bypass the function call to values-list when there's only 1 result ;; TODO - can there be zero results? this code would return 0 results into 1 NIL (if (cdr results) (values-list results) (car results))) (defconstant *caching-n-sxhash-composite-value* 167)
19,901
Common Lisp
.lisp
311
56.051447
600
0.695222
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
d299d564c2006c518b10cd9e053cf4cafc6e80217e0dbcfec50b3f53c058cdc6
6,775
[ -1 ]
6,776
set.lisp
white-flame_clyc/larkc-cycl/set.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; Replaced the implemenation with key->T hashtables ;; TODO - could defer the inlines to set-contents instead of hash-table (deflexical *new-set-default-test-function* #'eql) (defun* new-set (&optional (test *new-set-default-test-function*) (size 0)) (:inline t) "[Cyc] Allocate a new set with TEST as the equality test. Assume that SIZE elements will likely be immediately added." (make-hash-table :test test :size size)) (defun* set-size (set) (:inline t) "[Cyc] Return the number of items currently entered in SET" (hash-table-count set)) (defun* set-empty? (set) (:inline t) "[CYc] Return non-NIL iff SET is empty, NIL otherwise." (hash-table-empty-p set)) (defun* set-member? (element set) (:inline t) "[Cyc] Return T iff ELEMENT is in SET." (gethash element set)) ;; TODO DESIGN - this is a lot slower than if it didn't have to have the return value test. SBCL internals might allow us to do this more directly, but we should first check if the return value is ever actually used. (defun* set-add (element set) (:inline t) "[Cyc] Add this ELEMENT into the SET. Return T iff ELEMENT was not already there." (unless (set-member? element set) (setf (gethash element set) t))) (defun* set-remove (element set) (:inline t) "[Cyc] If ELEMENT is present in SET, then take it out of SET. Returns T iff ELEMENT was in SET to begin with." ;; remhash matches this return behavior (remhash element set)) (defun* clear-set (set) (:inline t) "[Cyc] Reset SET to the status of being just allocated. Returns SET." ;; TODO - we're not remembering its initial size. Oh well. (clrhash set)) (defun* new-set-iterator (set) (:inline t) (new-hash-table-iterator set)) (defconstant *cfasl-opcode-set* 60) (defun cfasl-input-set (stream) (let* ((test (cfasl-input stream)) (size (cfasl-input stream)) (set (new-set test size))) (cfasl-input-set-contents stream set size))) (defconstant *cfasl-opcode-legacy-set* 67) (defun* set-element-list (set) (:inline t) "[Cyc] Returns a list of the elements of SET." (hash-table-keys set)) ;; TODO - deprecate this (defun* set-rebuild (set) (:inline t) set) (defun* set-p (obj) (:inline t) "Since Clyc sets are hashtables, this overfits." ;; TODO - See if there are any places where set-p is used as a peer of dictionary-p or hash-table-p etc (hash-table-p obj)) (defmacro do-set ((item set &optional done-form) &body body) (alexandria:with-gensyms (val) `(block nil (maphash (lambda (,item ,val) (declare (ignore ,val)) ,(when done-form `(when ,done-form (return nil))) ,@body) ,set))))
4,136
Common Lisp
.lisp
89
42.157303
216
0.713536
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
98f831b3669b3ffdb82cf2ec2a271214ca42feaf5202b703dfdf4c19567e5f9e
6,776
[ -1 ]
6,777
kb-indexing-datastructures.lisp
white-flame_clyc/larkc-cycl/kb-indexing-datastructures.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun setup-indexing-tables (estimated-size) "[Cyc] Sets up all tables needed for the KB indexing. ESTIMATED-SIZE is the estimated # of constants." (let ((estimated-assertion-count (* 10 estimated-size))) (assertion-indexing-store-initialize estimated-assertion-count))) (defglobal *assertion-indexing-store* nil "[Cyc] The mapping between assertions and their indices.") (defun* assertion-indexing-store () (:inline t) *assertion-indexing-store*) (defun* assertion-indexing-store-reset (store) (:inline t) (setf *assertion-indexing-store* store)) (deflexical *meta-assertion-frequency* 0.015 "[Cyc] The estimated percentage of assertions that have meta-assertions.") (defun assertion-indexing-store-initial-size (&optional estimated-assertion-count) (if estimated-assertion-count (round (* estimated-assertion-count *meta-assertion-frequency*)) (if (kb-loaded) (round (* (assertion-count) *meta-assertion-frequency*)) 64))) (defun assertion-indexing-store-initialize (&optional estimated-assertion-count) (let ((initial-size (assertion-indexing-store-initial-size estimated-assertion-count))) (assertion-indexing-store-reset (make-hash-table initial-size #'eq))) ;; TODO - meaningful return value? *assertion-indexing-store*) (defun* assertion-indexing-store-get (assertion) (:inline t) (gethash assertion *assertion-indexing-store* (new-simple-index))) (defun assertion-indexing-store-set (assertion index) (if (eq index (new-simple-index)) (missing-larkc 31914) (setf (gethash assertion *assertion-indexing-store*) index))) (deflexical *unindexed-syntax-constants* (list #$implies #$and #$or #$not) "[Cyc] Constants which are part of the syntax and which therefore are not fully indexed.") (defun unindexed-syntax-constant-p (object) "[Cyc] Return T iff OBJECT is a constants which is part of the syntax and therefore not fully indexed." (member-eq? object *unindexed-syntax-constants*)) (defun indexed-term-p (object) "[Cyc] Returns T iff OBJECT is an indexed CycL term, e.g. a fort or assertion." (or (reified-term-p object) (indexed-unrepresented-term-p object))) (defun* indexed-unrepresented-term-p (object) (:inline t) "[Cyc] Returns T iff OBJECT is an indexed unrepresented CycL term, e.g., a string or number." (cycl-unrepresented-term-p object)) (defun valid-indexed-term? (object) "[Cyc] Returns T iff OBJECT is a valid indexed CycL term, i.e. a fort or an assertion." (cond ((fort-p object) (valid-fort? object)) ((assertion-p object) (valid-assertion? object)) ((indexed-unrepresented-term-p object) t))) (defun fully-indexed-term-p (object) "[Cyc] Return T iff OBJECT is the type which will be indexed in the other index, if necessary." (and (indexed-term-p object) (unindexed-syntax-constant-p object))) (defun valid-fully-indexed-term-p (object) "[Cyc] Return T iff OBJECT is the type which will be indexed in the other index, if necessary, and is valid." (and (valid-indexed-term? object) (not (unindexed-syntax-constant-p object)))) (defun term-index (term) (cond ((constant-p term) (when (valid-constant? term) (constant-index term))) ((nart-p term) (missing-larkc 30881)) ((assertion-p term) (assertion-index term)) ((indexed-unrepresented-term-p term) (unrepresented-term-index term)) ((auxiliary-index-p term) (get-auxiliary-index term)))) (defun reset-term-index (term index) "[Cyc] Primitively replaces TERM's index with INDEX." (cond ((fort-p term) (reset-fort-index term index)) ((hlmt-p term) nil) ((assertion-p term) (reset-assertion-index term index)) ((indexed-unrepresented-term-p term) (reset-unrepresented-term-index term index t)) ((auxiliary-index-p term) (reset-auxiliary-index term index)) (t (error "~s is not indexed" term))) ;; TODO - useful return value? term) (defun free-index (index) "[Cyc] Frees all resources consumed by INDEX." (cond ((simple-index-p index) (missing-larkc 31925)) ((complex-index-p index) (free-complex-index index)))) (defun free-term-index (term) "[Cyc] Frees all resources consumed by the index for TERM." (free-index (term-index term)) (reset-term-index term (new-simple-index))) (defun simple-index-p (object) "[Cyc] Return T iff OBJECT is a simple index." (and (listp object) (not (complex-index-p object)))) (defun* simple-indexed-term-p (term) (:inline t) (simple-index-p (term-index term))) (defun* new-simple-index () (:inline t) "[Cyc] Returns a new empty simple index." nil) (defun* simple-num-index (term) (:inline t) (length (term-index term))) (defun* simple-term-assertion-list (term) (:inline t) "[Cyc] Returns the list of all assertions referencing TERM. Note: result is NOT destructible!" (term-index term)) (defun* do-simple-index-term-assertion-list (term) (:inline t) (simple-term-assertion-list term)) (defun* reset-term-simple-index (term simple-index) (:inline t) (reset-term-index term simple-index)) (defun* complex-index-p (object) (:inline t) (subindex-p object)) (defun* complex-index-leaf-count (complex-index) (:inline t) (subindex-leaf-count complex-index)) (defun* complex-index-lookup (complex-index key) (:inline t) "[Cyc] Returns NIL or subindex-p or indexing-leaf-p." (subindex-lookup complex-index key)) (defun term-complex-index-lookup (term key) "[Cyc] Returns NIL or subindex-p." (when-let ((index (term-index term))) (complex-index-lookup index key))) (defun* initialize-term-complex-index (term) (:inline t) "[Cyc] Initializes a complex index for TERM. Clobbers any existing indexing for TERM." (initialize-term-subindex term)) (defun free-complex-index (complex-index) "[Cyc] Frees all resources consumed by COMPLEX-INDEX." (free-subindex complex-index)) (defun subindex-p (object) (or (intermediate-index-p object) (final-index-p object))) (defun subindex-lookup (subindex key) "[Cyc] Returns NIL or subindex-p or indexing-leaf-p." (cond ((intermediate-index-p subindex) (intermediate-index-lookup subindex key)) (t (missing-larkc 31922)))) (defun subindex-leaf-count (subindex) "[Cyc] Returns the number of indexing leaves anywhere below SUBINDEX." (if (intermediate-index-p subindex) (intermediate-index-leaf-count subindex) (final-index-leaf-count subindex))) (defun* initialize-term-subindex (term) (:inline t) "[Cyc]Initializes a subindex for TERM. Clobbers any existing indexing for TERM." (initialize-term-intermediate-index term)) (defun free-subindex (subindex) "[Cyc] Frees all resources consumed by SUBINDEX." (cond ((intermediate-index-p subindex) (free-intermediate-index subindex)) ((final-index-p subindex) (missing-larkc 31924)))) (defun intermediate-index-p (object) (and (consp object) (integerp (car object)) (hash-table-p (cdr object)))) (defun* new-intermediate-index (test-function) (:inline t) (cons 0 (make-hash-table :test test-function))) (defun* do-intermediate-index-valid-index-p (object) (:inline t) ;; TODO - Tests for non-NILness, which should be okay to just pass through. object) ;; Taken from kb-indexing.lisp relevant-mt-subindex-count-with-cutoff (defmacro do-intermediate-index ((key-var subindex-var intermediate-index) &body body) `(let ((index ,intermediate-index)) (when (do-intermediate-index-valid-index-p index) (block do-intermediate-index (dohash (,key-var ,subindex-var (intermediate-index-dictionary index)) ,@body))))) (defun* intermediate-index-lookup (intermediate-index key) (:inline t) "[Cyc] Returns NIL or subindex-p." (gethash key (intermediate-index-dictionary intermediate-index))) (defun* intermediate-index-keys (intermediate-index) (:inline t) "[Cyc] Returns a list of keys for INTERMEDIATE-INDEX." (hash-table-keys (intermediate-index-dictionary intermediate-index))) (defun intermediate-index-leaf-count (intermediate-index) "[Cyc] Returns the number of indexing leaves anywhere below INTERMEDIATE-INDEX." (car intermediate-index)) (defun intermediate-index-set (intermediate-index key value) "[Cyc] Does not reset the counts." (intermediate-index-dictionary-set intermediate-index key value) ;; TODO - useful return value? intermediate-index) (defun* intermediate-index-insert (intermediate-index keys leaf) (:inline t) "[Cyc] Returns whether it actually inserted (NIL if it was already there)." (intermediate-index-insert-int intermediate-index keys leaf nil)) (defun intermediate-index-insert-int (intermediate-index keys leaf key-history) "[Cyc] Insert LEAF at KEYS, having already gone down the keys in KEY-HISTORY." (destructuring-bind (key &rest rest-keys) keys (if rest-keys (let* ((new-key-history (nconc key-history (list key))) (subindex (intermediate-index-lookup-or-create-intermediate intermediate-index key new-key-history))) (when (intermediate-index-insert-int subindex rest-keys leaf new-key-history) ;; TODO - could be a tail call if this always returns non-NIL (intermediate-index-leaf-count-inc intermediate-index 1) t)) (let* ((subindex (intermediate-index-lookup-or-create-final intermediate-index key)) (old-count (final-index-leaf-count subindex))) (final-index-insert subindex leaf) (let ((new-count (final-index-leaf-count subindex))) (unless (= old-count new-count) ;; TODO - could be a tail call if this always returns non-NIL (intermediate-index-leaf-count-inc intermediate-index 1) t)))))) (defun intermediate-index-delete (intermediate-index keys leaf) "[Cyc] Returns whether it actually deleted (nil if it was already gone)." (destructuring-bind (key &rest rest-keys) keys (let ((subindex (intermediate-index-lookup intermediate-index key))) (when subindex (prog1 (if rest-keys (prog1-when (intermediate-index-delete subindex rest-keys leaf) (intermediate-index-leaf-count-inc intermediate-index -1)) (let ((old-count (final-index-leaf-count subindex))) (final-index-delete subindex leaf) (let ((new-count (final-index-leaf-count subindex))) (unless (= old-count new-count) ;; TODO - could be a tail call if this always returns non-NIL (intermediate-index-leaf-count-inc intermediate-index -1) t)))) (when (zerop (subindex-leaf-count subindex)) (intermediate-index-delete-key intermediate-index key))))))) (defun* intermediate-index-delete-key (intermediate-index key) (:inline t) "[Cyc] Delete any mapping from KEY to a subindex in INTERMEDIATE-INDEX." (intermediate-index-dictionary-delete-key intermediate-index key)) (defun* initialize-term-intermediate-index (term) (:inline t) "[Cyc] Initializes a top-level intermediate index for TERM. Clobbers any existing indexing for TERM." (reset-term-index term (new-intermediate-index #'eq))) (defun* free-intermediate-index (intermediate-index) (:inline t) "[Cyc] Frees all resources consumed by INTERMEDIATE-INDEX." (clrhash (intermediate-index-dictionary intermediate-index))) (defun* intermediate-index-leaf-count-reset (intermediate-index new-count) (:inline t) (rplaca intermediate-index new-count)) (defun intermediate-index-leaf-count-inc (intermediate-index delta) (let* ((old-count (intermediate-index-leaf-count intermediate-index)) (new-count (+ old-count delta))) (intermediate-index-leaf-count-reset intermediate-index new-count))) (defun intermediate-index-lookup-or-create-intermediate (intermediate-index key key-history) "[Cyc] Having already gone down the keys in KEY-HISTORY, look up KEY in INTERMEDIATE-INDEX. If not found, create a new intermediate index for KEY, with an equality test determined from KEY-HISTORY." (or (intermediate-index-lookup intermediate-index key) (let* ((equality-test (index-equality-test-for-keys key-history)) (subindex (new-intermediate-index equality-test))) (intermediate-index-set intermediate-index key subindex) subindex))) (defun intermediate-index-lookup-or-create-final (intermediate-index key) (or (intermediate-index-lookup intermediate-index key) (let ((subindex (new-final-index))) (intermediate-index-set intermediate-index key subindex) subindex))) (defun* intermediate-index-dictionary (intermediate-index) (:inline t) "[Cyc] Assumes INTERMEDIATE-INDEX is dictionary-style." (cdr intermediate-index)) (defun* intermediate-index-dictionary-set (intermediate-index key value) (:inline t) (setf (gethash key (intermediate-index-dictionary intermediate-index)) value)) (defun* intermediate-index-dictionary-delete-key (intermediate-index key) (:inline t) (remhash key (intermediate-index-dictionary intermediate-index))) (defun* final-index-p (object) (:inline t) (set-p object)) (defun* new-final-index () (:inline t) (new-set #'eq)) (defun* final-index-leaf-count (final-index) (:inline t) "[Cyc] Returns the number of indexing leaves in FINAL-INDEX." (set-size (final-index-set final-index))) (defun* final-index-insert (final-index leaf) (:inline t) "[Cyc] Is not required to check for membership before insertion." (set-add leaf (final-index-set final-index))) (defun* final-index-delete (final-index leaf) (:inline t) "[Cyc] Is not required to check for multiple elements to delete." (set-remove leaf (final-index-set final-index))) (defun* final-index-set (final-index) (:inline t) "[Cyc] Returns the set datastructure in FINAL-INDEX. Currently a final index _is_ a set, so this is the identity function." final-index)
15,512
Common Lisp
.lisp
290
48.237931
125
0.718296
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
335b3631f7060f1ae4c08548790732e55b3fa2f4141509fa3b6e658d11fb9eb5
6,777
[ -1 ]
6,778
variables.lisp
white-flame_clyc/larkc-cycl/variables.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defconstant *hl-variable-prefix-char* #\? "[Cyc] The character used as the first character of an HL variable's name.") (defconstant *default-el-variable-prefix* "?VAR" "[Cyc] The prefix for all default EL vars. By no coincidence, it is the upcase version of the prefix in PRINT-VARIABLE.") (defstruct (variable (:conc-name "VAR-")) id) (defmethod sxhash ((object variable)) (or (var-id object) 99)) (deflexical *variable-max* 200 "[Cyc] The total number of interned HL variables.") (defglobal *variable-array* nil) (defun* get-variable (num) (:inline t) "[Cyc] Return HL variable number NUM." (aref *variable-array* num)) (defun setup-variable-table () "[Cyc] Setup the array of interned HL variables." ;; TODO - Lazy initialization might be after *variable-max* is updated. Else, allocate it up front. (unless *variable-array* (setf *variable-array* (prog1-let ((array (make-vector *variable-max*))) (dotimes (i *variable-max*) (setf (aref array i) (make-variable :id i))))))) (defun* variable-id (variable) (:inline t) "[Cyc] Return ID of HL variable VARIABLE." (var-id variable)) ;; TODO - obsolete (defun* find-variable-by-id (id) (:inline t) "[Cyc] Return the HL variable wiht ID, or NIL if not present." (get-variable id)) (defun* variable-< (var1 var2) (:inline t) (< (variable-id var1) (variable-id var2))) (defun-memoized default-el-var-for-hl-var (variable) (:test eq :doc "[Cyc] Return a readable EL var from HL var VARIABLE.") (make-el-var (prin1-to-string variable))) (defun* sort-hl-variable-list (hl-variable-list) (:inline t) (sort hl-variable-list #'variable-<)) (defun* fully-bound-p (object) (:inline t) "[Cyc] Return T iff OBJECT contains no HL variables, and therefore is fully bound." (not (not-fully-bound-p object))) (defun not-fully-bound-p (object) "[Cyc] Return T iff OBJECT contains some HL variable, and therefore is not fully bound." (if (atom object) (variable-p object) ;; TODO - this is a form of SOME that also tests the dotted value? (do* ((rest object (cdr rest)) (next (car rest) (car rest))) ((atom (cdr rest)) (or (not-fully-bound-p next) (variable-p (cdr rest))))))) (defun* cycl-ground-expression-p (expression) (:inline t) (not (expression-find-if #'cyc-var? expression)))
3,864
Common Lisp
.lisp
81
42.851852
123
0.701787
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
8509abe4b4e660abb48286fd71c0d2825377cb443f1b3f386948cbeb4e410738
6,778
[ -1 ]
6,779
id-index.lisp
white-flame_clyc/larkc-cycl/id-index.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO DESIGN - yet another hashtable replacement. This one uses an array to look up non-negative integer keys. Are these limited to fixnums? Since they should map to array indices, which must fit in address space, it seems like they would, unless there's some offsetting delta that I'm not seeing. ;; TODO DESIGN - it seems like what's entered into the new-objects table is always <= next-id's value, looking at how optimize-id-index works. That means there's no real reason to use the hashtable, and might as well simply grow the array whenever next-id breaches the array size. ;; id-index-old-object-id-p tests for negative indices, which always falls back into the hasthable. However, there could be another array holding negated indices. Need to test how this stuff is used. ;; The old-objects vector is manually grown, so that the object itself can remain a simple-vector with optimized dereferencing, as opposed to using vector-push-extend ;; Need to know if arrays grow unboundedly or settle into some final size. If the latter, then we can perform a lot of small grow operations, and the speed will amortize away over time without being wasteful in overallocation, and still be faster to dereference than the split array/hashtable implementation. ;; The original code had an empty-list marker (symbol, replaced to NIL in results), and a 'tombstone' marker for unused entries (NIL, replaced to the default in results). The older model does more comparison than necessary, and has to do conversion on insertion. ;; I think SubL might have had to do this if it cannot control the default value of arrays and they might have always been NIL. ;; Tombstones are only used in the array, not in the hashtable. ;; Rewrote into using only tombstone marker, keeping NIL as an empty list untouched. (defconstant +id-index-tombstone+ :%tombstone) (defun* id-index-tombstone () (:inline t) +id-index-tombstone+) (defstruct (id-index (:conc-name "IDIX-")) lock ;; Total number of objects being held (old+new) (count 0 :type fixnum) (next-id 0 :type fixnum) ;; vector of objects for fast lookup (old-objects #() :type simple-vector) ;; hashtable of new entries before growing the old-objects vector new-objects) (defmacro with-idix-lock (id-index &body body) `(bt:with-lock-held ((id-index-lock ,id-index)) ,@body)) (defun* id-index-lock (id-index) (:inline t) "[Cyc] Return the lock used to control modifications of ID-INDEX." (idix-lock id-index)) (defun* id-index-count (id-index) (:inline t) "[Cyc] Return the total number of objects indexed in ID-INDEX." (idix-count id-index)) (defun* id-index-next-id (id-index) (:inline t) "[Cyc] Return the next internal ID which would be used in ID-INDEX." (idix-next-id id-index)) (defun* set-id-index-next-id (id-index next-id) (:inline t) (declare (fixnum next-id)) "[Cyc] Start reserving internal IDs in ID-INDEX at NEXT-ID." (setf (idix-next-id id-index) next-id)) (defun* id-index-old-objects (id-index) (:inline t) "[Cyc] Return the vector for old objects in ID-INDEX." (idix-old-objects id-index)) (defun* id-index-new-objects (id-index) (:inline t) "[Cyc] Return the hashtable for new objects in ID-INDEX." (idix-new-objects id-index)) (defun* id-index-empty-p (id-index) (:inline t) "[Cyc] Return T iff ID-INDEX is empty." (zerop (id-index-count id-index))) (defun* id-index-new-object-count (id-index) (:inline t) "[Cyc] Return the number of new objects in ID-INDEX." (hash-table-count (id-index-new-objects id-index))) (defun* id-index-old-object-count (id-index) (:inline t) "[Cyc] Return the number of old objects in ID-INDEX." (- (id-index-count id-index) (id-index-new-object-count id-index))) (defun* id-index-new-id-threshold (id-index) (:inline t) "[Cyc] Return the ID at which new objects start in ID-INDEX." (length (id-index-old-objects id-index))) (defun* id-index-old-object-id-p (id-index id) (:inline t) (declare (fixnum id)) ;; TODO DESIGN - can probably eliminate the non-negative-integer-p check and just leave the fixnum declaration, since optimize-id-index will break if negative indexes are placed into the new-objects table anwyay. (and (non-negative-integer-p id) (< id (id-index-new-id-threshold id-index)))) ;; TODO - this seems kinda huge. Measure how big these get. (deflexical *id-index-default-scaling-factor* 100 "[Cyc] Number of old entries anticipated for each new entry.") (deflexical *id-index-equality-test* #'eq "Used to define the hashtable test for array spillover values. Seems like it'll stay fixnums.") (defun new-id-index (&optional (old-objects-size 0) (new-id-start old-objects-size)) "[Cyc] Return a new ID-INDEX with ids for new entries starting at NEW-ID-START. Access to OLD-OBJECTS-SIZE number of ids starting at 0 will be optimized." (let* ((new-objects-size (max 10 (floor old-objects-size *id-index-default-scaling-factor*)))) (make-id-index :lock (bt:make-lock "ID-INDEX") :count 0 :next-id new-id-start :old-objects (make-vector old-objects-size (id-index-tombstone)) :new-objects (make-hash-table :test *id-index-equality-test* :size new-objects-size)))) (defun id-index-reserve (id-index) "[Cyc] Reserve an internal ID from ID-INDEX and return it." (with-idix-lock id-index (let ((next-id (id-index-next-id id-index))) (setf (idix-next-id id-index) (1+ next-id)) next-id))) (defun* id-index-tombstone-p (object) (:inline t) (eq object (id-index-tombstone))) (declaim (inline id-index-lookup-int)) (defun id-index-lookup-int (id-index id) "[Cyc] Return the object associated with ID in ID-INDEX." (if (id-index-old-object-id-p id-index id) (aref (id-index-old-objects id-index) id) ;; Added a default tombstone for hash lookups (gethash id (id-index-new-objects id-index) (id-index-tombstone)))) (defun* id-index-lookup (id-index id &optional default) (:inline t) (declare (inline id-index-lookup-int) (fixnum id)) (let ((result (id-index-lookup-int id-index id))) (if (id-index-tombstone-p result) default result))) (defun* id-index-enter-unlocked (id-index id object) (:inline t) (declare (fixnum id)) "[Cyc] Enter OBJECT in ID-INDEX as the object associated with the key ID. ID-INDEX is assumed to be already locked from the outside." (let ((existing (id-index-lookup-int id-index id))) (if (id-index-old-object-id-p id-index id) (setf (aref (id-index-old-objects id-index) id) object) (setf (gethash id (id-index-new-objects id-index)) object)) ;; Increment the count only if we overwrote an empty slot (when (id-index-tombstone-p existing) (incf (idix-count id-index))))) (defun id-index-enter (id-index id object) "[Cyc] Enter OBJECT in ID-INDEX as the object associated with the key ID. ID-INDEX is locked during the modification." (with-idix-lock id-index (id-index-enter-unlocked id-index id object))) (defun id-index-enter-autoextend (id-index id object) "[Cyc] Enter OBJECT in ID-INDEX as the object associated with the keY ID. ID-INDEX is locked during the modification. If the insert fills up the old objects vector, grow the vector." (id-index-enter id-index id object) (id-index-possibly-autoextend id-index id)) (defun id-index-possibly-autoextend (id-index id) "[Cyc] If ID was the last id in oldspace, grow the vector." (let ((threshold (id-index-new-id-threshold id-index))) (declare (fixnum threshold id)) (when (>= (the fixnum (1+ id)) threshold) (optimize-id-index id-index (+ 2 (max threshold id)))))) (defun id-index-remove (id-index id) (declare (fixnum id)) "[Cyc] Remove any association for ID in ID-INDEX." (with-idix-lock id-index (let ((existing (id-index-lookup-int id-index id))) (if (id-index-old-object-id-p id-index id) (setf (aref (id-index-old-objects id-index) id) (id-index-tombstone)) (remhash id (id-index-new-objects id-index))) ;; Only decrement the count if the item was found (unless (id-index-tombstone-p existing) (decf (idix-count id-index)))))) (defun clear-id-index (id-index) "[Cyc] Remove all ID associations in ID-INDEX." (with-idix-lock id-index (setf (idix-count id-index) 0) (fill (id-index-old-objects id-index) (id-index-tombstone)) (clrhash (id-index-new-objects id-index)))) ;; Macro helpers, were used in the expansion in id-index-values (defun* id-index-skip-tombstones-p (tombstone) (:inline t) (eq :skip tombstone)) (defun* id-index-objects-empty-p (id-index tombstone) (:inline t) (when (id-index-skip-tombstones-p tombstone) (id-index-empty-p id-index))) (defun* id-index-old-objects-empty-p (id-index tombstone) (:inline t) (when (id-index-skip-tombstones-p tombstone) (zerop (id-index-old-object-count id-index)))) (defun* id-index-new-objects-empty-p (id-index) (:inline t) (zerop (id-index-new-object-count id-index))) ;; TODO - the tombstone variable is very annoying, with its :skip option. I think the "hide tombstone" default value should be the tombstone symbol itself, since there's now 2 separate special values to check for (:%tombstone and :skip) all in the same value space, and the predicates for checking them are very poorly named. (defmacro do-id-index ((id object id-index &key (tombstone :skip tombstone-p) ordered progress-message done) &body body) "Iterate over all values in the id-index, binding id/object to the stored key/value. If the :tombstone is T then tombstones will be iterated as well with value NIL; else they are skipped." ;; TODO - don't know what DONE is supposed to do (when done (error ":DONE not supported on DO-ID-INDEX")) ;; Reconstructed from constant-handles set-next-constant-suid (alexandria:with-gensyms (total sofar new-ht) (alexandria:once-only (id-index tombstone) `(let ((,total (id-index-count ,id-index)) (,sofar 0)) ;; TODO - only use noting-percent-progress when :progress-message is provided (noting-percent-progress (,progress-message) ;; Skip if empty (unless (id-index-objects-empty-p ,id-index ,tombstone) ;; Vector (old contents) (unless (id-index-old-objects-empty-p ,id-index ,tombstone) (dovector (,id ,object (id-index-old-objects ,id-index)) (unless (id-index-tombstone-p ,object) (note-percent-progress ,sofar ,total) (incf ,sofar) ,@body))) ;; Hashtable (new contents) (unless (id-index-new-objects-empty-p ,id-index) ;; Ordered must iterate the index values ,(if ordered `(loop with ,new-ht = (id-index-new-objects ,id-index) for ,id from (id-index-new-id-threshold ,id-index) below (id-index-next-id ,id-index) for ,object = (gethash ,id ,new-ht ,(if tombstone-p tombstone `(id-index-tombstone))) do (unless ,(if tombstone-p nil `(id-index-tombstone-p ,object)) (note-percent-progress ,sofar ,total) (incf ,sofar) ,@body)) ;; Unordered can just hit the hashtable entries ;; but only if we're skipping tombstones (if tombstone-p (error ":ORDERED + :TOMBSTONE can't both be used in DO-ID-INDEX.") `(dohash (,id ,object (id-index-new-objects ,id-index)) (note-percent-progress ,sofar ,total) (incf ,sofar) ,@body)))))))))) (defconstant *cfasl-wide-opcode-id-index* 128) (defun optimize-id-index (id-index &optional size) "[Cyc] Optimize ID-INDEX by merging the new objects into the old objects." (with-idix-lock id-index (let* ((next-id (id-index-next-id id-index)) (new-size (if size (max size next-id) next-id)) (new-objects (id-index-new-objects id-index)) (old-objects (id-index-old-objects id-index)) (old-object-limit (length old-objects))) (declare (fixnum next-id new-size old-object-limit)) (when (> new-size old-object-limit) (let ((optimized-old-objects (make-vector new-size (id-index-tombstone)))) (replace optimized-old-objects old-objects) ;; TODO DESIGN - no allowance for negative IDs, which id-index-old-object-id-p checks for (dohash (id object new-objects) (setf (aref optimized-old-objects id) object)) (setf (idix-old-objects id-index) optimized-old-objects) (clrhash new-objects)))))) (defun id-index-values (id-index) "[Cyc] Returns a list of the values of ID-INDEX." (let ((values nil) (old-objects (id-index-old-objects id-index)) (new-objects (id-index-new-objects id-index))) ;; The original loop did strange things with tombstone values that seem degenerate. ;; There are a ton of do-* macros declared, so probably an effect from those. (loop for id from 0 below (min (length old-objects) (id-index-count id-index)) do (let ((object (aref old-objects id))) (unless (id-index-tombstone-p object) (push object values)))) (dohash (id object new-objects) (declare (ignore id)) (unless (id-index-tombstone-p object) (push object values))) (nreverse values)))
15,332
Common Lisp
.lisp
263
50.939163
325
0.67593
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
11c89d788cd8b5095e693e633fbef2797bc2e5fdc5dcdbaf078a2f4d5233d5e5
6,779
[ -1 ]
6,780
control-vars.lisp
white-flame_clyc/larkc-cycl/control-vars.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO DESIGN - Nothing in the code ever sets this to NIL, so the #$ can't be used in bootstrap? ;; HACK - setting it to NIL for now (defparameter *read-require-constant-exists* nil ;;t "[Cyc] Does the #$ reader error if the referenced constant does not exist?") (defglobal *table-area* nil) (defvar *rkf-mt* nil "[Cyc] The mt within which RKF interactions are assumed.") (defglobal *hl-lock* (bt:make-lock "HL Store Lock") "[Cyc] Controls modification of the HL store") (defparameter *bootstrapping-kb?* nil) (deflexical *keywords-package* (find-package "KEYWORD")) (deflexical *sublisp-package* (find-package "SUBLISP")) ;; TODO - clyc? subl? (deflexical *cyc-package* (find-package "CYC")) ;; TODO - clyc? (defparameter *cnf-matching-predicate* 'equal "[Cyc] predicate used to compare two cnfs when searching for an assertion (or axiom) in the kb") (defparameter *gaf-matching-predicate* 'equal "[Cyc] predicate used to compare two gaf formulas when searching for an assertion (or axiom) in the kb") (defparameter *nat-matching-predicate* 'equal "[Cyc] predicate used to compare two nat formulas when searching for a reified nat in the kb") (defparameter *candidate-assertion* nil "[Cyc] used for robust assertion lookup in find-assertions-*") (defparameter *variable-names* nil) (defparameter *assertion-truth* :true) (defparameter *mapping-answer* nil) (defparameter *mapping-pred* nil) (defparameter *mapping-source* nil) (defparameter *mapping-target* nil) (defparameter *mapping-target-arg* nil) (defparameter *mapping-index-arg* nil) (defparameter *mapping-gather-arg* nil) (defparameter *mapping-gather-args* nil) (defparameter *mapping-output-stream* t) (defparameter *mapping-equality-test* #'eq) (defparameter *mapping-any-answer?* nil) (defparameter *mapping-relation* nil) (defparameter *mapping-finished-fn* nil) (defparameter *mapping-path* nil) (defparameter *mapping-data-1* nil) (defparameter *mapping-data-2* nil) (defparameter *mapping-pivot-arg* #'identity) (defparameter *mapping-gather-key-args* nil) (defparameter *mapping-assertion-selection-fn* nil) (defparameter *mapping-assertion-bookkeeping-fn* nil) (defparameter *mapping-fn* *unprovided* "[Cyc] function applied in mapping-funcall-arg") (defparameter *mapping-fn-arg* 1 "[Cyc] designates non-default argument in mapping-funcall-arg") (defparameter *mapping-fn-arg1* *unprovided* "[Cyc] default arg1 in mapping-funcall-arg") (defparameter *mapping-fn-arg2* *unprovided* "[Cyc] default arg2 in mapping-funcall-arg") (defparameter *mapping-fn-arg3* *unprovided* "[Cyc] default arg3 in mapping-funcall-arg") (defparameter *mapping-fn-arg4* *unprovided* "[Cyc] default arg4 in mapping-funcall-arg") (defparameter *mapping-fn-arg5* *unprovided* "[Cyc] default arg5 in mapping-funcall-arg") (defparameter *mapping-fn-arg6* *unprovided* "[Cyc] default arg6 in mapping-funcall-arg") (defparameter *mapping-fn-arg7* *unprovided* "[Cyc] default arg7 in mapping-funcall-arg") (defparameter *mapping-fn-arg8* *unprovided* "[Cyc] default arg8 in mapping-funcall-arg") (defparameter *kba-pred* nil) (defparameter *standard-indent-string* " ") (defparameter *term-functional-complexity-cutoff* nil "[Cyc] The maximum function complexity of CycL allowed by the system. NIL means 'no limit'.") (defparameter *term-relational-complexiy-cutoff* nil "[Cyc] The maximum relational complexity of CycL allowed by the system. NIL means 'no limit'.") (defparameter *collect-justification-compilations?* nil "[Cyc] compile successful inference chains into macro rules?") (defparameter *justification-compilations* nil "[Cyc] candidate macro rules are recorded here") (defparameter *ebl-trace* 0 "[Cyc] tracing level for ebl module [0..5]") (defparameter *allow-forward-skolemization* nil "[Cyc] Do we allow skolemization during forward inference?") (defparameter *prefer-forward-skolemization* nil "[Cyc] Do we prefer skolemization during forward inference? This option will make forward inference tend not to unify to existing NARTs so that new NARTs can be created if they would come into existence (see nat-lookup-pos-preference.)") (defparameter *perform-unification-occurs-check* t "[Cyc] Do we check for and reject unifications where a variable appears in its own binding?") (defparameter *perform-equals-unification* t "[Cyc] Do we use #$equals assertions within term unification?") (defparameter *allow-backward-gafs* t "[Cyc] Do we allow backward gafs?") (defparameter *cached-ask-result-direction* :forward "[Cyc] The direction to use for cached ask results.") (defparameter *check-for-circular-justs* t "[Cyc] Do we check for circularly justified assertions?") (defparameter *filter-deductions-for-trivially-derivable-gafs* nil "[Cyc] Do we ignore deductions for gafs which are already trivially derivable?") (defparameter *inference-debug?* nil "[Cyc] Whether the inference engine is to be run in debug mode.") (defvar *browse-forward-inferences?* nil "[Cyc] Whether forward inferences will be browsable. If NIL, they will be destroyed after use, along with their problem stores. If T, problem store descruction may never happen for many problem stores--BE CAREFUL") (defun browse-forward-inferences? () *browse-forward-inferences?*) (defparameter *query-properties-inherited-by-recursive-queries* '(:productivity-limit :removal-backtracking-productivity-limit) "[Cyc] The query properties that should be inherited by recursive queries.") (defparameter *proof-checking-enabled* nil "[Cyc] Are we using the inference engine as a proof-checker?") (defparameter *proof-checker-rules* nil "[Cyc] allowable rules") (defparameter *inference-propagate-mt-scope* nil) (defparameter *inference-current-node-mt-scope* nil) (defparameter *inference-literal* nil) (defparameter *inference-sense* nil) (defparameter *inference-arg* nil) (defparameter *inference-more-supports* nil) (defparameter *inference-highly-relevant-assertions* nil "[Cyc] Axioms specified by #$highlyRelevantAssertion.") (defparameter *inference-highly-relevant-mts* nil "[Cyc] Microtheories specified by highlyRelevantMt.") (defparameter *within-hl-failure-backchaining?* nil) (defparameter *hl-failure-backchaining* nil "[Cyc] Do we backchain on HL predicates?") (defparameter *evaluatable-backchain-enabled* nil "[Cyc] Do we backchain on evaluatable predicates?") (defparameter *negation-by-failure* nil "[Cyc] Do we allow the minimization inference methods to fire?") (defparameter *complete-extent-minimization* t "[Cyc] Do we allow use of the 'complete extent' HL inference modules?") (defparameter *unbound-rule-backchain-enabled* nil "[Cyc] Do we allow backchaining using the unbound rule index.") (deflexical *default-removal-cost-cutoff* 10000) (defparameter *removal-cost-cutoff* *default-removal-cost-cutoff* "[Cyc] How expensive a removal do we allow (NIL for no restriction).") (defparameter *forward-inference-removal-cost-cutoff* *default-removal-cost-cutoff* "[Cyc] How expensive a removal do we allow during forward inference (NIL for no restriction).") (defparameter *application-filtering-enabled* nil) (defparameter *marking-doomed-inference-ancestors* nil "[Cyc] When a goal node is rejected, do we mark all its semantically invalid ancestors as doomed, thereby cutting off large chunks of search which will fail.") (defparameter *inference-search-strategy* :heuristic) (defparameter *unique-inference-result-bindings* t) (defparameter *inference-answer-handlers* t "[Cyc] The handler function to use when generating the results to return from inference searches.") (defparameter *hl-module-simplification-cost* 0.1 "[Cyc] The cost value used for performing an HL module simplification step.") (defparameter *hl-module-check-cost* 0.5 "[Cyc] The cost value used for performing fully-bound HL module checks.") (deflexical *cheap-hl-module-check-cost* 0.5 "[Cyc] The cost value used for performing cheap fully-bound HL module checks.") (deflexical *typical-hl-module-check-cost* 1.0 "[Cyc] The cost value used for performing typical fully-bound HL module checks.") (deflexical *expensive-hl-module-check-cost* 1.5 "[Cyc] The cost value used for performing expensive fully-bound HL module checks.") (deflexical *expensive-hl-module-singleton-generate-costs* *expensive-hl-module-check-cost* "[Cyc] The cost value used for performing expensive HL module generations.") (deflexical *maximum-hl-module-check-cost* nil "[Cyc] When non-NIL, the maximum cost value allowable for fully-bound HL module checks.") (defparameter *average-all-isa-count* 38 "[Cyc] An estimate of the total number of types for the average term.") (defparameter *average-all-genls-count* 47 "[Cyc] An estimate of the total number of superclasses for the average collection.") (defparameter *pgia-active?* nil) (defparameter *the-term-inference-enabled* nil "[Cyc] Global control of whether we ever allow any the-term reasoning at all.") (defparameter *allow-the-term-unification* nil "[Cyc] Controls whether the unifier treats the-terms as variables. Should always be globally NIL and bound to T by the-term inference methods.") (defparameter *inference-the-term-bindings* nil) (defparameter *the-term-qua-constant* nil) (defparameter *external-inference-enabled* nil "[Cyc] Determines whether or not External HL module inferencing is enabled.") (defparameter *suppress-conflict-notices?* nil) (defparameter *ignore-conflicts?* nil) (defparameter *conflicts-from-invalid-deductions* nil "[Cyc] Do we treat semantically invalid deductions as conflicts?") (defparameter *record-inconsistent-support-sets* nil "[Cyc] When non-NIL, sets of mutually inconsistent HL supports are stored on the variable *INCONSISTENT-SUPPORT-SETS*") (deflexical *last-agenda-op* nil) (deflexical *last-agenda-error-message* nil) (deflexical *last-agenda-error-explanatory-supports* nil "[Cyc] A list - containing either one or more assertions or a list of the form (#$equals <term> <term>) - the contents of which accounts for the halting of the agenda.") (defparameter *agenda-display-fi-warnings* nil) (defparameter *ignore-remote-errors* t "[Cyc] Do we ignore remote errors or handle them the same way as local errors?") (defglobal *auto-increment-kb* nil "[Cyc] This determines whether or not the image will change to the next KB when teh close-kb transcript operation is reached.") (deflexical *load-submitted-transcripts?* nil "[Cyc] Controls whether the running image will load submitted transcripts via MAYBE-LOAD-SUBMITTED-TRANSCRIPT.") (deflexical *send-submitted-transcript-loading-notices?* nil "[Cyc] Controls whether, when a submitted transcript is loaded, the image should notify the submitter that it is being loaded as part of a build.") (defvar *cyc-image-id* nil "[Cyc] A string consisting of '<machine-name>-<universal-time>-<process-id>'.") ;; TODO - referenced from kb-accessors (missing-function-implementation mapping-funcall-arg) (defun make-cyc-image-id () "[Cyc] Make a unique identifier for a cyc image: '<machine-name>-<universal-time>-<process-id>" (let ((machine-name (string-downcase (machine-instance))) (process-id #+sbcl (write-to-string (sb-posix:getpid)) #-sbcl "unknownpid") (cyc-universal-time (universal-timestring))) (format nil "~a-~a-~a" machine-name cyc-universal-time process-id))) (defun set-cyc-image-id () (setf *cyc-image-id* (make-cyc-image-id))) (defun cyc-image-id () "[Cyc] Accessor for *CYC-IMAGE-ID*" *cyc-image-id*) (defglobal *build-kb-loaded* nil) (defun set-build-kb-loaded (kb) (when kb (check-type kb 'integerp)) (setf *build-kb-loaded* kb)) (defglobal *kb-loaded* nil) (defun kb-loaded () "[Cyc] @return nil or integerp; Return the current KB version." *kb-loaded*) (defun set-kb-loaded (kb) (when kb (check-type kb 'integerp)) (setf *kb-loaded* kb)) (defun non-tiny-kb-loaded? () "[Cyc] Does the KB contain a nontrivial amount that is not the core (tiny) KB?" ;; TODO - distant forward references from SubL into CycL. These should be moved into a CycL library (and (> (funcall 'constant-count) 10000) (< 8 (truncate (funcall 'assertion-count) (funcall 'fort-count))))) (defglobal *kb-pedigree* :unknown) (defparameter *use-transcript?* t) (defglobal *run-own-operations?* t) (defglobal *caught-up-on-master-transcript* nil "[Cyc] Boolean: This is used by the agenda to decide whether or not to wait before doing another read.") (defglobal *communication-mode* :unknown) (defparameter *unencapsulating-within-agenda* nil) (defvar *save-asked-queries?* nil "[Cyc] Whether to save queries asked into a query transcript.") (defun save-asked-queries? () (and *save-asked-queries?* (non-tiny-kb-loaded?) (typep (kb-loaded) '(integer 0)))) (defglobal *init-file-loaded?* nil) (defparameter *within-assert* nil) (defparameter *within-unassert* nil) (defparameter *within-ask* nil) (defparameter *within-query* nil) (defun within-ask? () *within-ask*) (defun within-query? () (or *within-ask* *within-query*)) (defun within-assert? () *within-assert*) (defparameter *compute-inference-results* t) (defparameter *cache-inference-results* nil "[Cyc] Do we cache the results of successful inference in the KB?") (defparameter *transformation-depth-cutoff* nil) (defparameter *show-assertions-in-english* nil "[Cyc] boolean; Should assertions be displayed in English?") (defparameter *assume-cyc-cyclist-dialog?* t "[Cyc] boolean; Should we assume Cyc is talking to the currently-logged-in Cyclist when generating NL in the CB interface?") (defparameter *show-fet-edit-buttons?* t "[Cyc] boolean; Should terms have links to edit term with FET?") (defparameter *show-fet-create-instance-buttons?* t "[Cyc] boolean; Should collections have links to create instance with FET?") (defparameter *show-fet-create-spec-buttons?* nil "[Cyc] boolean; Should collections have links to create spec with FET?") (defparameter *cb-literal-query-results-one-per-line?* nil "[Cyc] boolean; Should literal query result terms be displayed one per line?") (defparameter *cb-skolem-applicable-relations?* nil "[Cyc] boolean; Should skolem applicable relations be displayed?") (defparameter *cb-applicable-relations-one-per-line?* nil "[Cyc] boolean; Should applicable relations be displayed one per line?") (defparameter *cb-paraphrase-applicable-relations?* nil "[Cyc] boolean; Should applicable relations be paraphrased?") (defparameter *meta-query-start-string* nil) (defparameter *current-cache* nil) (defparameter *dbm-init-file-loaded?* nil "[Cyc] Has the db meta query init file successfully loaded, or not?") (defparameter *dbm-cache-loading-started?* nil) (defparameter *dbm-cache-loading-finished?* nil) (defglobal *acip-subkernel-extraction* nil "[Cyc] When non-NIL, the ACIP subkernel we are currently extracting.") (defglobal *acip-subkernel-output-stream* nil "[Cyc] When non-NIL, the stream we are using for output of the ACIP subkernel we are extracting.") (defparameter *janus-tag* nil "[Cyc] This tag will be inserted into every Janus operation that is logged.") (defparameter *janus-new-constants* nil) (defparameter *janus-test-case-logging?* nil) (defparameter *janus-operations* nil) (defparameter *janus-extraction-deduce-specs* nil) (defparameter *janus-within-something?* nil) (defparameter *janus-testing-deduce-specs* nil) (defparameter *janus-test-case-running?* nil) (defvar *ask-quirk?* nil) (defvar *curried-kbq-lookup?* t "[Cyc] Whether to use #$sentenceParameterValueInSpecification, #$microtheoryParameterValueInSpecification, and #$inferenceModeParameterValueInSpecification for lookup") (defparameter *kbq-run-query-auto-destroy-enabled?* t "[Cyc] When non-NIL, the inferences and problem-stores generated by KBQ-RUN-QUERY are auto-destroyed.") (defparameter *kbq-run-query-non-continuable-enabled?* t "[Cyc] When non-NIL, the inferences generated by KBQ-RUN-QUERY are always run with :CONTINUABLE? NIL since they won't ever be continued.")
17,481
Common Lisp
.lisp
315
53.390476
239
0.769577
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
88136f41fefb838f6730d5d937f14a0bca10fba7bd6d44a4ab8976675eb3a7ba
6,780
[ -1 ]
6,781
wff-macros.lisp
white-flame_clyc/larkc-cycl/wff-macros.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun* within-wff? () (:inline t) "[Cyc] Return T iff currently within wff checking." *within-wff?*) ;; TODO - where's the defun-memoized that matches this? (defun* possibly-new-wff-memoization-state () (:inline t) (or *wff-memoization-state* (new-memoization-state))) (defun new-wff-special-variable-state (properties) (check-wff-properties properties) (let ((svs (new-special-variable-state nil))) (dohash (indicator data (wff-properties-table)) (destructuring-bind (var default) data (when var (let ((desired-value (getf properties indicator default))) (unless (equal desired-value default) (missing-larkc 31672)))))) svs))
2,100
Common Lisp
.lisp
44
43.613636
77
0.747668
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
1f6e77606805a5dc92b375fec454223ee01de9c8a6bcc1428ba88b5b6f088961
6,781
[ -1 ]
6,782
kb-hl-supports.lisp
white-flame_clyc/larkc-cycl/kb-hl-supports.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO - Ugh, this file is quite important, but came with nearly zero comments. ;; kb-hl-support = simple id ;; hl-support ;; hl-support-content (defun* find-kb-hl-support (hl-support) (:inline t) (or (find-kb-hl-support-during-creation hl-support) (lookup-kb-hl-support hl-support))) (defun* find-kb-hl-support-by-id (id) (:inline t) (lookup-kb-hl-support-by-id id)) (defun* 9find-kb-hl-supports-mentioning-term (term) (:inline t) (lookup-kb-hl-supports-mentioning-term term)) (defun* kb-hl-support-count () (:inline t) (if *kb-hl-supports-from-ids* (id-index-count *kb-hl-supports-from-ids*) 0)) (defun* kb-hl-support-id (kb-hl-support) (:inline t) (kb-hl-support-get-id kb-hl-support)) (defun* do-kb-hl-support-dependents-helper (kb-hl-support) (:inline t) (kb-hl-support-content-get-dependents (kb-hl-support-content kb-hl-support))) (defun kb-hl-support-hl-support (kb-hl-support) (let* ((content (kb-hl-support-content kb-hl-support)) (argument (kb-hl-support-content-get-argument content))) (cond ((deduction-p argument) (deduction-assertion argument)) ((hl-support-p argument) argument)))) (defun kb-hl-support-sentence (kb-hl-support) (let ((hl-support (kb-hl-support-hl-support kb-hl-support))) (when (hl-support-p hl-support) (hl-support-sentence hl-support)))) (defun kb-hl-support-tv (kb-hl-support) (let ((hl-support (kb-hl-support-hl-support kb-hl-support))) (when (hl-support-p hl-support) (hl-support-tv hl-support)))) (defun* find-or-possibly-create-kb-hl-support (hl-support) (:inline t) (or (find-kb-hl-support hl-support) (possibly-create-kb-hl-support hl-support))) (defstruct (kb-hl-support (:conc-name "KB-HLS-")) id) (defmethod sxhash ((object kb-hl-support)) (or (kb-hls-id object) 787)) (defun new-kb-hl-support (id) (make-kb-hl-support :id id)) (defun free-kb-hl-support (kb-hl-support) (setf (kb-hls-id kb-hl-support) nil)) (defstruct (kb-hl-support-content (:conc-name "KB-HLSC-")) argument dependents) (defun new-kb-hl-support-content () (make-kb-hl-support-content)) (defun free-kb-hl-support-content (kb-hl-support-content) (setf (kb-hlsc-argument kb-hl-support-content) nil) (setf (kb-hlsc-dependents kb-hl-support-content) nil)) ;; TODO - spurious accessors? (defun* kb-hl-support-content-get-argument (kb-hl-support-content) (:inline t) (kb-hlsc-argument kb-hl-support-content)) (defun* kb-hl-support-content-get-dependents (kb-hl-support-content) (:inline t) (kb-hlsc-dependents kb-hl-support-content)) (defun* kb-hl-support-content-set-argument (kb-hl-support-content deduction) (:inline t) (setf (kb-hlsc-argument kb-hl-support-content) deduction)) (defun* kb-hl-support-content-set-dependents (kb-hl-support-content dependents) (:inline t) (setf (kb-hlsc-dependents kb-hl-support-content) dependents)) (defun make-kb-hl-support-shell (id) (let ((kb-hl-support (new-kb-hl-support id))) (register-kb-hl-support-id id kb-hl-support) kb-hl-support)) (defun* kb-hl-support-content (kb-hl-support) (:inline t) (lookup-kb-hl-support-content (kb-hl-support-get-id kb-hl-support))) (defun kb-hl-support-add-dependent (kb-hl-support deduction) (let* ((content (kb-hl-support-content kb-hl-support)) (old-dependents (kb-hl-support-content-get-dependents content)) (new-dependents (set-contents-add deduction old-dependents))) (kb-hl-support-content-set-dependents content new-dependents) (mark-kb-hl-support-content-as-muted (kb-hl-support-id kb-hl-support)))) (defun kb-hl-support-remove-dependent (kb-hl-support deduction) (let* ((content (kb-hl-support-content kb-hl-support)) (old-dependents (kb-hl-support-content-get-dependents content)) (new-dependents (set-contents-delete deduction old-dependents))) (kb-hl-support-content-set-dependents content new-dependents) (mark-kb-hl-support-content-as-muted (kb-hl-support-id kb-hl-support)))) (defun remove-kb-hl-support (kb-hl-support) (let* ((content (kb-hl-support-content kb-hl-support)) (argument (kb-hl-support-content-get-argument content))) (when (valid-deduction? argument) (remove-deduction argument)) (free-kb-hl-support kb-hl-support) (free-kb-hl-support-content content))) (defun* hl-justify-for-kb-hl-support (hl-support) (:inline t) (remove hl-support (hl-support-justify hl-support) :test #'equal)) (defun valid-kb-hl-support? (object &optional robust?) (and (valid-kb-hl-support-handle? object) (or (not robust?) (missing-larkc 11080)))) (defun valid-kb-hl-support-handle? (object) (and (kb-hl-support-p object) (kb-hl-support-handle-valid? object))) (defun* kb-hl-support-handle-valid? (kb-hl-support) (:inline t) ;; TODO - assuming the not-integerp is just integer or nil (kb-hl-support-get-id kb-hl-support)) (defun tms-remove-kb-hl-supports-mentioning-term (term) (let ((removed-count 0)) (dolist (kb-hl-support (find-kb-hl-supports-mentioning-term term)) (when (valid-support? kb-hl-support) (tms-remove-kb-hl-support kb-hl-support)) (incf removed-count)) removed-count)) (defun setup-kb-hl-support-tables (size exact?) (setup-kb-hl-support-id-tables size exact?) (setup-kb-hl-support-index-table)) (defun finalize-kb-hl-supports (&optional max-kb-hl-support-id) (set-next-kb-hl-support-id max-kb-hl-support-id) (unless max-kb-hl-support-id (missing-larkc 11056))) (defglobal *kb-hl-supports-from-ids* nil) (defun* do-kb-hl-supports-table () (:inline t) *kb-hl-supports-from-ids*) (defun setup-kb-hl-support-id-tables (size exact?) (unless *kb-hl-supports-from-ids* (setf *kb-hl-supports-from-ids* (new-id-index size 0))) (setup-kb-hl-support-content-table size exact?)) (defun* lookup-kb-hl-support-by-id (id) (:inline t) (id-index-lookup *kb-hl-supports-from-ids* id)) (defun* next-kb-hl-support-id () (:inline t) (id-index-next-id *kb-hl-supports-from-ids*)) (defun* register-kb-hl-support-id (id kb-hl-support) (:inline t) (id-index-enter *kb-hl-supports-from-ids* id kb-hl-support)) (defun* deregister-kb-hl-support-id (id) (:inline t) (id-index-remove *kb-hl-supports-from-ids* id)) (defun set-next-kb-hl-support-id (&optional max-kb-hl-support-id) (let ((max -1)) (if max-kb-hl-support-id (setf max max-kb-hl-support-id) (do-id-index (id kb-hl-support (do-kb-hl-supports-table) :progress-message "Determining maximum KB HL support") (setf max (max max (kb-hl-support-id kb-hl-support))))) (let ((next-id (1+ max))) (set-id-index-next-id *kb-hl-supports-from-ids* next-id) next-id))) (defun increment-next-kb-hl-support-id () (let ((id (next-kb-hl-support-id))) (set-id-index-next-id *kb-hl-supports-from-ids* (1+ id)))) (defun clear-kb-hl-support-id-tables () (clear-id-index *kb-hl-supports-from-ids*) (clear-kb-hl-support-content-table)) (defglobal *kb-hl-support-index* nil) (deflexical *kb-hl-support-index-lock* (bt:make-lock "KB HL support indexing lock")) (deflexical *kb-hl-support-idnex-unindexed-terms* (list #$isa #$DefaultSemanticsForStringFn #$evaluate #$genlInverse #$genlPreds #$genls #$ist #$ist-Asserted #$SubLStringConcatenationFn #$TheList #$TheSet)) (defun* kb-hl-support-index-unindexed-term? (term) (:inline t) (member term *kb-hl-support-index-unindexed-terms* :test #'equal)) (defun kb-hl-support-index-indexed-term-p (term) (and (indexed-term-p term) (not (kb-hl-support-unindexed-term? term)))) (defun kb-hl-support-index-indexed-terms (sentence) (let ((terms (expression-gather sentence #'indexed-term-p nil #'equal))) ;; TODO - weird logic between these 2 list searches; is it right? (if (find-if-not #'kb-hl-support-index-unindexed-term? terms) (remove-if #'kb-hl-support-index-unindexed-term? terms) terms))) (defun setup-kb-hl-support-index-table () (unless *kb-hl-support-index* (setf *kb-hl-support-index* (make-hash-table :test #'eq)) t)) (defun lookup-kb-hl-support (hl-support) (let ((support-sets nil)) (destructuring-bind (module sentence mt tv) hl-support (bt:with-lock-held (*kb-hl-support-index-lock*) (when-let* ((mt-index (gethash module *kb-hl-support-index*)) (tv-index (gethash mt mt-index)) (term-index (gethash tv tv-index))) (let ((indexed-terms (kb-hl-support-index-indexed-terms sentence)) (done? nil)) (csome (term indexed-terms done?) (let ((support-set (gethash term term-index))) (cond ((set-contents-empty? support-set) (setf support-sets nil) (setf done? t)) ((set-contents-singleton? support-set) (setf support-sets (list support-set)) (setf done? t)) (t (push support-set support-sets))))))) (when support-sets (let ((candidate-kb-hl-supports (if (singleton? support-sets) (car support-sets) (set-intersection support-sets #'eq))) (kb-hl-support nil)) (do-set (candidate-kb-hl-support candidate-kb-hl-supports kb-hl-support) (let ((candidate-sentence (kb-hl-support-sentence candidate-kb-hl-support))) (when (equal candidate-sentence sentence) (setf kb-hl-support candidate-kb-hl-support)))) kb-hl-support)))))) (defun lookup-kb-hl-supports-mentioning-term (term) (let ((sentence-kb-hl-supports (lookup-kb-hl-supports-mentioning-term-in-sentence term)) (mt-kb-hl-supports (lookup-kb-hl-supports-mentioning-term-in-mt term))) ;; TODO - using set-contents APIs which should transition to just set-* (set-contents-element-list (set-union (list sentence-kb-hl-supports mt-kb-hl-supports) #'eq)))) (defun lookup-hl-supports-mentioning-term-in-sentence (term) (if (kb-hl-support-index-indexed-term-p term) (lookup-kb-hl-supports-mentioning-indexed-term-in-sentence term) (missing-larkc 11055))) (defun lookup-kb-hl-supports-mentioning-indexed-term-in-sentence (term) (let ((support-sets nil)) (bt:with-lock-held (*kb-hl-support-index-lock*) (dohash (key mt-index *kb-hl-support-index*) (dohash (key tv-index mt-index) (dohash (key term-index tv-index) (when-let ((support-set (gethash term term-index))) (unless (hash-table-empty-p support-set) (push support-set support-sets))))))) (set-union support-sets #'eq))) (defun lookup-kb-hl-supports-mentioning-term-in-mt (term) (let ((support-sets nil)) (bt:with-lock-held (*kb-hl-support-index-lock*) (dohash (key mt-index *kb-hl-support-index*) (dohash (mt tv-index mt-index) (when (simple-tree-find-via-equal? term mt) (dohash (key term-index tv-index) (dohash (key support-set term-index) (push support-set support-sets))))))) (set-union support-sets #'eq))) (defun index-kb-hl-support (kb-hl-support hl-support) (destructuring-bind (module sentence mt tv) hl-support (bt:with-lock-held (*kb-hl-support-index-lock*) ;; TODO - original did dictionary-p in the UNLESS forms, I'm assuming it's dictionary-p or nil which will be faster (let ((mt-index (gethash module *kb-hl-support-index*))) (unless mt-index (setf mt-index (make-hash-table :test #'equal)) (setf (gethash module *kb-hl-support-index*) mt-index)) (let ((tv-index (gethash mt mt-index))) (unless tv-index (setf tv-index (make-hash-table :test #'eq)) (setf (gethash mt mt-index) tv-index)) (let ((term-index (gethash tv tv-index))) (unless term-index (setf term-index (make-hash-table :test #'equal)) (setf (gethash tv tv-index) term-index)) (let ((indexed-terms (kb-hl-support-index-indexed-terms sentence))) (dolist (term indexed-terms) ;; TODO - this probably can be optimized because the hashtable is edited in place and doesn't need to be setf'd back like alists do. (let* ((old-supports (gethash term term-index)) (new-supports (set-add kb-hl-support old-supports))) (setf (gethash term term-index) new-supports)))))))))) (defun unindex-kb-hl-support (kb-hl-support &optional robust?) (if robust? (missing-larkc 11077) (let ((hl-support (kb-hl-support-hl-support kb-hl-support))) (if (hl-support-p hl-support) (unindex-kb-hl-support-with-hl-support kb-hl-support hl-support) (missing-larkc 11078))))) (defun unindex-kb-hl-support-with-hl-support (kb-hl-support hl-support) (destructuring-bind (module sentence mt tv) hl-support (bt:with-lock-held (*kb-hl-support-index-lock*) ;; TODO - assuming the java dictionary-p is testing for non-nil (when-let* ((mt-index (gethash module *kb-hl-support-index*)) (tv-index (gethash mt mt-index)) (term-index (gethash tv tv-index)) (indexed-terms (kb-hl-support-index-indexed-terms sentence))) (dolist (term indexed-terms) (let ((supports (gethash term term-index))) (set-remove kb-hl-support supports) ;; TODO - the ordering of this cleanup seems to be necessarily trickle-up, while the original did the testing unconditionally. (when (set-empty? supports) (remhash term term-index) (when (hash-table-empty-p term-index) (remhash tv tv-index) (when (hash-table-empty-p tv-index) (remhash mt mt-index) (when (hash-table-empty-p mt-index) (remhash module *kb-hl-support-index*))))))))))) (defun* clear-kb-hl-support-index () (:inline t) (clrhash *kb-hl-support-index*)) (defglobal *kb-hl-supports-being-created* nil) (defun note-kb-hl-support-creation-started (hl-support kb-hl-support) (unless *kb-hl-supports-being-created* (setf *kb-hl-supports-being-created* (make-hash-table :test #'equal))) (setf (gethash hl-support *kb-hl-supports-being-created*) kb-hl-support)) (defun note-kb-hl-support-creation-complete (hl-support) (when *kb-hl-supports-being-created* (remhash hl-support *kb-hl-supports-being-created*))) (defun find-kb-hl-support-during-creation (hl-support) (when *kb-hl-supports-being-created* (gethash hl-support *kb-hl-supports-being-created*))) (defun create-kb-hl-support (hl-support justification) (let* ((id (next-kb-hl-support-id)) (kb-hl-support (new-kb-hl-support id)) (kb-hl-support-content (new-kb-hl-support-content))) (note-kb-hl-support-creation-started hl-support kb-hl-support) (increment-next-kb-hl-support-id) (register-kb-hl-support-id id kb-hl-support) (register-kb-hl-support-content id kb-hl-support-content) (let* ((canon-just (canonicalize-supports justification t)) (deduction (create-deduction-for-hl-support hl-support canon-just))) (kb-hl-support-content-set-argument kb-hl-support-content deduction)) (index-kb-hl-support kb-hl-support hl-support) (note-kb-hl-support-creation-complete hl-support) kb-hl-support)) (defun destroy-kb-hl-support (kb-hl-support) (unindex-kb-hl-support kb-hl-support) (let ((id (kb-hl-support-id kb-hl-support))) (remove-kb-hl-support kb-hl-support) (deregister-kb-hl-support-id id) (deregister-kb-hl-support-content id))) (defun free-all-kb-hl-support () (clear-kb-hl-support-index) (do-id-index (id kb-hl-support (do-kb-hl-supports-table) :progress-message "Freeing KB HL supports") (let ((content (kb-hl-support-content kb-hl-support))) (free-kb-hl-support kb-hl-support) (free-kb-hl-support-content content))) (clear-kb-hl-support-id-tables)) (defparameter *unreify-kb-hl-supports?* nil) (defun possibly-unreify-kb-hl-supports (justification) (if *unreify-kb-hl-supports?* (missing-larkc 11079) justification)) (defparameter *tms-kb-hl-support-queue* nil) (defun* enqueue-kb-hl-supports-for-tms? () (:inline t) ;; TODO - assuming it's nil or queue-p *tms-kb-hl-support-queue*) (defun process-tms-kb-hl-support-queue () (until (queue-empty-p *tms-kb-hl-support-queue*) (let ((kb-hl-support (dequeue *tms-kb-hl-support-queue*))) (when (kb-hl-support-id kb-hl-support) (missing-larkc 11060))))) (defun tms-remove-kb-hl-support (kb-hl-support) (do-set (deduction (do-kb-hl-support-dependents-helper kb-hl-support)) (missing-larkc 12446) ;; can't declare ignore as this &body isn't at the top of the scope. Could add another field to do-set for declarations, though. deduction) (destroy-kb-hl-support kb-hl-support)) (defun create-sample-invalid-kb-hl-support () "[Cyc] Create a sample invalid KB HL support." (make-kb-hl-support)) (defparameter *kb-hl-support-dump-id-table* nil) (defun* find-kb-hl-support-by-dump-id (dump-id) (:inline t) (find-kb-hl-support-by-id dump-id)) (defun load-kb-hl-support-content (kb-hl-support stream) (let* ((id (kb-hl-support-id kb-hl-support)) (argument (cfasl-input stream nil)) (dependents (cfasl-input stream nil)) ;; TODO - no path to directly pass in slot values on construction through this (content (new-kb-hl-support-content))) (kb-hl-support-content-set-argument content argument) (kb-hl-support-content-set-dependents content dependents) (register-kb-hl-support-content id content) id)) (defun load-kb-hl-support-indexing-int (filename) (setf *kb-hl-support-index* (cfasl-load filename)))
19,974
Common Lisp
.lisp
386
43.974093
148
0.657723
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
f45423119f2c88ed94a93742c22e806d84ad0be6b229d373bc0385998acc230d
6,782
[ -1 ]
6,783
tcp.lisp
white-flame_clyc/larkc-cycl/tcp.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; Originally larkc-3.0/src/main/java/com/cyc/tool/subl/jrtl/nativeCode/subLisp/Tcp.java (defvar *retain-client-socket?* nil) (defvar *tcp-localhost-only? nil) (defvar *remote-hostname* nil) (defvar *remote-address* nil) (defvar *port-to-server-socket-process-map* (make-hash-table :synchronized t) "Maps numeric port to usocket listener socket") (defun open-tcp-stream (host port) ;; java.net.ServerSocket deals with bytes (usocket:socket-connect host port :element-type '(unsigned-byte 8))) (defun start-tcp-server (port handler) ;; TODO - test what the handler protocol is. usocket passes a stream object to it. The java interface seems to pass the stream into it twice, maybe a reader & writer stream separately? ;; TODO - Error capture & reporting? The Java SafeRunnable seems to just enable Lisp conditions to catch exceptions, and print errors to stdout if not caught. ;; socket-server returns the thread & the socket, when multithreading is enabled (let ((socket (nth-value 1 (usocket:socket-server nil port handler nil :multi-threading t :name (format nil "Socket Server (port: ~a handler: ~a" port handler))))) (setf (gethash port *port-to-server-socket-process-map*) socket))) (defun stop-tcp-server (port) (or (sb-ext:with-locked-hash-table (*port-to-server-socket-process-map*) (gethash-and-remove port *port-to-server-socket-process-map*)) (error "~s is not a TCP server port designator." port)))
2,981
Common Lisp
.lisp
51
52.784314
188
0.731405
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
6980c345bfc1aa39e16a6368661700a0d0251fd8c805d5ae951c8a4ffb723a9a
6,783
[ -1 ]
6,784
cfasl.lisp
white-flame_clyc/larkc-cycl/cfasl.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defmacro declare-cfasl-opcode (name val func) ;; These two seem to happen for each opcode `(progn (defconstant ,name ,val) (register-cfasl-input-function ,name ,func))) (defstruct cfasl-encoding-stream internal-stream) (defun cfasl-output-maybe-externalized (object stream externalized?) (if externalized? (cfasl-output-externalized object stream) (cfasl-output object stream))) (defparameter *terse-guid-serialization-enabled?* nil "[Cyc] Temporary control variable, should eventually stay T.") (defparameter *terse-guid-serialization-enabled-for-cfasl-encode-externalized?* :uninitialized "[Cyc] Temporary control variable, the only controls whether cfasl-encode-externalized-terse uses terse GUID serialization") (defstruct cfasl-decoding-stream internal-stream) (defstruct cfasl-count-stream position) (defparameter *cfasl-stream-extensions-enabled* nil) (defparameter *cfasl-unread-byte* nil) (defun cfasl-output (object stream) "[Cyc] Output OBJECT to STREAM in the CFASL protocol. The encoding is relevant to this image only." (when (cfasl-compress-object? object) (missing-larkc 12988)) (cfasl-output-object object stream)) (defun cfasl-output-externalized (object stream) "[Cyc] Output OBJECT to STREAM in the CFASL protocol. The encoding is relevant to any image, not just this one." (cfasl-output-externalization object stream)) ;; TODO - part of the method dispatch stuff? (deflexical *cfasl-output-object-method-table* (make-array '(256))) (defpolymorphic cfasl-output-object (object stream) ;; TODO - is this correct? does Errors.handleMissingMethodError fill in for any expression but blows up? (missing-larkc 31000)) (defun cfasl-raw-write-byte (byte stream) (cond ((cfasl-count-stream-p stream) (missing-larkc 30957)) ((cfasl-encoding-stream-p stream) (missing-larkc 30966)) (t (write-byte byte stream)))) (defparameter *cfasl-input-to-static-area* nil "[Cyc] If non-NIL, then structure created during CFASL input is allocated in the static area.") (defun cfasl-input (stream &optional (eof-error-p t) (eof-value :eof)) "[Cyc] Input an object from STREAM in the CFASL protocol. EOF-ERROR-P indicates whether an end-of-file is considered an error. EOF-VALUE indicates a value to return when end-of-file is encountered and EOF-ERROR-P is NIL." (cfasl-input-internal stream eof-error-p eof-value)) (defun cfasl-opcode-peek (stream &optional (eof-error-p t) (eof-value :eof)) "[Cyc] Peek at STREAM to return the opcode for the next object to be read in CFASL protocol. EOF-ERROR-P indicates whether an end-of-file is considered an error. EOF-VALUE indicates a value to return when end-of-file is encountered and EOF-ERROR-P is NIL." (cfasl-opcode-peek-internal stream eof-error-p eof-value)) (defun cfasl-input-object (stream) (cfasl-input-internal stream nil nil)) (defun cfasl-input-internal (stream eof-error-p eof-value) (let ((opcode (cfasl-raw-read-byte stream))) (cond ((null opcode) (if eof-error-p (error "end-of-file on stream ~s" stream) eof-value)) ((cfasl-immediate-fixnum-opcode opcode) (cfasl-extract-immediate-fixnum opcode)) (t (let ((cfasl-input-method (cfasl-input-method opcode))) (if (eq 'cfasl-input-error cfasl-input-method) (error "Undefined cfasl opcode ~s in ~s" opcode stream) (funcall cfasl-input-method stream))))))) (defun cfasl-opcode-peek-internal (stream eof-error-p eof-value) (let ((opcode (cfasl-raw-peek-byte stream))) (cond ((null opcode) (if eof-error-p (error "end-of-file on stream ~s" stream) eof-value)) (t opcode)))) (defconstant *cfasl-max-opcode* 128) (defglobal *cfasl-input-method-table* (make-array (list *cfasl-max-opcode*) :initial-element 'cfasl-input-error) "[Cyc] Dispach table used by CFASL-INPUT.") (defun cfasl-input-method (cfasl-opcode) (aref *cfasl-input-method-table* cfasl-opcode)) (defun register-cfasl-input-function (cfasl-opcode function) (setf (aref *cfasl-input-method-table* cfasl-opcode) function)) (defun cfasl-raw-peek-byte (stream) ;; Rewritten since CL doesn't have unread-byte ;; Pulled error detection from cfasl-raw-read-byte (when (cfasl-decoding-stream-p stream) (missing-larkc 30961)) (flexi-streams:peek-byte stream)) (defun cfasl-raw-read-byte (stream) (when (cfasl-decoding-stream-p stream) (missing-larkc 30961)) (read-byte stream)) (defparameter *within-cfasl-externalization* nil) (defun within-cfasl-externalization-p () "[Cyc] Return T iff we are assuming CFASL externalization." *within-cfasl-externalization*) (defparameter *cfasl-channel-externalized?* t) (defglobal *cfasl-extensions* nil) (declare-cfasl-opcode *cfasl-opcode-externalization* 51 'cfasl-input-externalization) (defun cfasl-output-externalization (object stream) (cfasl-raw-write-byte *cfasl-opcode-externalization* stream) (let ((*within-cfasl-externalization* t)) (cfasl-output object stream))) (defun cfasl-input-externalization (stream) (let ((*within-cfasl-externalization* t)) (cfasl-input-object stream))) (defparameter *current-cfasl-defstruct-output-stream* nil "[Cyc] The current stream to which the CFASL-DEFSTRUCT-RECIPE-OUTPUT-METHOD is writing.") (declare-cfasl-opcode *cfasl-opcode-defstruct-recipe* 44 'cfasl-input-defstruct-recipe) (defun cfasl-output-defstruct-recipe (object stream) "[Cyc] This method expects to be called by CFASL-OUTPUT in the case where no implementation is available for a STRUCTURE-P." (declare (ignorable object stream)) ;; TODO - missing means executing is aborted? this seems pretty important to have working (missing-larkc 30992)) (defun cfasl-output-defstruct-recipe-visitorfn (obj phase param-a param-b) (let ((stream *current-cfasl-defstruct-output-stream*)) (case phase (:begin (cfasl-output param-a stream) ;; constructor-fn (cfasl-output param-b stream) ;; num-of-slots ) (:slot (cfasl-output param-a stream) ;; slot-name (cfasl-output param-b stream) ;; slot-value ) (:end)) obj)) (defun cfasl-input-defstruct-recipe (stream) "[Cyc] this method is dispatched to by the CFASL-INPUT infrastructure after the *CFASL-OPCODE-DEFSTRUCT-RECIPE* has been read." (let ((constructor-fn (cfasl-input stream)) (num-of-slots (cfasl-input stream)) (plist nil) (cursor nil)) (must (function-spec-p constructor-fn) "Error: Expected constructor for defstruct, got ~a" constructor-fn) (setf plist (make-list (+ num-of-slots num-of-slots))) (setf cursor plist) (dotimes (i num-of-slots) (let ((slot-name (cfasl-input stream)) (slot-value (cfasl-input stream))) (must (keywordp slot-name) "Expected keyword at slot #~a of structure with constructor ~a, got ~a" i constructor-fn slot-name) (setf (nth 0 cursor) slot-name) (setf (nth 1 cursor) slot-value) (setq cursor (cddr cursor)))) (funcall constructor-fn plist))) (defconstant *cfasl-immediate-fixnum-cutoff* *cfasl-max-opcode*) (defconstant *cfasl-immediate-fixnum-offset* (- 256 *cfasl-immediate-fixnum-cutoff*)) (defun cfasl-immediate-fixnump (object) (and (typep object 'fixnum) (>= object 0) (< object *cfasl-immediate-fixnum-cutoff*))) (defun cfasl-output-immediate-fixnum (object stream) (cfasl-raw-write-byte (+ *cfasl-immediate-fixnum-offset* object) stream) object) (defun cfasl-immediate-fixnum-opcode (opcode) (>= opcode *cfasl-immediate-fixnum-offset*)) (defun cfasl-extract-immediate-fixnum (opcode) (- opcode *cfasl-immediate-fixnum-offset*)) (declare-cfasl-opcode *cfasl-opcode-p-8bit-int* 0 'cfasl-input-p-8bit-int) (declare-cfasl-opcode *cfasl-opcode-n-8bit-int* 1 'cfasl-input-n-8bit-int) (declare-cfasl-opcode *cfasl-opcode-p-16bit-int* 2 'cfasl-input-p-16bit-int) (declare-cfasl-opcode *cfasl-opcode-n-16bit-int* 3 'cfasl-input-n-16bit-int) (declare-cfasl-opcode *cfasl-opcode-p-24bit-int* 4 'cfasl-input-p-24bit-int) (declare-cfasl-opcode *cfasl-opcode-n-24bit-int* 5 'cfasl-input-n-24bit-int) (declare-cfasl-opcode *cfasl-opcode-p-32bit-int* 6 'cfasl-input-p-32bit-int) (declare-cfasl-opcode *cfasl-opcode-n-32bit-int* 7 'cfasl-input-n-32bit-int) (declare-cfasl-opcode *cfasl-opcode-p-bignum-int* 23 'cfasl-input-p-bignum) (declare-cfasl-opcode *cfasl-opcode-n-bignum-int* 24 'cfasl-input-n-bignum) (defun cfasl-output-object-integer-method (object stream) (cfasl-output-integer object stream)) (defun cfasl-output-integer (integer stream) (if (cfasl-immediate-fixnump integer) (cfasl-output-immediate-fixnum integer stream) (let ((positive (plusp integer)) (value (abs integer))) (if (< value 2147483648) (multiple-value-bind (num-bytes pos-opcode neg-opcode) (cond ((< value 128) (values 1 *cfasl-opcode-p-8bit-int* *cfasl-opcode-n-8bit-int*)) ((< value 32768) (values 2 *cfasl-opcode-p-16bit-int* *cfasl-opcode-n-16bit-int*)) ((< value 8388608) (values 3 *cfasl-opcode-p-24bit-int* *cfasl-opcode-n-24bit-int*)) (t (values 4 *cfasl-opcode-p-32bit-int* *cfasl-opcode-n-32bit-int*))) (cfasl-raw-write-byte (if positive pos-opcode neg-opcode) stream) (cfasl-output-integer-internal value num-bytes stream)) ;; Bignum handling (let ((bignum-spec (disassemble-integer-to-fixnums integer))) (destructuring-bind (sign . fixnums) bignum-spec (cfasl-raw-write-byte (if (minusp sign) *cfasl-opcode-n-bignum-int* *cfasl-opcode-p-bignum-int*) stream) (cfasl-output (length fixnums) stream) (dolist (fixnum fixnums) (cfasl-output fixnum stream))))))) integer) (defun cfasl-output-integer-internal (integer bytes stream) ;; bytes = count of bytes (if (= 1 bytes) (cfasl-raw-write-byte integer stream) (let ((low-part (logand integer 255)) (high-part (ash integer -8))) (cfasl-raw-write-byte low-part stream) (cfasl-output-integer-internal high-part (1- bytes) stream))) integer) (defun cfasl-input-n-8bit-int (stream) (- (cfasl-input-integer 1 stream))) (defun cfasl-input-p-8bit-int (stream) (cfasl-input-integer 1 stream)) (defun cfasl-input-n-16bit-int (stream) (- (cfasl-input-integer 2 stream))) (defun cfasl-input-p-16bit-int (stream) (cfasl-input-integer 2 stream)) (defun cfasl-input-n-24bit-int (stream) (- (cfasl-input-integer 3 stream))) (defun cfasl-input-p-24bit-int (stream) (cfasl-input-integer 3 stream)) (defun cfasl-input-n-32bit-int (stream) (- (cfasl-input-integer 4 stream))) (defun cfasl-input-p-32bit-int (stream) (cfasl-input-integer 4 stream)) (defun assemble-2-fixnums-to-non-negative-integer (fixnum0 fixnum1) (logior fixnum0 (ash fixnum1 8))) (defun assemble-3-fixnums-to-non-negative-integer (fixnum0 fixnum1 fixnum2) (logior fixnum0 (ash fixnum1 8) (ash fixnum2 16))) (defun assemble-4-fixnums-to-non-negative-integer (fixnum0 fixnum1 fixnum2 fixnum3) (logior fixnum0 (ash fixnum1 8) (ash fixnum2 16) (ash fixnum3 24))) (defun cfasl-input-integer (bytes stream) ;; bytes seems to be a byte count again (cond ((not (cfasl-decoding-stream-p stream)) (read-byte-sequence-to-positive-integer bytes stream)) ;; TODO BUG - this breaks past 8 bytes! ((> bytes 4) (let ((high-recursive (cfasl-input-integer (- bytes 4) stream)) (low-4 (cfasl-input-integer 4 stream))) (logior (ash high-recursive 32) low-4))) (t (case bytes (4 (assemble-4-fixnums-to-non-negative-integer (cfasl-raw-read-byte stream) (cfasl-raw-read-byte stream) (cfasl-raw-read-byte stream) (cfasl-raw-read-byte stream))) (3 (assemble-3-fixnums-to-non-negative-integer (cfasl-raw-read-byte stream) (cfasl-raw-read-byte stream) (cfasl-raw-read-byte stream))) (2 (assemble-2-fixnums-to-non-negative-integer (cfasl-raw-read-byte stream) (cfasl-raw-read-byte stream))) (1 (cfasl-raw-read-byte stream)) (0 0))))) ;;(declare-cfasl-opcode *cfasl-opcode-p-float* 8 'cfasl-input-p-float) ;;(declare-cfasl-opcode *cfasl-opcode-n-float* 9 'cfasl-input-n-float) (defmethod cfasl-output-object ((object float) stream) ;; TODO - shouldn't be hard to implement (missing-larkc 30985)) (defmethod cfasl-output-object ((object symbol) stream) (cond ((null object) (cfasl-output-nil stream)) ((cfasl-common-symbol-p object) (missing-larkc 30983)) ((keywordp object) (missing-larkc 30988)) (t (cfasl-output-other-symbol object stream)))) (declare-cfasl-opcode *cfasl-opcode-keyword* 10 'cfasl-input-keyword) (defun cfasl-input-keyword (stream) (let ((name (cfasl-input-object stream))) (when (char= #\: (char name 0)) (setf name (subseq name 1))) (make-keyword name))) (declare-cfasl-opcode *cfasl-opcode-other-symbol* 11 'cfasl-input-other-symbol) (defun cfasl-output-other-symbol (object stream) (cfasl-raw-write-byte *cfasl-opcode-other-symbol* stream) (unless (cyc-package-symbol-p object) (cfasl-output (symbol-package object) stream)) (cfasl-output-string (symbol-name object) stream) object) (defun cyc-package-symbol-p (object) "[Cyc] Return T iff OBJECT is a symbol in the Cyc package" (and (symbolp object) (not (keywordp object)) (or (eq *cyc-package* (symbol-package object)) (eq object (find-symbol (symbol-name object) *cyc-package*))))) (defun cfasl-input-other-symbol (stream) (let ((input (cfasl-input-object stream))) (if (stringp input) (intern input *cyc-package*) (let ((package input) (name (cfasl-input-object stream))) (if package (intern name package) (make-symbol name)))))) (declare-cfasl-opcode *cfasl-opcode-nil* 12 'cfasl-input-nil) (defun cfasl-output-nil (stream) (cfasl-raw-write-byte *cfasl-opcode-nil* stream) nil) (defun cfasl-input-nil (stream) (declare (ignore stream)) nil) (defparameter *cfasl-common-symbols* nil "[Cyc] A list of commonly used symbols for which it is cost-effective to output in a terser representation.") (defun cfasl-set-common-symbols (symbols) "[Cyc] Set the currently used list of common symbols for CFASL to be SYMBOLS." (setf *cfasl-common-symbols* (apply #'vector symbols))) (defun cfasl-set-common-symbols-simple (symbols) "[Cyc] Set the currently used list of common symbols for CFASL to be SYMBOLS, assuming that we're only doing a few cfasl functions and so will sacrifice time for space and not make a vector" (setf *cfasl-common-symbols* symbols)) (defun cfasl-current-common-symbols () "[Cyc] Get the currently active common symbols in a form that can be used in conjunction with CFASL-SET-COMMON-SYMBOLS." (let ((syms *cfasl-common-symbols*)) (if (vectorp syms) (coerce syms 'list) syms))) (defun cfasl-common-symbol-p (object) (and *cfasl-common-symbols* (symbolp object) (position object *cfasl-common-symbols* :test #'eq))) (defun cfasl-decode-common-symbol (integer) (let ((syms *cfasl-common-symbols*)) (if (vectorp syms) (aref syms integer) (nth integer syms)))) (defun cfasl-input-common-symbol (stream) (let* ((encoding (cfasl-input-object stream)) (symbol (cfasl-decode-common-symbol encoding))) (unless symbol (cerror "Use NIL." "Common symbol at index ~d was not found in ~s." '*cfasl-common-symbols*)) symbol)) (defmethod cfasl-output-object ((object cons) stream) (if (proper-list-p object) (cfasl-output-list object stream) (cfasl-output-dotted-list object stream))) (defglobal *cfasl-list-methods* nil) (declare-cfasl-opcode *cfasl-opcode-list* 13 'cfasl-input-list) (defun cfasl-output-list (list stream) (let ((length (list-length list))) (cond ((null length) (cerror "Output NIL instead" "Trying to output a circular list.") (cfasl-output-nil stream)) ((zerop length) (cfasl-output-nil stream)) ;; TODO - huh? ;;((and *cfasl-list-methods* (missing-larkc 31001)) (t (cfasl-raw-write-byte *cfasl-opcode-list* stream) (cfasl-output-integer length stream) (dolist (item list) (cfasl-output item stream)) ;; TODO - do these output functions really need to always return the object? list)))) (defun cfasl-input-list (stream) (let* ((length (cfasl-input-object stream)) (list (make-list length))) (loop for cell on list do (rplaca cell (cfasl-input-object stream))) list)) (declare-cfasl-opcode *cfasl-opcode-dotted-list* 17 'cfasl-input-dotted-list) (defun cfasl-output-dotted-list (object stream) (let ((length (dotted-length object))) (cfasl-raw-write-byte *cfasl-opcode-dotted-list* stream) (cfasl-output-integer length stream) (let ((cons (cons nil object))) (dotimes (i length) (pop cons) (cfasl-output (first cons) stream)) ;; TODO - original has a bug that wanted to put out the cons cell itself? wouldn't that be infinitely looping? (cfasl-output (cdr cons) stream)))) ;; TODO - input and output don't match in the original source for dotted lists. Assuming all elements + final cdr are written linearly (defun cfasl-input-dotted-list (stream) (let ((length (cfasl-input-object stream))) (if (= 1 length) (cons (cfasl-input-object stream) (cfasl-input-object stream)) (let ((list (make-list length))) (loop for cell on list do (rplaca cell (cfasl-input-object stream)) do (when (null (cdr cell)) (rplacd cell (cfasl-input-object stream)) (return))) list)))) (defmethod cfasl-output-object ((object vector) stream) ;; TODO - should be easy (missing-larkc 4931)) ;; TODO - vector types ;;(declare-cfasl-opcode *cfasl-opcode-general-vector* 14) ;;(declare-cfasl-opcode *cfasl-opcode-byte-vector* 26) (declare-cfasl-opcode *cfasl-opcode-string* 15 'cfasl-input-string) (defmethod cfasl-output-object ((object string) stream) (cfasl-output-string object stream)) (defun cfasl-output-string (string stream) (cfasl-raw-write-byte *cfasl-opcode-string* stream) (map nil (lambda (char) (cfasl-raw-write-byte (char-code char) stream)) string)) (defparameter *cfasl-input-string-resource* nil "[Cyc] If non-NIL, a string that is destructively re-used when loading a string of the same length.") (defun cfasl-input-string (stream) (let* ((length (cfasl-input-object stream)) (string (let ((old *cfasl-input-string-resource*)) (if (and (stringp old) (= length (length old))) old (make-string length))))) (if (not (cfasl-decoding-stream-p stream)) (read-sequence string stream) (dotimes (i length) (setf (char string i) (code-char (cfasl-raw-read-byte stream))))) string)) ;; TODO ;;(declare-cfasl-opcode *cfasl-opcode-character* 16 'cfasl-input-character) (defmethod cfasl-output-object ((object character) stream) ;; TODO (missing-larkc 30982)) (declare-cfasl-opcode *cfasl-opcode-hashtable* 18 'cfasl-input-hashtable) (defun cfasl-input-hashtable (stream) (let* ((test (cfasl-input-object stream)) (size (cfasl-input-object stream)) (hashtable (make-hash-table :size size :test test))) (dotimes (i size) (let ((key (cfasl-input-object stream)) (value (cfasl-input-object stream))) (setf (gethash key hashtable) value))) hashtable)) (defconstant *cfasl-opcode-guid* 43) ;; TODO - the class GUID is not defined yet, it's a native type in Java SubL ;; (defmethod cfasl-output-object ((object guid) stream) ;; (cfasl-output-guid object stream)) (defun cfasl-output-guid (guid stream) (if (not *terse-guid-serialization-enabled?*) (cfasl-output-legacy-guid guid stream) (let ((byte-vector (disassemble-guid-to-fixnums guid))) (cfasl-raw-write-byte *cfasl-opcode-guid* stream) (dotimes (i 16) (cfasl-raw-write-byte (aref byte-vector i) stream)) guid))) ;; TODO - cfasl-input-guid is missing? (defconstant *cfasl-opcode-legacy-guid* 25) (defun cfasl-output-legacy-guid (guid stream) (cfasl-raw-write-byte *cfasl-opcode-legacy-guid* stream) (cfasl-output-string (guid-to-string guid) stream) guid) (defun cfasl-input-legacy-guid (stream) (string-to-guid (cfasl-input-guid-string stream))) (defparameter *cfasl-input-guid-string-resource* nil) (defun cfasl-input-guid-string (stream) (let ((*cfasl-input-string-resource* *cfasl-input-string-resource*)) (cfasl-input stream))) (defun get-new-cfasl-input-guid-string-resource () "[Cyc] Allocates and provides access to a new GUID string resource object." (make-string 36)) (defmacro with-new-cfasl-input-guid-string-resource (&body body) "[Cyc] Allocates a new GUID string resource and makes it available to the GUID loading infrastructure." ;; Guesswork, hopefully correct? `(let ((*cfasl-input-guid-string-resource* (get-new-cfasl-input-guid-string-resource))) ,@body)) ;; TODO ;;(declare-cfasl-opcode *cfasl-opcode-result-set* 27 'cfasl-input-resul-set) ;;(declare-cfasl-opcode *cfasl-opcode-package* 28 'cfasl-input-package) (defmethod cfasl-output-object ((object package) stream) (declare (ignorable object stream)) ;; TODO (missing-larkc 30993)) ;; TODO ;;(declare-cfasl-opcode *cfasl-opcode-wide-cfasl-opcode* 29) (defconstant *cfasl-min-wide-opcode* *cfasl-max-opcode* "[Cyc] All wide opcodes have to be more than one byte, so that all narrow opcodes can be re-encoded as wide opcodes without loss of functionality.") (defglobal *cfasl-wide-opcode-input-method-table* (make-hash-table) "[Cyc] DIspatch table used by the wide CFASL-INPUT methods.") (defun register-wide-cfasl-opcode-input-function (wide-opcode function) (setf (gethash wide-opcode *cfasl-wide-opcode-input-method-table*) function)) ;; TODO ;; (declare-cfasl-opcode *cfasl-opcode-instance* 124) ;; (declare-cfasl-opcode *cfasl-opcode-guid-denoted-type* 126) (deflexical *cfasl-guid-denoted-type-input-method-table* (make-hash-table :test #'equalp) "[Cyc] Stores the GUIDs -> input type Mappings.") (defun register-cfasl-guid-denoted-type-input-function (cfasl-guid-opcode function) (setf (gethash cfasl-guid-opcode *cfasl-guid-denoted-type-input-method-table*) function))
24,650
Common Lisp
.lisp
484
44.743802
258
0.693098
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
e652284d63453ad2a0d67eb4acf8dc71143f7f0b26f629cb638d1341aea25ee1
6,784
[ -1 ]
6,785
utilities-macros.lisp
white-flame_clyc/larkc-cycl/utilities-macros.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun register-cyc-api-function (name arglist doc-string argument-types return-types) "[Cyc] Register NAME as a (public) Cyc API function. Note its ARGLIST, DOC-STRING, ARGUMENT-TYPES and RETURN-TYPES." (register-api-predefined-function name) (register-cyc-api-symbol name) (register-cyc-api-args name arglist) (register-cyc-api-function-documentation name doc-string) (register-cyc-api-arg-types name argument-types) (register-cyc-api-return-types name return-types)) (defun register-cyc-api-macro (name pattern doc-string) "[Cyc] Register NAME as a (public) Cyc API macro. Note its PATTERN and DOC-STRING." (register-api-predefined-macro name) (register-cyc-api-symbol name) (register-cyc-api-args name pattern) (register-cyc-api-function-documentation name doc-string)) (defglobal *api-special-table* (make-hash-table :test #'eq)) (defun api-special-p (operator) (gethash operator *api-special-table*)) (defun register-api-special (operator handler) (if (or (api-predefined-function-p operator) (api-predefined-macro-p operator)) (warn "Attempted to register ~a as special even though it's already predefined!" operator) (setf (gethash operator *api-special-table*) handler)) operator) (defglobal *api-predefined-function-table* (make-hash-table :test #'eq)) (defun api-predefined-function-p (operator) (if (api-predefined-host-function-p operator) *permit-api-host-access* (gethash operator *api-predefined-function-table*))) (defun register-api-predefined-function (operator) "[Cyc] Permit the use of the OPERATOR function in the CYC api" (unless (api-special-p operator) (setf (gethash operator *api-predefined-function-table*) t)) operator) (defglobal *api-predefined-host-function-table* (make-hash-table :test #'eq)) (defun api-predefined-host-function-p (operator) (unless (api-special-p operator) (setf (gethash operator *api-predefined-host-function-table*) t)) operator) (defglobal *api-predefined-macro-table* (make-hash-table :test #'eq)) (defun api-predefined-macro-p (operator) (if (api-predefined-host-macro-p operator) *permit-api-host-access* (gethash operator *api-predefined-macro-table*))) (defun register-api-predefined-macro (operator) "[Cyc] Permit the use of the OPERATOR macro in the CYC api" (unless (api-special-p operator) (setf (gethash operator *api-predefined-macro-table*) t)) operator) (defglobal *api-predefined-host-macro-table* (make-hash-table :test #'eq)) (defun api-predefined-host-macro-p (operator) (gethash operator *api-predefined-host-macro-table*)) (defun register-api-predefined-host-macro (operator) "[Cyc] Permit the use of the OPERATOR host-access macro in the CYC api" (unless (api-special-p operator) (setf (gethash operator *api-predefined-host-macro-table*) t)) operator) (defglobal *api-symbols* nil) (defun register-cyc-api-symbol (name) "[Cyc] Register the symbol NAME as a defined Cyc API function or macro. Return the NAME." (declare (symbol name)) (put name :cyc-api-symbol t) (pushnew name *api-symbols*) name) (defun register-cyc-api-args (name arglist) "[Cyc] For the symbol NAME, register the Cyc API ARGLIST since SMUCL does not record the macro argument list. Return the NAME." (declare (symbol name) (list arglist)) (put name :cyc-api-args arglist) name) (defun register-cyc-api-function-documentation (name documentation-string) "[Cyc] Register DOCUMENTATION-STRING as the function documentation for NAME." (declare (symbol name) (string documentation-string) (ignore name documentation-string))) (defun register-cyc-api-arg-types (name argument-type-list) "[Cyc] For the symbol NAME, register the Cyc API function argument types, whcih take the form of a list of argument type expressions. Return the NAME." (declare (symbol name) (list argument-type-list)) (put name :cyc-api-arg-types argument-type-list)) (defun register-cyc-api-return-types (name return-types) (declare (symbol name) (list return-types)) (dolist (return-type return-types) (validate-return-type return-type)) (put name :cyc-api-return-types return-types) name) (defglobal *api-types* nil) (defun validate-return-type (return-type) "[Cyc] Ensure that each symbol denoting a predicate in the RETURN-TYPE expression is recorded as an api type function. Return T if OK, otherwise signal an error." (if (atom return-type) (progn (pushnew return-type *api-types*) t) (progn (must (= 2 (length return-type)) "~s return type expression not list length 2." return-type) (if (member (first return-type) '(list nil-or)) (validate-return-type (second return-type)) (error "~s complex return type expression" return-type))))) (defglobal *kb-function-table* (make-hash-table :test #'eq)) (defun register-kb-symbol (symbol) "[Cyc] Note that SYMBOL is expected to be a symbol referenced by the KB." (declare (symbol symbol)) (setf (gethash symbol *kb-function-table*) t) symbol) (macro-helpers define-kb (defun register-kb-function (function-symbol) "[Cyc] Note that SYMBOL is expected to be a function symbol referenced by the KB." (register-kb-symbol function-symbol))) (defglobal *funcall-helper-property* :funcall-helper) (macro-helpers define-private-funcall (defun note-funcall-helper-function (symbol) "[Cyc] Note that SYMBOL has been defined via DEFINE-PRIVATE-FUNCALL" (put symbol *funcall-helper-property* t))) (defglobal *unprovided* '#:unprovided "[Cyc] A unique marker which can be used as a default optional argument to indicate that no argument was explicitly provided. The ONLY references to this variable should be as the default value for an argument in the formal arguments for a function.") (defun unprovided-argument-p (arg) "[Cyc] Return T iff ARG indicates that it was an unprovided argument to a function call.." (eq arg *unprovided*)) (defun declare-control-parameter-internal (variable fancy-name description settings-spec) (declare (symbol variable) (string fancy-name) (string description)) (put variable :fancy-name fancy-name) (put variable :description description) (put variable :settings-spec settings-spec) variable) (defun mapping-finished () (throw :mapping-done nil)) (defparameter *cfasl-stream* nil) (defglobal *global-locks* nil) (defun initialize-global-locks () "[Cyc] Initialize all global locks" (dolist (pair *global-locks*) (destructuring-bind (global name) pair (initialize-global-lock-internal global name)))) ;; TODO - SubL can have macros and functions with the same name? (macro-helpers register-global-lock (defun register-global-lock (global name) (declare (symbol global) (string name)) (setf *global-locks* (cons (cons global name) (delete global *global-locks* :key #'car))))) (defun global-lock-initialization-form (name) (declare (string name)) (list 'make-lock name)) (macro-helpers initialize-global-locks (defun initialize-global-lock-internal (global name) (eval (list 'setf global (global-lock-initialization-form name))) global)) (defglobal *fi-state-variables* nil) (macro-helpers def-state-variable (defun note-state-variable-documentation (variable documentation) (put variable :variable-doc documentation) variable)) (defglobal *gt-state-variables* nil) (defglobal *at-state-variables* nil) (defglobal *defn-state-variables* nil) (defglobal *kbp-state-variables* nil) (defparameter *current-forward-problem-store* nil "[Cyc] The current problem store in use for forward inference.") ;; Converted this from a function to a macro, since it contains distant forward code references (defmacro within-normal-forward-inference? () "[Cyc] A more strict version of (within-forward-inference?) that returns NIL when we're in a special forward inference mode." `(and (within-forward-inference?) (not *within-assertion-forward-propagation?*) (not *prefer-forward-skolemization*))) (defparameter *tracing-level* nil "[Cyc] An alist of things to trace and the level at which they should be traced. Current items are :CYCL, :PLANNER, and :EXECUTOR. A level of NIL or 0 means don't print out any tracing information. Higher numbers mean do more tracing.") (deflexical *structure-resourcing-enabled* nil "[Cyc] Controls whether or not a free list is maintained and used for a structure resource declared via DEFINE-STRUCTURE-RESOURCE.") (defparameter *structure-resourcing-make-static* nil "[Cyc] Controls whether or not any new structure is statically allocated for a structure resource declared via DEFINE-STRUCTURE-RESOURCE.") (defvar *silent-progress?* nil) (defparameter *noting-progress-start-time* nil) (defmacro noting-progress ((title) &body body) "Assumed from usage" `(let ((*noting-progress-start-time* (get-universal-time))) (noting-progress-preamble ,title) ,@body (noting-progress-postamble))) (macro-helpers noting-progress (defun noting-progress-preamble (string) (unless *silent-progress?* (format t "~%~a" string) (force-output))) (defun noting-progress-postamble () (unless *silent-progress?* (let ((elapsed (elapsed-universal-time *noting-progress-start-time*))) (format t "DONE (~a)~%" (elapsed-time-abbreviation-string elapsed)) (force-output))))) (defvar *last-percent-progress-index* nil) (defparameter *last-percent-progress-prediction* nil "[Cyc] Bound to the latest prediction we made about how long the process will take, or NIL if we haven't made such a prediction.") (defvar *within-noting-percent-progress* nil) (defvar *percent-progress-start-time* nil) (defmacro noting-percent-progress ((note) &body body) ;; from utilities_macros.java, list217 `(let ((*last-percent-progress-index* 0) (*last-percent-progress-prediction* nil) (*within-noting-percent-progress* t) (*percent-progress-start-time* (get-universal-time))) (noting-percent-progress-preamble ,note) ,@body (noting-percent-progress-postamble))) (macro-helpers noting-percent-progress (defun noting-percent-progress-preamble (string) (unless *silent-progress?* (format t "~&~a~% [" string) (force-output))) (defun noting-percent-progress-postamble () (unless *silent-progress?* (let ((elapsed (elapsed-universal-time *percent-progress-start-time*))) (format t " DONE (~a" (elapsed-time-abbreviation-string elapsed)) (when (> elapsed 600) (format t ", ended (missing-larkc 23127)")) (format t ") ]~%") (force-output)))) (defun note-percent-progress (index max) (when (and (not *silent-progress?*) *within-noting-percent-progress* index) (let ((percent (compute-percent-progress index max))) (when (> percent *last-percent-progress-index*) (let* ((elapsed (elapsed-universal-time *percent-progress-start-time*)) (predicted-total-seconds (truncate (* elapsed 100) percent))) (cond ((and (or (= 1 percent) (= 1 index)) (>= predicted-total-seconds (* 5 *seconds-in-a-minute*))) (write-char #\.) (possibly-note-percent-progress-prediction elapsed predicted-total-seconds 300 600)) ((and (or (= 2 percent) (= 2 index)) (>= predicted-total-seconds (* 10 *seconds-in-a-minute*))) (write-char #\.) (possibly-note-percent-progress-prediction elapsed predicted-total-seconds 300 600)) ((<= predicted-total-seconds 5) nil) ((= 0 (mod percent 10)) (print-progress-percent percent) (possibly-note-percent-progress-prediction elapsed predicted-total-seconds 600 1200)) ((< max 60) (write-char #\.)) ((<= predicted-total-seconds 20) nil) (t (progn (when (= 0 (mod percent 2)) (write-char #\.)) (when *last-percent-progress-prediction* (let ((threshold (+ *last-percent-progress-prediction* (truncate *last-percent-progress-prediction* 10)))) (when (> predicted-total-seconds threshold) (print-progress-percent percent) (possibly-note-percent-progress-prediction elapsed predicted-total-seconds threshold 1200)))))))) (force-output) (setf *last-percent-progress-index* percent)))))) (defun print-progress-percent (percent) (write-char #\Space) (print-2-digit-nonnegative-integer percent *standard-output*) (write-char #\%)) (defun print-2-digit-nonnegative-integer (integer stream) (format stream "~2,'0d" integer)) (defun possibly-note-percent-progress-prediction (elapsed predicted-total-seconds threshold &optional show-ending-threshold) (when (and (> predicted-total-seconds threshold) (> predicted-total-seconds elapsed)) (format t " (~a of ~~~a" (elapsed-time-abbreviation-string elapsed) (elapsed-time-abbreviation-string predicted-total-seconds)) (when (and show-ending-threshold (> predicted-total-seconds show-ending-threshold)) (format t ", ending ~~(missing-larkc 13128)") ) (format t ")~% ") t)) (defun compute-percent-progress (index max) (cond ((or (<= max 0) (<= index 0)) 0) ((>= index max) 100) (t (let* ((target-length 10) (current-length (integer-length max)) (scale-factor (- target-length current-length))) (when (minusp scale-factor) (setf index (ash index scale-factor)) (setf max (ash max scale-factor)))) (min 99 (truncate (* 100 index) max))))) (defparameter *progress-note* "") (defparameter *progress-start-time* (get-universal-time)) (defparameter *progress-total* 1) (defparameter *progress-so-far* 0) (defmacro progress-dolist ((var list &optional (message "")) &body body) ;; expansion modeled from memoization_state.clear_all_globally_cached_functions ;; TODO - though it works like dolist, the var's called csome, but there's no early exit functionality? (alexandria:once-only (list) `(progn ;; TODO - why do these set instead of making a new binding? (setf *progress-note* ,message *progress-total* (length ,list) *progress-so-far* 0) (noting-percent-progress (*progress-note*) (dolist (,var ,list) (note-percent-progress *progress-so-far* *progress-total*) (incf *progress-so-far*) ,@body))))) (defparameter *util-var-error-format-string* "~s - var ~s is not a symbol.") (defparameter *util-func-error-format-string* "~s - function ~s is not a symbol.") (defparameter *util-search-type-error-format-string* "~s - search type ~s is not one of (:depth-first :breadth-first).") (deflexical *process-resource-tracking-100s-of-nanoseconds-properties* '(:user-time :system-time) "[Cyc] Properties whose values are expressed in 100s of nanoseconds") (macro-helpers with-process-resource-tracking-in-seconds (defun convert-process-resource-tracking-timing-info-to-seconds (timing-info) "[Cyc] Destructively divides the times in TIMING-INFO to convert them into seconds. Assumes they were originally in 100s of nanoseconds." (let ((converted-timing-info nil)) (loop for (property value) on timing-info by #'cddr do (let ((new-value (if (member property *process-resource-tracking-100s-of-nanoseconds-properties* :test #'eq) (/ value 10000000) value))) (setf (getf converted-timing-info property) new-value))) converted-timing-info)) (defun nadd-clock-time-to-process-resource-timing-info (clock-time timing-info) "[Cyc] @hack until with-process-resource-tracking supports wall clock time" (putf timing-info :wall-clock-time clock-time))) (defglobal *kb-var-initializations* nil "[Cyc] Store of (var init-func) pairs that specify kb-variables and their kb-dependent initialization") (macro-helpers def-kb-variable (defun register-kb-variable-initialization (var-symbol func) "[Cyc] Associates FUNC as the initialization function for VAR-SYMBOL in @xref *kb-var-initializations*" (setf *kb-var-initializations* (alist-enter *kb-var-initializations* var-symbol func)))) (defun initialize-kb-variables () "[Cyc] Initializes all of the KB_vars with their initialization functions. @xref *kb-var-initializations*" (noting-progress ("Initializing KB variables...") (dolist (cons *kb-var-initializations*) (destructuring-bind (var-symbol . func) cons (set var-symbol (funcall func)))))) (defun register-obsolete-cyc-api-function (name replacements arglist doc-string argument-types return-types) "[Cyc] Register NAME as a deprecated (public) Cyc API function. Note its REPLACEMENTS, ARGLIST, DOC-STRING, ARGUMENT-TYPES and RETURN-TYPES." (register-cyc-api-function name arglist doc-string argument-types return-types) (register-obsolete-cyc-api-replacements name replacements)) (defun register-obsolete-cyc-api-replacements (name replacements) "[Cyc] For the symbol NAME, denoting a deprecated Cyc API register the Cyc API replacements. Return the NAME." (declare (symbol name) (list replacements)) (put name :obsolete-cyc-api-replacements replacements)) (defparameter *partial-results-accumulator* nil "[Cyc] Partial results can be accumulated here.") (defparameter *partial-results-size* nil "[Cyc] How many partial results have been stacked up.") (defparameter *partial-results-threshold* 40 "[Cyc] When the partial results, if ever, are supposed to be flushed.") (defparameter *partial-results-total-size* nil "[Cyc] How many results have been computed altogether up.") (defparameter *partial-results-total-accumulator* nil "[Cyc] Once the partial results have been notified, they can be added to here.") (defparameter *partial-results-initialization-fn* 'initialization-for-partial-list-results "[Cyc] How the partial results have to be setup.") (defparameter *partial-results-accumulation-fn* 'accumulation-for-partial-list-results "[Cyc] Who adds a new result to the partial results we already have.") (defparameter *partial-results-consolidation-fn* 'consolidation-for-partial-list-results "[Cyc] Who adds the partial results in the accumulator to the total result set.") (defparameter *partial-results-notification-fn* 'notification-for-partial-list-results "[Cyc] Who gets the partial results as they become available.") (defparameter *partial-results-final-result-fn* 'final-results-for-partial-list-results "[Cyc] How the partial results will be processed for final usage.") (defparameter *accumulating-partial-results?* nil) (defconstant *sxhash-bit-limit* 27 "[Cyc] The number of bits used in the internal integer computations done by sxhash-external.") (deflexical *sxhash-update-state-vector* #(7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 0 1 2 3 4 5 6)) (defun sxhash-update-state (state) "[Cyc] Update the composite hash STATE" (aref *sxhash-update-state-vector* state)) (defparameter *sxhash-composite-state* nil) (defparameter *sxhash-composite-hash* nil)
21,068
Common Lisp
.lisp
394
47.756345
255
0.711925
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
efc2b709026d8471839d5311db13d9a460c5ff8a8bfbc9b7d34e5e18c02fb1f3
6,785
[ -1 ]
6,786
deductions-high.lisp
white-flame_clyc/larkc-cycl/deductions-high.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun* create-deduction-spec (supports) (:inline t) (cons :deduction (canonicalize-supports supports t))) (defun* deduction-spec-supports (deduction-spec) (:inline t) "[Cyc] Returns the list of supports specified by DEDUCTION-SPEC." (cdr deduction-spec)) (defun create-deduction-with-tv (assertion supports tv) (prog1-let ((deduction (create-deduction assertion supports (tv-truth tv)))) (set-deduction-strength deduction (tv-strength tv)))) (defun create-deduction-for-hl-support (hl-support justification) (create-deduction-with-tv hl-support justification (hl-support-tv hl-support))) (defun* create-deduction (assertion supports truth) (:inline t) (kb-create-deduction assertion supports truth)) (defun* remove-deduction (deduction) (:inline t) (kb-remove-deduction deduction)) (defun* set-deduction-strength (deduction new-strength) (:inline t) (kb-set-deduction-strength deduction new-strength)) (defun* find-deduction (assertion supports &optional (truth :true)) (:inline t) "[Cyc] Find the deduction that justifies ASSERTION via SUPPORTS having TRUTH. Return NIL if not present." (kb-lookup-deduction assertion supports truth)) (defun deduction-supports-equal (supports1 supports2) ;; TODO - could create a LENGTH-SAME helper function that doesn't bother with numeric length at all. (and (length= supports1 (length supports2)) (sets-equal? supports1 supports2 #'support-equal))) (defun* deduction-assertion (deduction) (:inline t) "[Cyc] Return the support for which DEDUCTION is a deduction." (and (deduction-handle-valid? deduction) (kb-deduction-assertion deduction))) (defun deduction-truth (deduction) "[Cyc] Return the truth of DEDUCTION -- either :TRUE or :FALSE or :UNKNOWN." (if (deduction-handle-valid? deduction) (kb-deduction-truth deduction) :unknown)) (defun deduction-strength (deduction) (and (deduction-handle-valid? deduction) (possibly-unreify-kb-hl-supports (kb-deduction-supports deduction)))) (defparameter *deduction-dump-id-table* nil) (defun* find-deduction-by-dump-id (dump-id) (:inline t) (find-deduction-by-id dump-id))
3,595
Common Lisp
.lisp
68
48.882353
102
0.756077
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
e9beff00dbc29d8d34ff42c77998946b4196caa8ddaef14d796708178536ec4a
6,786
[ -1 ]
6,787
kb-utilities.lisp
white-flame_clyc/larkc-cycl/kb-utilities.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun kb-statistics (&optional (stream *standard-output*)) (let* ((constant-count (constant-count)) (cached-constant-index-count (cached-constant-index-count)) (nart-count (nart-count)) (cached-nart-index-count (cached-nart-index-count)) (cached-nart-hl-formula-count (cached-nart-hl-formula-count)) (fort-count (fort-count)) (kb-assertion-count (assertion-count)) (cached-assertion-count (cached-assertion-count)) (bookkeeping-assertion-count (bookkeeping-assertion-count)) (virtual-assertion-count 0) (deduction-count (deduction-count)) (cached-deduction-count (cached-deduction-count)) (kb-hl-support-count (kb-hl-support-count)) (cached-kb-hl-support-count (cached-kb-hl-support-count)) (unrepresented-term-count (kb-unrepresented-term-count)) (cached-unrepresented-term-index-count (cached-unrepresented-term-index-count)) (total-assertion-count (+ kb-assertion-count bookkeeping-assertion-count virtual-assertion-count))) (let ((*read-default-float-format* 'double-float)) (format stream "~%;;; KB ~s statistics" (kb-loaded)) (format stream "~%FORTs : ~9,' d" fort-count) (format stream "~% Constants : ~9,' d" constant-count) (unless (zerop constant-count) (format stream "~% cached indexing : ~9,' d (~a%)" cached-constant-index-count (percent cached-constant-index-count constant-count 3))) (format stream "~% NARTs : ~9,' d" nart-count) (unless (zerop nart-count) (format stream "~% cached indexing : ~9,' d (~a%)" cached-nart-index-count (percent cached-nart-index-count nart-count 3)) (format stream "~% cached HL formulas : ~9,' d (~a%)" cached-nart-hl-formula-count (percent cached-nart-hl-formula-count nart-count 3))) (format stream "~%Assertions : ~9,' d" total-assertion-count) (format stream "~% KB Assertions : ~9,' d" kb-assertion-count) (unless (zerop kb-assertion-count) (format stream "~% cached : ~9,' d (~a%)" cached-assertion-count (percent cached-assertion-count kb-assertion-count 3))) (format stream "~% Bookkeeping Assertions : ~9,' d" bookkeeping-assertion-count) (format stream "~%Deductions : ~9,' d" deduction-count) (unless (zerop deduction-count) (format stream "~% cached : ~9,' d (~a%)" cached-deduction-count (percent cached-deduction-count deduction-count 3))) (format stream "~%KB HL supports : ~9,' d" kb-hl-support-count) (unless (zerop kb-hl-support-count) (format stream "~% cached : ~9,' d (~a%)" cached-kb-hl-support-count (percent cached-kb-hl-support-count kb-hl-support-count 3))) (format stream "~%Unrepresented terms : ~9,' d" unrepresented-term-count) (unless (zerop unrepresented-term-count) (format stream "~% cached indexing : ~9,' d (~a%)" cached-unrepresented-term-index-count (percent cached-unrepresented-term-index-count unrepresented-term-count 3))) (terpri stream)))) (deflexical *estimated-assertions-per-constant* 17.1d0) (deflexical *estimated-constants-per-nart* 1.41d0) (deflexical *estimated-assertions-per-deduction* 2.67d0) (deflexical *estimated-assertions-per-clause-struc* 39.3d0) (deflexical *estimated-assertions-per-meta-assertion* 30.3d0) (deflexical *estimated-arguments-per-assertion* 1.12d0) (deflexical *estimated-assertions-per-unrepresented-term* 7.97) (deflexical *estimated-deductions-per-hl-support* 10) (deflexical *kb-table-padding-multiplier* 1.05) (defun setup-kb-tables-int (exact? constant-count nart-count assertion-count deduction-count kb-hl-support-count clause-struc-count kb-unrepresented-term-count) (setf constant-count (ceiling (* constant-count *kb-table-padding-multiplier*))) (setf nart-count (ceiling (* nart-count *kb-table-padding-multiplier*))) (setf assertion-count (ceiling (* assertion-count *kb-table-padding-multiplier*))) (setf deduction-count (ceiling (* deduction-count *kb-table-padding-multiplier*))) (setf kb-hl-support-count (ceiling (* kb-hl-support-count *kb-table-padding-multiplier*))) (setf clause-struc-count (ceiling (* clause-struc-count *kb-table-padding-multiplier*))) (setf kb-unrepresented-term-count (ceiling (* kb-unrepresented-term-count *kb-table-padding-multiplier*))) (setup-kb-fort-tables constant-count nart-count exact?) (setup-kb-assertion-tables assertion-count exact?) (setup-kb-deduction-tables deduction-count exact?) (setup-kb-hl-support-tables kb-hl-support-count exact?) (setup-clause-struc-table clause-struc-count exact?) (setup-unrepresented-term-table kb-unrepresented-term-count exact?) (setup-variable-table) (setup-indexing-tables constant-count) (setup-rule-set assertion-count) (setup-cardinality-tables constant-count)) (defun setup-kb-fort-tables (constant-count nart-count exact?) "[Cyc] Setup the kb fort tables, based on an estimate of CONSTANT-COUNT total constants and NART-COUNT total narts." (let ((constant-table-size constant-count) (nart-table-size nart-count)) (setup-constant-tables constant-table-size exact?) (setup-nart-table nart-table-size exact?) (setup-nart-hl-formula-table nart-table-size exact?) (setup-nart-index-table nart-table-size exact?))) (defun setup-kb-assertion-tables (assertion-table-size exact?) (setup-assertion-table assertion-table-size exact?) (setup-assertion-content-table assertion-table-size exact?)) (defun setup-kb-deduction-tables (deduction-table-size exact?) (setup-deduction-table deduction-table-size exact?) (setup-deduction-content-table deduction-table-size exact?)) (defparameter *default-estimated-constant-count* 50000) (defun clear-kb-state-int () (free-all-clause-strucs) (free-all-kb-hl-support) (free-all-deductions) (free-all-assertions) (free-all-narts) (free-all-constants) (map-constants-in-completions #'init-constant) (clear-unrepresented-term-table) (clear-current-forward-inference-environment) (clear-bookkeeping-binary-gaf-store) (clear-kb-state-hashes)) (defun possibly-clear-dumpable-kb-state-hashes () (when (defns-cache-unbuilt?) (clear-defns-cache)) (when (somewhere-cache-unbuilt?) (clear-all-somewhere-caches))) (defun possibly-initialize-dumpable-kb-state-hashes () (when (nart-hl-formulas-unbuilt?) (missing-larkc 869)) (when (non-fort-isa-tables-unbuilt?) (missing-larkc 1806)) (when (tva-cache-unbuilt?) (missing-larkc 3822)) (when (defns-cache-unbuilt?) (missing-larkc 10610)) (when (somewhere-cache-unbuilt?) (missing-larkc 32146)) (when (arity-cache-unbuilt?) (missing-larkc 12081))) (defun clear-kb-state-hashes () "[Cyc] Clear any hashes related to KB state." (possibly-clear-dumpable-kb-state-hashes) (clear-after-addings) (clear-after-removings) (clear-some-equality-assertions-somewhere-set) (clear-all-arg-type-predicate-caches)) (defun initialize-kb-state-hashes () "[Cyc] Initialize any hashes related to KB state." (possibly-initialize-dumpable-kb-state-hashes) (rebuild-after-adding-caches) (initialize-some-equality-assertions-somewhere-set) (initialize-all-arg-type-predicate-caches)) (defun swap-out-all-pristine-kb-objects () (swap-out-all-pristine-assertions) (swap-out-all-pristine-deductions) (swap-out-all-pristine-constant-indices) (swap-out-all-pristine-nart-indices) (swap-out-all-pristine-nart-hl-formulas) (swap-out-all-pristine-unrepresented-term-indices) (swap-out-all-pristine-kb-hl-supports) (swap-out-all-pristine-sbhl-module-graph-links)) (defparameter *sort-terms-constants-by-name* t) (defparameter *sort-terms-ignore-variable-symbols* nil) (defparameter *sort-terms-by-internal-id?* nil "[Cyc] This trumps *SORT-TERMS-CONSTANTS-BY-NAME*.") (defun sort-terms (list &optional copy? stable? constants-by-name? ignore-variable-symbols? (key #'identity) use-internal-ids?) (let ((*sort-terms-constants-by-name* constants-by-name?) (*sort-terms-ignore-variable-symbols* ignore-variable-symbols?) (*sort-terms-by-internal-id?* use-internal-ids?) (seq (if copy? (copy-list list) list)) (sort-func (if stable? #'stable-sort #'sort))) (funcall sort-func seq #'form-sort-pred :key key))) (defun term-< (term1 term2 &optional constants-by-name? ignore-variable-symbols? use-internal-ids?) (let ((*sort-terms-constants-by-name* constants-by-name?) (*sort-terms-ignore-variable-symbols* ignore-variable-symbols?) (*sort-terms-by-internal-id?* use-internal-ids?)) (form-sort-pred term1 term2))) (defun form-sort-pred (form1 form2) (unless (eq form1 form2) (if (atom form1) (if (atom form2) (atom-sort-pred form1 form2) t) (if (atom form2) nil (cons-sort-pred form1 form2))))) (defun cons-sort-pred (cons1 cons2) (loop for curr-cons1 on cons1 for curr-cons2 on cons2 for car1 = (car curr-cons1) for car2 = (car curr-cons2) do (cond ((form-sort-pred car1 car2) (return t)) ((form-sort-pred car2 car1) (return nil)) (t (let ((cdr1 (cdr curr-cons1)) (cdr2 (cdr curr-cons2))) (if (atom cdr1) (if (atom cdr2) (return (atom-sort-pred cdr1 cdr2)) (return t)) (when (atom cdr2) (return nil)))))))) (defun atom-sort-pred (atom1 atom2) (unless (eq atom1 atom2) ;; TODO - what a horrible mess. Must be a macroexpansion from a sort order spec. At some point, reverse what the spec is, especially since we could add to or modify the supported atom types in the future. Also, somehow ensure that this didn't gain translation errors from the java. (or (and (fort-p atom1) (or (not (fort-p atom2)) (fort-sort-pred atom1 atom2))) (and (not (fort-p atom2)) (or (and (variable-p atom1) (or (not (variable-p atom2)) (variable-< atom1 atom2))) (and (not (variable-p atom2)) (or (and (symbolp atom1) (or (not (symbolp atom2)) (symbol-sort-pred atom1 atom2))) (and (not (symbolp atom2)) (or (and (stringp atom1) (or (not (stringp atom2)) (string< atom1 atom2))) (and (not (stringp atom2)) (or (and (numberp atom1) (or (not (numberp atom2)) (< atom1 atom2))) (and (characterp atom1) (not (numberp atom2)) (or (not (characterp atom2)) (char< atom1 atom2)))))))))))))) (defun symbol-sort-pred (symbol1 symbol2) ;; TODO - ugh, another one. This is rotting my brain. Same note as above, but this has the additional fun of unreachable code from missing-larkc. But I kept all the structure for sanity's sake. (or (and (keywordp symbol1) (or (not (keywordp symbol2)) (string< (symbol-name symbol1) (symbol-name symbol2)))) (and (not (keywordp symbol2)) (or (and (missing-larkc 32021) (or (not (missing-larkc 32022)) (and (not *sort-terms-ignore-variable-symbols*) (string< (symbol-name symbol1) (symbol-name symbol2))))) (and (not (missing-larkc 32023)) (string< (symbol-name symbol1) (symbol-name symbol2))))))) (defun fort-sort-pred (fort1 fort2) (if (nart-p fort1) (if (nart-p fort2) (missing-larkc 4905) nil) (if (nart-p fort2) t (constant-sort-pred fort1 fort2)))) (defun constant-sort-pred (constant1 constant2) (if *sort-terms-by-internal-id?* (missing-larkc 31624) (if *sort-terms-constants-by-name* (atom-sort-pred (constant-name constant1) (constant-name constant2)) (constant-external-id-< constant1 constant2)))) (deflexical *definitional-pred-sort-order* (list #$isa #$genls #$genlPreds #$genlInverse #$genlMt #$disjointWith #$negationPreds #$negationInverse #$negationMt #$defnIff #$defnSufficient #$defnNecessary #$resultIsa #$resultIsaArg #$resultGenl #$resultGenlArg #$arity #$arityMin #$arityMax #$argsIsa #$argsGenl #$arg1Isa #$arg1Genl #$arg2Isa #$arg2Genl #$arg3Isa #$arg3Genl #$arg4Isa #$arg4Genl #$arg5Isa #$arg5Genl #$argIsa #$argGenl #$fanOutArg #$evaluationDefn #$afterAdding #$afterRemoving)) ;; TODO DESIGN - removed the term-order methods, as their bodies were all missing-larkc ;; TODO - missing some -caching-state variables, as there's no matching defun (defparameter *set-to-collection-uses-reformulator?* t "[Cyc] Temporary variable. @todo hard-code to T." ;; this todo is done? ) (deflexical *forbidden-kb-covering-collection-types* (list #$UnderspecifiedCollectionType #$CycKBSubsetCollection) "[Cyc] Instances of any of these collections are forbidden.") (deflexical *forbidden-kb-covering-quoted-collection-types* (list #$WorkflowConstant #$TPTP-PLA001-1-ProblemFORT #$PoorlyOntologized #$StubTerm #$IndeterminateTerm) "[Cyc] Quoted instances of any of these collections are forbidden.") ;; TODO DESIGN - I wonder if these forbiddings are to ensure private client data doesnt escape? See if this is referenced in the larkc version. (deflexical *forbidden-cols* (list #$PotentialCBRNEThreat #$Y2KThing #$BPVMilitaryUnit #$BPVEvent #$BPVArtifact #$BPVAgent #$HPKB-TransnationalAgent) "[Cyc] These exact collections are forbidden.") (deflexical *forbidden-specs* nil "[Cyc] Specs of any of these collections are forbidden.") (defparameter *min-each-spec-cardinality* nil "[Cyc] Temporary variable for forbidden-kb-covering-collection?.") (deflexical *predicate-type-arity-table* '((1 . #$UnaryPredicate) (2 . #$BinaryPredicate) (3 . #$TernaryPredicate) (4 . #$QuaternaryPredicate) (5 . #$QuintaryPredicate))) (defparameter *coasserted-fort-source* nil) (defparameter *coasserted-fort-set* nil)
19,042
Common Lisp
.lisp
354
39.039548
285
0.565801
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
5a6c8e802a66946833a55079c39e895e9a34f656f5278f94987c6039aa4dcc89
6,787
[ -1 ]
6,788
hl-storage-modules.lisp
white-flame_clyc/larkc-cycl/hl-storage-modules.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO DESIGN - these functions pass a ton of variables around, which is both slow and messy for readability. Might be able to speed up these call chains by judicious inlining, having a single set of dynamic bindings established on entry, or wrapping these utilities in a single closure. (defglobal *hl-storage-modules* (new-set #'eq) "[Cyc] Set of HL storage modules (set-p of hl-module-p).") (defglobal *predicate-generic-hl-storage-modules* (new-set #'eq) "[Cyc] Set of generic (non-predicate-specific) HL storage modules.") (defglobal *predicate-specific-hl-storage-modules-table* (make-hash-table :test #'eq) "[Cyc] Mapping between predicates and a list of their HL storage modules.") (defglobal *argument-type-specific-hl-storage-modules-table* (make-hash-table :test #'eq) "[Cyc] Mapping between argument types and a list of HL storage modules that handle that argument type.") (defun hl-storage-module (name plist) "[Cyc] Declare and create a new HL storage module with name NAME and properties PLIST." (setup-hl-storage-module name plist)) (defun try-hl-add-modules (hl-modules argument-spec cnf mt direction variable-map) "[Cyc] Tests for applicability and attempts to add to the store. Returns whether the addition was successful." (try-hl-storage-modules-int hl-modules argument-spec cnf mt direction variable-map :add)) (defun try-hl-remove-modules (hl-modules argument-spec cnf mt) "[Cyc] Tests for applicability and attempts to remove an argument from the store. Returns whether the removal was successful." (try-hl-storage-modules-int hl-modules argument-spec cnf mt nil nil :remove)) (defun* hl-storage-modules-for-predicate-and-argument-type (predicate argument-type) (:inline t) (fast-intersection (hl-storage-modules-for-predicate predicate) (hl-storage-modules-for-argument-type argument-type))) (defun hl-storage-modules-for-predicate (predicate) (copy-list (gethash predicate *predicate-specific-hl-storage-modules-table*))) (defun hl-storage-modules-for-argument-type (argument-type) (let ((genls (argument-type-genls argument-type))) (loop for genl in genls nconc (hl-storage-modules-for-just-argument-type genl)))) (defun hl-storage-modules-for-just-argument-type (argument-type) "[Cyc] Accessor analogous to indexing, does not implement inheritance. Result is destructible" (copy-list (gethash argument-type *argument-type-specific-hl-storage-modules-table*))) (defparameter *currently-executing-hl-storage-module* nil) (defun try-hl-storage-modules-int (hl-modules argument-spec cnf mt direction variable-map action &optional default) "[Cyc] This assumes a partition rather than a covering; we could relax this to allow more than one of HL-MODULES to apply." (let ((success? nil)) ;; TODO - assuming *resourcing-sbhl-marking-spaces-p* is related to memory areas/spaces and unused here. (multiple-value-bind (applicable-hl-modules dispreferred-hl-modules) (applicable-hl-storage-modules hl-modules argument-spec cnf mt direction variable-map) ;; All references to this were after the missing-larkc (declare (ignore dispreferred-hl-modules)) (let ((sorted-applicable-hl-modules (sort-hl-storage-modules-by-cost applicable-hl-modules argument-spec cnf mt direction variable-map))) (csome (hl-module sorted-applicable-hl-modules success?) (setf success? (apply-hl-storage-module hl-module argument-spec cnf mt direction variable-map action default)) (when success? (note-successful-hl-storage-module hl-module))) ;; outside CSOME loop (unless success? (missing-larkc 31649)))) success?)) (defun apply-hl-storage-module (hl-module argument-spec cnf mt direction variable-map action default) (let ((*currently-executing-hl-storage-module* hl-module)) (case action (:add (hl-storage-module-add hl-module argument-spec cnf mt direction variable-map default)) (:remove (hl-storage-module-remove hl-module argument-spec cnf mt default)) (:remove-all (missing-larkc 31641))))) (defun hl-storage-module-applicable? (hl-module argument-spec cnf mt direction variable-map) (let ((applicable-func (hl-storage-module-applicability-func hl-module))) ;; TODO - funcalled symbol (if (fboundp applicable-func) (funcall applicable-func argument-spec cnf mt direction variable-map) (missing-larkc 31637)))) (defun applicable-hl-storage-modules (hl-modules argument-spec cnf mt direction variable-map) (let ((supplanted-hl-modules nil) (dispreferred-hl-modules nil) (applicable-hl-modules nil) (exclusive-found? nil)) (csome (hl-module hl-modules exclusive-found?) (unless (member? hl-module supplanted-hl-modules) (when (or (alist-lookup-without-values dispreferred-hl-modules hl-module) (hl-storage-module-applicable? hl-module argument-spec cnf mt direction variable-map)) (let ((exclusive-func (hl-storage-module-exclusive-func hl-module))) (when (or (not exclusive-func) (and (function-spec-p exclusive-func) (funcall exclusive-func argument-spec cnf mt direction variable-map))) (when exclusive-func (missing-larkc 31652)) (unless exclusive-found? (multiple-value-bind (applicable-hl-modules-4 dispreferred-hl-modules-5) (update-dispreferred-hl-storage-modules-wrt-applicable-modules hl-module applicable-hl-modules dispreferred-hl-modules hl-modules argument-spec cnf mt direction variable-map) (setf applicable-hl-modules applicable-hl-modules-4) (setf dispreferred-hl-modules dispreferred-hl-modules-5))) (when (or exclusive-found? (not (alist-lookup dispreferred-hl-modules hl-module))) (push hl-module applicable-hl-modules))))))) (values (nreverse applicable-hl-modules) (unless exclusive-found? dispreferred-hl-modules)))) (defun update-dispreferred-hl-storage-modules-wrt-applicable-modules (hl-module applicable-hl-modules dispreferred-hl-modules hl-modules argument-spec cnf mt direction variable-map) ;; TODO - java did an empty pcase over this value? (let ((newly-dispreferred-module-names (hl-storage-module-preferred-over-info hl-module))) (dolist (dispreferred-module-name newly-dispreferred-module-names) (let ((dispreferred-hl-module (find-hl-module-by-name dispreferred-module-name))) (when (member? dispreferred-hl-module hl-modules) (cond ((member? dispreferred-hl-module applicable-hl-modules) (setf applicable-hl-modules (delete dispreferred-hl-module applicable-hl-modules)) (setf dispreferred-hl-modules (alist-push dispreferred-hl-modules dispreferred-hl-module hl-module))) ((alist-lookup dispreferred-hl-modules dispreferred-hl-module) (setf dispreferred-hl-modules (alist-push dispreferred-hl-modules dispreferred-hl-module hl-module))) ((hl-storage-module-applicable? dispreferred-hl-module argument-spec cnf mt direction variable-map) (setf dispreferred-hl-modules (alist-push dispreferred-hl-modules dispreferred-hl-module hl-module)))))))) (values applicable-hl-modules dispreferred-hl-modules)) (defun* sort-hl-storage-modules-by-cost (hl-modules argument-spec cnf mt direction variable-map) (:inline t) (declare (ignore argument-spec cnf mt direction variable-map)) hl-modules) (defun* hl-storage-module-add (hl-module argument-spec cnf mt direction variable-map &optional default) (:inline t) "[Cyc] If HL-MODULE has an :ADD property, the specified function is applied to ARGUMENT-SPEC, CNF, MT, DIRECTION, and VARIABLE-MAP. Otherwise, DEFAULT is returned." (if-let ((add-func (get-hl-storage-module-property hl-module :add))) (funcall add-func argument-spec cnf mt direction variable-map) default)) (defun* hl-storage-module-remove (hl-module argument-spec cnf mt &optional default) (:inline t) "[Cyc] If HL-MODULE has a :REMOVE property, the specified function is applied to ARGUMENT-SPEC, CNF, and MT. Otherwise, DEFAULT is returned." (if-let ((remove-func (get-hl-storage-module-property hl-module :remove))) (funcall remove-func argument-spec cnf mt) default)) (defun* hl-storage-module-argument-type (hl-module) (:inline t) (get-hl-storage-module-property hl-module :argument-type)) (defun* hl-storage-module-predicate (hl-module) (:inline t) (get-hl-storage-module-property hl-module :predicate)) (defun* hl-storage-module-applicability-func (hl-module) (:inline t) (multiple-value-bind (applicability-func default?) (get-hl-storage-module-property hl-module :applicability) (unless default? applicability-func))) (defun* hl-storage-module-exclusive-func (hl-module) (:inline t) (get-hl-storage-module-property hl-module :exclusive)) (defun* hl-storage-module-preferred-over-info (hl-module) (:inline t) (get-hl-storage-module-property hl-module :preferred-over)) (defun* get-hl-storage-module-property (hl-module indicator) (:inline t) (hl-module-property hl-module indicator)) (defun reclassify-hl-storage-modules () (clear-hl-storage-module-indexes) (rebuild-solely-specific-hl-storage-module-predicate-store) (do-set (hl-module *hl-storage-modules*) (classify-hl-storage-module hl-module (hl-storage-module-predicate hl-module) (hl-storage-module-argument-type hl-module)))) ;; TODO - this list was directly referenced in the java ($list28), so should this really be defconstant? (deflexical *hl-storage-module-properties* '(:pretty-name :module-subtype :module-source :argument-type :sense :direction :required-mt :predicate :any-predicates :applicability-pattern :applicability :supplants :exclusive :preferred-over :incompleteness :add :remove :remove-all :documentation)) (defun clear-hl-storage-module-indexes () (setf *predicate-generic-hl-storage-modules* (new-set #'eq)) (clrhash *predicate-specific-hl-storage-modules-table*)) (defun setup-hl-storage-module (name plist) (destructuring-bind (&key pretty-name module-subtype module-source argument-type sense direction required-mt predicate any-predicates applicability-pattern applicability supplants exclusive preferred-over incompleteness add remove remove-all documentation) plist ;; TODO - tons of check-type calls in here, depending on if the keyword was given, but nothing was done with them? I guess this just verifies the option shapes/values without doing anything with them? (declare (ignore pretty-name module-subtype module-source argument-type sense direction required-mt predicate any-predicates applicability-pattern applicability supplants exclusive preferred-over incompleteness add remove remove-all documentation)) (register-hl-storage-module name plist))) (defun register-hl-storage-module (name plist) (let ((hl-module (progn (setup-module name :storage plist) *hl-storage-modules*))) (classify-hl-storage-module hl-module (getf plist :predicate) (getf plist :argument-type)) hl-module)) (defun classify-hl-storage-module (hl-module predicate argument-type) (if predicate (register-predicate-specific-hl-storage-module hl-module predicate) (register-predicate-generic-hl-storage-module hl-module)) (register-argument-type-specific-hl-storage-module hl-module argument-type)) (defun register-predicate-specific-hl-storage-module (hl-module predicate) ;; TODO - dictionary calls have the opposite arg ordering from hashtables and sets, change that when the utils move into hashtable-utilities. (dictionary-pushnew *predicate-specific-hl-storage-modules-table* predicate hl-module)) (defun register-predicate-generic-hl-storage-module (hl-module) (set-add hl-module *predicate-generic-hl-storage-modules*)) (defun register-argument-type-specific-hl-storage-module (hl-module argument-type) (dictionary-pushnew *argument-type-specific-hl-storage-modules-table* argument-type hl-module)) (defglobal *solely-specific-hl-storage-module-predicate-store* (new-set #'eq)) (defun* rebuild-solely-specific-hl-storage-module-predicate-store () (:inline t) (set-rebuild *solely-specific-hl-storage-module-predicate-store*)) (defun* register-solely-specific-hl-storage-module-predicate (predicate) (:inline t) "[Cyc] If you want the specific hl-storage modules for PREDICATE to supplant ALL generic hl-storage modules, then register this property." (set-add predicate *solely-specific-hl-storage-module-predicate-store*)) (defun* solely-specific-hl-storage-module-predicate? (predicate) (:inline t) (set-member? predicate *solely-specific-hl-storage-module-predicate-store*)) (defstruct (hl-assertion-spec (:type list) (:constructor new-hl-assertion-spec (cnf mt &optional direction variable-map))) cnf mt direction variable-map) (defstruct (hl-assertible (:type list) (:constructor new-hl-assertible (hl-assertion-spec argument-spec))) hl-assertion-spec argument-spec) (defun hl-add-assertible (hl-assertible) ;; TODO - probably should build an easy structure destructuring macro, when these aren't in order. (apply #'hl-add-argument hl-assertible)) (defun hl-add-argument (argument-spec cnf mt direction &optional variable-map) "[Cyc] Returns NIL if the argument specified by ARGUMENT-SPEC was /not/ added as an argument for CNF, and non-NIL otherwise." (janus-note-argument argument-spec cnf mt direction variable-map) ;; TODO - probably tear these out to avoid a bunch of always-false runtime checks. (when *recording-hl-transcript-operations?* (missing-larkc 32159)) (when (hlmts-supported?) (setf mt (canonicalize-hlmt mt))) (hl-store-perform-action-int :add argument-spec cnf mt direction variable-map)) (defun hl-remove-argument (argument-spec cnf mt) (when *recording-hl-transcript-operations?* (missing-larkc 32160)) (hl-store-perform-action-int :remove argument-spec cnf mt nil nil)) (defparameter *successful-hl-storage-modules* nil) (defun note-successful-hl-storage-module (hl-module) (set-add hl-module *successful-hl-storage-modules*)) (defun hl-store-perform-action-int (action argument-spec cnf mt direction variable-map) (let ((success? nil) (solely-specific? nil) (argument-type (and argument-spec (argument-spec-type argument-spec))) (*successful-hl-storage-modules* (new-set))) (when (atomic-clause-p cnf) (let* ((predicate (atomic-cnf-predicate cnf)) (predicate-specific-modules (if argument-type (hl-storage-modules-for-predicate-and-argument-type predicate argument-type) (hl-storage-modules-for-predicate predicate)))) (setf solely-specific? (solely-specific-hl-storage-module-predicate? predicate)) (when predicate-specific-modules (setf success? (hl-perform-action-with-storage-modules-int action predicate-specific-modules argument-spec cnf mt direction variable-map))))) (unless success? (unless solely-specific? (missing-larkc 31629))) success?)) (deflexical *robustly-remove-uncanonical-decontextualized-assertibles?* t "[Cyc] Whether the HL storage modules should robustly try to remove a decontextualized assertible from the MT given by the user in addition to removing it from its proper, decontextualized MT. This can happen for example when a predicate is asserted to be decontextualized _after_ some assertions have already been made with it in other MTs.") (defun hl-perform-action-with-storage-modules-int (action hl-modules argument-spec cnf mt direction variable-map) (let ((actual-mt (possibly-convention-mt-for-decontextualized-cnf mt cnf))) (case action (:add (try-hl-add-modules hl-modules argument-spec cnf actual-mt direction variable-map)) (:remove (let ((success? (try-hl-remove-modules hl-modules argument-spec cnf actual-mt)) (robust-success? (and *robustly-remove-uncanonical-decontextualized-assertibles?* (not (hlmt-equal mt actual-mt)) (try-hl-remove-modules hl-modules argument-spec cnf mt)))) (or success? robust-success?))) (:remove-all (missing-larkc 31650)) (otherwise (error "Unexpected HL storage action ~a" action))))) (defun* hl-assert (cnf mt strength direction &optional variable-map) (:inline t) "[Cyc] Returns NIL if CNF was not stored at the HL in some fashion, and non-NIL otherwise. If CNF is stored as an as assertion object, that assertion object (assertion-p) will be returned, but there is no guarantee that CNF will be stored as an assertion." (hl-add-argument (create-asserted-argument-spec strength) cnf mt direction variable-map)) (defglobal *dummy-asserted-argument-spec* (create-asserted-argument-spec :unspecified)) (defun* hl-unassert (cnf mt) (:inline t) (hl-remove-argument *dummy-asserted-argument-spec* cnf mt))
20,127
Common Lisp
.lisp
299
56.725753
345
0.687227
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
6e2485ad69c70b0cf8605bcbe3b6d7dca0294703bda122f6d43349ecaf6af81b
6,788
[ -1 ]