I have a series of rules and a set of initial (assert) facts. Now, I want to add those facts, run the rules, and then apply another set of rules to check if the current existing facts after (run) contains correct facts and nothing else, without triggering the previous rules anymore and without destroying current facts. Then, I want to keep going applying new facts, running new rules, and test new inserted facts, etc.
How can I do that? My test (batch) file is something like:
(clear) ; just in case
(load constructs.clp) ; All loaded in the MAIN module.
(assert (blabla))
(assert (blabla2))
(run)
;; Code (rules/functions... I'm still wondering how to do it) to check
;; current facts
(assert (blabla3))
(assert (blabla4))
(run)
;; More tests.
(exit)
I have tried to create, for each deftemplate T a deftemplate T-copy with same slots and them apply a (assert (testing)) fact to make the copies first. Then I fire a set of rules with testing purposes and higher salience that "halts" the (run) execution when it's done, to avoid firing the previous rules (the rules I'm testing). The problem with that approach, apart from requiring too many steps, is that I don't know the salience of the original rules and so I cannot be sure that the testing rules will have more priority.
I'm aware of the defmodule constructs and the focus stack but I haven't understood them yet. If my guesses are correct, I think I could put all of my testing rules in a specific module and place the focus on that module to avoid execution of any MAIN rule. If something is wrong, I'll (halt)
execution in one of the testing rules or just (exit) the batch script. If everything is correct, I pop the testing module to come back to MAIN, add more assert, (run) again, and them push the testing module again with new tests to see if everything is still correct.
But I'm not sure if my assumptions are right I'll like to see an example of how should I do the testing.
PD: In addition, my CLIPS version has no support for fact-set queries.
Here's the general idea of separating the core group of rules from the rules doing the testing into separate modules and then using the focus command to execute the testing rules.
CLIPS> (defmodule MAIN (export ?ALL))
CLIPS> (deftemplate MAIN::point (slot x) (slot y))
CLIPS>
(defrule MAIN::r1
=>
(assert (point (x 1) (y 2)))
(assert (point (x 1) (y 5))))
CLIPS> (defmodule TESTING (import MAIN ?ALL))
CLIPS>
(defrule TESTING::horizontal
(point (x ?x1) (y ?y))
(point (x ?x2&:(< ?x2 ?x1)) (y ?y))
=>
(printout t "Horizonal issue " ?y crlf))
CLIPS> (reset)
CLIPS> (agenda)
0 r1: *
For a total of 1 activation.
CLIPS> (run)
CLIPS> (facts)
f-0 (initial-fact)
f-1 (point (x 1) (y 2))
f-2 (point (x 1) (y 5))
For a total of 3 facts.
CLIPS> (focus TESTING)
TRUE
CLIPS> (agenda)
CLIPS> (run)
CLIPS>
(defrule MAIN::r2
=>
(assert (point (x 3) (y 2))))
CLIPS> (run)
CLIPS> (facts)
f-0 (initial-fact)
f-1 (point (x 1) (y 2))
f-2 (point (x 1) (y 5))
f-3 (point (x 3) (y 2))
For a total of 4 facts.
CLIPS> (focus TESTING)
TRUE
CLIPS> (run)
Horizonal issue 2
CLIPS>
(defrule TESTING::vertical
(point (x ?x) (y ?y1))
(point (x ?x) (y ?y2&:(< ?y2 ?y1)))
=>
(printout t "Vertical issue " ?x crlf))
CLIPS> (focus TESTING)
TRUE
CLIPS> (agenda)
0 vertical: f-2,f-1
For a total of 1 activation.
CLIPS> (run)
Vertical issue 1
CLIPS>
Related
I'm trying to create a AutoLISP function that takes the selection sets layer and store it in a variable.
I want to select multiply objects, which is allways in the same layer and then change the layer later with some commands.
I have tried the following, based on (setq currentlayer (assoc 8 (entget (car (entsel)) )))
My code is:
(defun c:objectslayer()
(setq objects (car (ssget))) ; Need to select multiply objects
(setq currentlayer (entget objects)) ; Need the layer of the objects, in my case, it will allways be in the same layer
(setq cl (assoc 8 currentlayer)) ; Need the layer, for commands to change the layer later
(prompt (strcat "\nThe layer of the objects is: " cl))
(princ)
)
I appreciate all the help and point of direction
Thanks in advance
Without supplying a filter list argument to the ssget function, you cannot guarantee that all objects within the selection will reside on the same layer.
If you are targeting a specific layer with your program, then I would suggest using a filter list to only permit selection of objects residing on such layer, e.g.:
(ssget '((8 . "YourLayerHere")))
Alternatively, you could prompt for selection of a single object to set the target layer (using entsel), and then prompt for a selection of multiple objects residing on such layer using ssget with a filter list constructed using the layer of the entity obtained from entsel e.g.:
(if
(and
(setq ent (car (entsel "\nSelect object on target layer: ")))
(setq sel (ssget (list (assoc 8 (entget ent)))))
)
(progn
;; Do some operations ...
)
)
If you really want to permit the user to select objects on any layer, then to obtain a list of the layers selected, you could use something like:
(defun c:test ( / idx lay lst sel )
(if (setq sel (ssget))
(progn
(repeat (setq idx (sslength sel))
(setq idx (1- idx)
lay (cdr (assoc 8 (entget (ssname sel idx))))
)
(if (not (member lay lst)) (setq lst (cons lay lst)))
)
(print lst)
)
)
(princ)
)
For more information on how to iterate over the objects in a selection set, you may wish to refer to my tutorial on Selection Set Processing.
In an answer to this question, Leonardo posts a link to "Exact nonlinear optimization on demand". This sounds like nonlinear optimization will be (or is?) supported by vZ. In the paper "νZ - An Optimizing SMT Solver", the abstract says:
νZ
provides a portfolio of approaches for solving
linear optimization problems over SMT formulas, MaxSMT, and their
combinations.
This again sounds like nonlinear optimizations are out of scope at the moment.
I played around with this smt2 code:
(set-option :pp.decimal true)
(set-option :produce-models true)
(declare-fun x () Real)
(declare-fun y () Real)
(assert (= y (+ 1 (^ (- x 1) 2.0))))
(assert (and (<= (- 3.0) x) (< x 3.0)))
(assert (and (<= (- 3.0) y) (< y 3.0)))
(minimize y)
(check-sat)
(get-value (x y))
(exit)
As an answer I get this response:
unknown
(objectives
(y ((* (- 1) oo) oo))
)
((x 0.0)
(y 2.0))
So I guess, that nonlinear functions are indeed not supported by vZ.
Are there plans in doing so?
I have a Common Lisp function that merges two ordered lists of symbols, without duplicates (two ordered sets):
(defun my-merge (x y)
"merge two lists of symbols *already sorted and without duplicates*
(and return the resulting list sorted and without duplicates)"
(let* ((first (cons nil nil))
(last first))
(loop while (and x y)
for cx = (car x)
for cy = (car y)
if (string= cx cy)
do (setf x (cdr x))
else if (string< cx cy)
do (rplacd last (cons cx nil))
and do (setf last (cdr last)
x (cdr x))
else do (rplacd last (cons cy nil))
and do (setf last (cdr last)
y (cdr y)))
(rplacd last (or x y))
(cdr first)))
Since I have found only scarce information about the use of type declarations in practical cases in order to compile efficiently the code, I am unsure if it is sufficient to declare the variables, for instance in this way:
(defun my-merge (x y)
"merge two list of symbols *already sorted and without duplicates*"
(declare (list x y))
(let* ((first (cons nil nil))
(last first))
(declare (cons first last))
(loop while (and x y)
for cx symbol = (car x)
for cy symbol = (car y)
...
or, as I suppose, if it is necessary also to add the the specifier to my code? But then, where and in which cases should I add it?
There is some rule that one can follow?
Should I also declare the type of my functions, again for the optimization purposes?
Style
Since you don't actually use the extended LOOP features in any useful way and the LOOP syntax isn't that great for your example, I would propose to write it with the primitive LOOP. See how COND makes it more readable for a Lisp programmer:
(defun my-merge (x y &aux (first (list nil)) (last first) cx cy)
(macrolet ((cdr! (v)
`(setf ,v (cdr ,v))))
(loop (unless (and x y)
(return))
(setf cx (car x) cy (car y))
(cond ((string= cx cy)
(cdr! x))
((string< cx cy)
(rplacd last (list cx))
(cdr! last)
(cdr! x))
(t
(rplacd last (list cy))
(cdr! last)
(cdr! y))))
(rplacd last (or x y))
(cdr first)))
Compiling
Given the level of sophistication of a compiler:
fully stupid = compiler ignores all declarations -> declarations don't help
mostly stupid = compiler needs declarations everywhere, but optimizes -> you need to write a lot of declarations
example:
(let ((a 1) (b 2))
(declare (integer a b))
(let ((c (the integer (* (the integer (+ a b))
(the integer (- a b))))))
(declare (integer c))
(the integer (* c c))))
Note that it might not enough to know what the argument types are, it might be necessary to declare the type of results. Thus the use of the. DISASSEMBLE and the profiler are your friends.
basic = compiler needs type declarations, optimizes, but also can infer some types. Types for the standard language is known.
Even better compilers complain about type errors, can propagate types across functions and can complain when certain optimizations are not possible.
Sequence functions
Note that sequence functions are a particular tough case. Sequences have as subtypes lists and vectors (including strings).
Let's say a sequence function is:
(foo result-type sequence-1 sequence-2 fn)
if the sequences are of the same type, one might want to have an optimized code versions for lists and another one for vectors.
if the sequences are of different types, it might be useful to convert one sequences to a different type. Maybe not.
the result type also has influence, depending on result types, different algorithms may be possible/necessary
So the degree of freedom is quite high. The compiler might contribute to fast code. But also the implementation of the particular sequence function might be able to do some optimization at runtime.
Then fn is a function which takes elements and produces new elements. It might be helpful to know its type signature - or not.
I can't really say which current Common Lisp has a sophisticated implementation of the sequence functions. Though I remember that the Symbolics Common Lisp implementations put some effort into it.
Documentation and papers
Often what the compiler can optimize and how is not well documented, if at all. There are some papers about this topic, but often they are old and/or outdated.
The Python compiler of CMUCL: The Compiler.
The Python compiler of CMUCL: Advanced Compiler Use.
The Python compiler for CMU Common Lisp (Postscript)
SBCL Compiler
Allegro CL: Compiling
LispWorks: Optimizing your code
Performance beyond expectations
How to make Lisp code go faster than C
An evaluation of major Lisp compilers
I want to implement the vim commandT plugin in emacs. This code is mostly a translation from the matcher.
I've got some elisp here that's still too slow to use on my netbook -
how can I speed it up?
(eval-when-compile (require 'cl))
(defun commandT-fuzzy-match (choices search-string)
(sort (loop for choice in choices
for score = (commandT-fuzzy-score choice search-string (commandT-max-score-per-char choice search-string))
if (> score 0.0) collect (list score choice))
#'(lambda (a b) (> (first a) (first b)))
))
(defun* commandT-fuzzy-score (choice search-string &optional (score-per-char (commandT-max-score-per-char choice search-string)) (choice-pointer 0) (last-found nil))
(condition-case error
(loop for search-char across search-string
sum (loop until (char-equal search-char (elt choice choice-pointer))
do (incf choice-pointer)
finally return (let ((factor (cond (last-found (* 0.75 (/ 1.0 (- choice-pointer last-found))))
(t 1.0))))
(setq last-found choice-pointer)
(max (commandT-fuzzy-score choice search-string score-per-char (1+ choice-pointer) last-found)
(* factor score-per-char)))))
(args-out-of-range 0.0) ; end of string hit without match found.
))
(defun commandT-max-score-per-char (choice search-string)
(/ (+ (/ 1.0 (length choice)) (/ 1.0 (length search-string))) 2))
Be sure to compile that part, as that already helps a lot.
And a benchmark:
(let ((choices (split-string (shell-command-to-string "curl http://sprunge.us/FcEL") "\n")))
(benchmark-run-compiled 10
(commandT-fuzzy-match choices "az")))
Here are some micro optimizations you can try:
Use car-less-than-car instead of your lambda expression. This has no visible effect since the time is not spent in sort but in commandT-fuzzy-score.
Use defun instead of defun*: those optional arguments with a non-nil default have a non-negligible hidden cost. This reduces the GC cost by almost half (and you started with more than 10% of the time spent in the GC).
(* 0.75 (/ 1.0 XXX)) is equal to (/ 0.75 XXX).
use eq instead of char-equal (that changes the behavior to always be case-sensitive, tho). This makes a fairly large difference.
use aref instead of elt.
I don't understand why you pass last-found in your recursive call, so I obviously don't fully understand what your algorithm is doing. But assuming that was an error, you can turn it into a local variable instead of passing it as an argument. This saves you time.
I don't understand why you make a recursive call for every search-char that you find, instead of only for the first one. Another way to look at this is that your max compares a "single-char score" with a "whole search-string score" which seems rather odd. If you change your code to do the max outside of the two loops with the recursive call on (1+ first-found), that speeds it up by a factor of 4 in my test case.
The multiplication by score-per-char can be moved outside of the loop (this doesn't seem to be true for your original algorithm).
Also, the Elisp as implemented in Emacs is pretty slow, so you're often better off using "big primitives" so as to spend less time interpreting Elisp (byte-)code and more time running C code. Here is for example an alternative implementation (not of your original algorithm but of the one I got after moving the max outside of the loops), using regexp pattern maching to do the inner loop:
(defun commandT-fuzzy-match-re (choices search-string)
(let ((search-re (regexp-quote (substring search-string 0 1)))
(i 1))
(while (< i (length search-string))
(setq search-re (concat search-re
(let ((c (aref search-string i)))
(format "[^%c]*\\(%s\\)"
c (regexp-quote (string c))))))
(setq i (1+ i)))
(sort
(delq nil
(mapcar (lambda (choice)
(let ((start 0)
(best 0.0))
(while (string-match search-re choice start)
(let ((last-found (match-beginning 0)))
(setq start (1+ last-found))
(let ((score 1.0)
(i 1)
(choice-pointer nil))
(while (setq choice-pointer (match-beginning i))
(setq i (1+ i))
(setq score (+ score (/ 0.75 (- choice-pointer last-found))))
(setq last-found choice-pointer))
(setq best (max best score)))))
(when (> best 0.0)
(list (* (commandT-max-score-per-char
choice search-string)
best)
choice))))
choices))
#'car-less-than-car)))
Context: I do research on bounded java program verification using z3. I want to get an optimization model on a linearization problem. A standard approach could be incrementally search the model until find a unsat case. But the performance seems be a problem, and it destroys the code portability by introducing JNI, which intergrates z3 c/c++ api to my tool.
Now I want to add constraints on all inputs of a java method. I use quantity arrays (I use theory of array to model heaps). However, z3 always returns "unknown" immediately on a satisfiable problem. It seems that it is impossible to generate model. I notice that there is an option of z3, INST_GEN, then I am trying to understand it. I feed following formulas to z3.
(set-option :INST_GEN true)
(define-sort S () (_ BitVec 2))
(declare-fun s () S)
(assert (= s (_ bv0 2)))
(define-sort A () (Array S S))
(push) ;; 1st case
(assert (forall ((a A)) (= (select a s) s)))
(check-sat)
(get-model)
(pop)
(push) ;; 2nd case
(declare-fun a () A)
(assert (forall ((t S)) (= (select a t) t)))
(check-sat)
(get-model)
(pop)
(push) ;; 3rd case
(check-sat)
(get-model)
(pop)
In both 1st and 2nd cases, z3 returns "segmentation fault" in Linux, while it crashes in windows 7. Both z3 are version 4.0, x64.
In 3rd case, it is quantify-free, and Z3 successfully generates model
sat
(model (define-fun s () (_ BitVec 2) #b00) )
My first question is how this option works? Does it enumerate arrays?
Second question is, I notice that z3 could successfully return "unsat" on a unsatisfied problem with quantify arrays. Does z3 support some option or approach to generate a model in a satisfied problem with quantified arrays, with bounded indices and elements? e.g. using if-then-else clause.
First, the option INST_GEN was part of an experiment. It should not have been exposed to external users. This options was not seriously tested. It will be hidden in future versions. Sorry about that.
Second, in general, Z3 will fail on satisfiable problems that quantify over arrays. The following tutorial (section Quantifiers) describes many fragments where Z3 is complete.
Finally, Z3 has many different engines/solvers. However, only one of them supports incremental solving. Whenever, push/pop commands are used, Z3 will automatically switch to this incremental solver.
If we remove the push and pop commands, then Z3 can show the second problem to be satisfiable.
Here is a link with the modified example: http://rise4fun.com/Z3/apcQ.