Putting equality constraint in z3 - constraints

I am using z3's python API to solve see if a set of constraint is satisfiable or not.
I have the conditions as string and I want to directly pass them to z3 whenever possible, just to save processing time of transcoding it.
If the constraint is an assignment like a = b what is the best way to enter it.
I want something like
str1 = "a = b"
a = BitVec('a', 3)
b = BitVec('b', 3)
s = Solver()
s.push()
s.add(str1)
This program gives error as "True, False or Z3 Boolean expression expected"
Please let me know the best way to do it.

You need to pass Z3 expressions to the majority of the API functions (like Solver.add(expr)), not strings. For your example (z3py link: http://rise4fun.com/Z3Py/iu0 ):
str1 = "a = b"
a = BitVec('a', 3)
b = BitVec('b', 3)
constraint1 = a == b # sets constraint1 to be the z3 expression a == b
s = Solver()
s.push()
# s.add(str1) # error: 'True, False or Z3 Boolean expression expected'
s.add(constraint1)
print constraint1
If you want to pass strings encoded in infix notation (like "a = b"), you should be able to use Python's eval, although this may not work with full generality, so you may have to write a parser, and you cannot use eval on rise4fun due to the sanitizer:
constraint2 = eval(str1)
Here's some more details on using eval: z3python: converting string to expression
If you have strings encoded in the SMT-LIB standard (which uses prefix notation, e.g., "(= a b)"), you can use the parse_smt2_string API function. Here's an example continuing from the above:
cstr1 = "(assert (= a b))"
ds = { 'a' : a, 'b' : b }
constraint3 = parse_smt2_string(cstr1, decls=ds)
print constraint3
prove(constraint1 == constraint3)
Here's the API documentation for parse_smt2_string: http://research.microsoft.com/en-us/um/redmond/projects/z3/z3.html#-parse_smt2_string
See also this related question and answer on using infix for output of Z3 expressions: how to convert z3 expression to infix expression?

Related

How to interpolate multiple variables in a Markdown string in Julia

In the following Julia 1.5 code:
a, b = 4, 5
"a=$(a), b=($b)" # "a=4, b=5"
using Markdown
md"a=$(a), b=($b)" # a=a, b=b
# but...
Markdown.parse("a=$(a), b=($b)") # "a=4, b=5"
It seems that the Markdown macro thinks two $ indicate a math expression. But the parse handles it OK.
Can someone explain this? is there a way to use the md"..." form for this.
It's not obvious in my opinion, but I think $ with a non-space before is interpreted as a closing LaTeX $ if there is one before.
Some suggestions:
If you're OK with spaces around your = sign, then this works:
julia> md"a = $a, b = $b"
a = 4, b = 5
Or you could make it a list:
julia> md"""
- a=$a
- b=$b
"""
• a=4
• b=5

Using invalid character "²" for squared. Extend Julia syntax with custom operators

In my equations we have many expressions with a^2, and so on. I would like to map "²" to ^2, to obtain something like that:
julia> a² == a^2
true
The above is not however a legal code in Julia. Any idea on how could I implement it ?
Here is a sample macro #hoo that does what you requested in a simplified scenario (since the code is long I will start with usage).
julia> x=5
5
julia> #hoo 3x² + 4x³
575
julia> #macroexpand #hoo 2x³+3x²
:(2 * Main.x ^ 3 + 3 * Main.x ^ 2)
Now, let us see the macro code:
const charsdict=Dict(Symbol.(split("¹²³⁴⁵⁶⁷⁸⁹","")) .=> 1:9)
const charsre = Regex("[$(join(String.(keys(charsdict))))]")
function proc_expr(e::Expr)
for i=1:length(e.args)
el = e.args[i]
typeof(el) == Expr && proc_expr(el)
if typeof(el) == Symbol
mm = match(charsre, String(el))
if mm != nothing
a1 = Symbol(String(el)[1:(mm.offset-1)])
a2 = charsdict[Symbol(mm.match)]
e.args[i] = :($a1^$a2)
end
end
end
end
macro hoo(expr)
typeof(expr) != Expr && return expr
proc_expr(expr)
expr
end
Of course it would be quite easy to expand this concept into "pure-math" library for Julia.
I don't think that there is any reasonable way of doing this.
When parsing your input, Julia makes no real difference between the unicode character ² and any other characters you might use in a variable name. Attempting to make this into an operator would be similar to trying to make the suffix square into an operator
julia> asquare == a^2
The a and the ² are not parsed as two separate things, just like the a and the square in asquare would not be.
a^2, on the other hand, is parsed as three separate things. This is because ^ is not a valid character for a variable name and it is therefore parsed as an operator instead.

Tokenizing a letter as an operator

I need to make a language that has variables in it, but it also needs the letter 'd' to be an operand that has a number on the right and maybe a number on the left. I thought that making sure the lexer checks for the letter first would give it precedence, but that doesn't happen and i don't know why.
from ply import lex, yacc
tokens=['INT', 'D', 'PLUS', 'MINUS', 'LPAR', 'RPAR', 'BIGGEST', 'SMALLEST', 'EQ', 'NAME']
t_PLUS = r'\+'
t_MINUS = r'\-'
t_LPAR = r'\('
t_RPAR = r'\)'
t_BIGGEST = r'\!'
t_SMALLEST = r'\#'
t_D = r'[dD]'
t_EQ = r'\='
t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*'
def t_INT(t):
r'[0-9]\d*'
t.value = int(t.value)
return t
def t_newline(t):
r'\n+'
t.lexer.lineno += 1
t_ignore = ' \t'
def t_error(t):
print("Not recognized by the lexer:", t.value)
t.lexer.skip(1)
lexer = lex.lex()
while True:
try: s = input(">> ")
except EOFError: break
lexer.input(s)
while True:
t = lexer.token()
if not t: break
print(t)
If i write:
3d4
it outputs:
LexToken(INT,3,1,0)
LexToken(NAME,'d4',1,1)
and i don't know how to work around it.
Ply does not prioritize token variables by order of appearance; rather, it orders them in decreasing order by length (longest first). So your t_NAME pattern will come before t_D. This is explained in the Ply manual, along with a concrete example of how to handle reserved words (which may not apply in your case).
If I understand correctly, the letter d cannot be an identifier, and neither can d followed by a number. It is not entirely clear to me whether you expect d2e to be a plausible identifier, but for simplicity I'm assuming that the answer is "No", in which case you can easily restrict the t_NAME regular expression by requiring an initial d to be followed by another letter:
t_NAME = '([a-ce-zA-CE-Z_]|[dD][a-zA-Z_])[a-zA-Z0-9_]*'
If you wanted to allow d2e to be a name, then you could go with:
t_NAME = '([a-ce-zA-CE-Z_]|[dD][0-9]*[a-zA-Z_])[a-zA-Z0-9_]*'

Guidance on missing() in R

Suppose a function, G, takes two arguments; a and b: G(a = some number, b = some number).
Now two situations (wondering what commands to use in each case?):
1- if a user puts G(b = some number), will the if(missing(a)){do this} recognize the complete absence of a argument? AND more importantly:
2- if a user puts G(a =, b = some number), still will the if(missing(a)){do this} recognize a = but lack of some number in front of it?
Defining the function as below doesn't throw an error in both the cases:
ch <- function(a=NA,b=NA){ if(is.na(a)) return(b) else( return(a+b)) }
> ch(b=2)
[1] 2
> ch(a=,b=2)
[1] 2

Rewrite recursive BNF rule with iteration

Look at the following recursive BNF rule
(1) X = Xa | b
This produces sentences like
X = b
X = ba
X = baa
X = baaa
...
This can be written as
(2) X = b a*
where the right hand side is not recursive
Now take a look at the following recursive BNF rule
(3) X = { X } | b
This produces sentences like
X = b
X = {b}
X = {{b}}
X = {{{b}}}
...
Is there some way to rewrite rule (3) in a non recursive way, analogous as we did when we rewrote rule (1) to rule (2).
Observe that X = {* b }* is no good since the parenthesis need to be balanced.
I do not know if the question above is possible to answer. The reason for the question above was that I wanted to avoid infinite loop in my parser (written in Java). One way was to insure that the BNF rules are not recursive, hence my question. But another way is to use the recursive rule, but avoid the infinite loop inside my (Java) program. Turns out that you can avoid loops by lazy instantiation.
For instance look at the following rules:
expression = term ('+' term)*;
term = factor ('*' factor)*;
factor = '(' expression ')' | Num;
expression() calls term(), which calls factor(), which calls expression(), thus we can end up with infinite loop. To avoid that we can use lazy instantiation, so instead of writing something like:
public Parser expression() {
expression = new ...
return expression;
}
we instead write:
public Parser expression() {
if (expression == null) {
expression = new ...
}
return expression;
}
Observe that you must declare expression as an instance variable to get this to work.

Resources