AutoLISP - Change multiply layers by selecting multiply objects - autolisp

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.

Related

Defining Functor Instance for Tensor Type (Idris)

I've been learning Idris recently, and decided I'd try to write a simple tensor library. I started by defining the type.
data Tensor : Vect n Nat -> Type -> Type
Scalar : a -> Tensor [] a
Dimension : Vect n (Tensor d a) -> Tensor (n::d) a
As you can see, the type Tensor is parameterized by a Vect of Nats describing the tensor's dimensions, and a type, describing its contents. So far so good. Next I decided to try making the Tensor type a Functor.
instance Functor (Tensor d) where
map f (Scalar x) = f x
map f (Dimension x) = map f x
And Idris gave me the following error.
Unifying `b` and `Tensor [] b` would lead to infinite type
Okay. From the error, I figured that maybe the issue was that the first pattern of map was too specific (i.e., would only accept scalars when the type declaration of map is such that it accepts any tensor). That seemed odd, but I figured I'd try rewriting it using a with statement.
dimensions : {d : Vect n Nat} -> Tensor d a -> Vect n Nat
dimensions {d} _ = d
instance Functor (Tensor d) where
map f t with (dimensions t)
map f (Scalar x) | [] = f x
map f (Dimension x) | (_::_) = map f x
But I got the same error. I have quite a bit of experience in Haskell, but I'm still not quite used to the lingo used in dependently typed programming in general and by Idris in particular, so any help understanding the error message would be greatly appreciated.
(Note: from Idris 0.10, the instance keyword is deprecated and should be simply left out).
The task is to apply the function to all elements in the Scalar constructors, but otherwise leave the structure unchanged. So, we need to map Scalar to Scalar and Dimension to Dimension, and since Dimension contains a vector of recursive occurrences, we should use Vect's map to access them.
Functor (Tensor d) where
map f (Scalar x) = Scalar (f x)
map f (Dimension xs) = Dimension (map (map f) xs)
So, in map (map f) xs, the first map is for mapping over Vect, and map f is the recursive call.

Common Lisp best practices to use type declarations for optimization

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

Apply list of values as arguments to a function

Can I apply a list of n values to a function that takes n values, where n varies?
A first naive attempt is the following but the compiler (fairly) complains of a weird self-referential type for applyN
applyN f xs =
case xs of
[] -> f
(x::xs) -> applyN (f x) xs
I can't see how a fold would work and respect its type signature either.
For context, I want to take a list of N Json Decoders and evaluate
Json.objectN ConstructorN n1 n2 ... nN
Clearly if n is known (let's say 2) then we have
case lst of
(d1 :: d2 :: _) -> Json.object2 Constructor2 d1 d2
otherwise -> ....
but that's a lot of code to write if I cannot generalise for n.
I'm fearing it is not possible as in Haskell it needs some special compiler flags.
No, you can not do that, at least not without dependant types or at least some type level trickery, which there is none of in Elm (for reference: How do I define Lisp’s apply in Haskell?)
(This is why there are all the objectN functions by the way.)
Try to restructure your code - can't f just take a list?
In this context of Json decoding, if you have a list literal with decoders, you can do something equivalent to applyN. This pattern uses the functions map: (a -> b) -> Decoder a -> Decoder b and andMap : Decoder (a -> b) -> Decoder a -> Decoder b. You use it like so:
Constructor
`Json.map` n1
`Json.andMap` n2
`Json.andMap` ...
`Json.andMap` nN
Sadly andMap isn't offered for every core module. You can define it yourself if there is a map2 or andThen. In this case object2 works, it's basically the same as map2. So:
andMap : Decoder (a -> b) -> Decoder a -> Decoder b
andMap decFun decA =
object2 (\f a -> f a) decFun decA
You can also use Json.Decode.Extra.apply, which is the same thing, just named in a non-standard way*.
*non-standard within the Elm world anyway

Speed up string matching in emacs

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)))

What is INST_GEN in z3

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.