I have the following system I'm trying to solve:
assume(x>0);
solve([x^2 = 3], x);
I expected that the answer would be [x=sqrt(3)], but maxima also gives the negative solution [x=-sqrt(3),x=sqrt(3)]. Is it possible to specify that the domain of x here is all positive real numbers?
This seems to work for me, (not yet tested in other cases):
assume(x>0)$
sublist(
solve(x^2=3,x),
lambda(
[point],
facts: subst(point, facts(initial)),
every(lambda([fact], is(fact)), facts)
)
);
Related
I want to use a symbolic expression as a MathematicalProgram constraint but am unsure how to achieve this. My best go so far is the following (simplified example):
x = Variable("x")
expression = x**2
prog = MathematicalProgram()
v = prog.NewContinuousVariables(1)
prog.AddConstraint(
lambda a: Evaluate(np.array([expression]), {x: a[0].value()}),
lb=np.array([0.0]),
ub=np.array([0.0]),
vars=v,
)
result = Solve(prog)
I'm getting the error PyFunctionConstraint: Output must be of scalar type AutoDiffXd. Got float instead.. Using lambda a: Evaluate(np.array([expression]), {x: a[0]}) does not work due to incompatible function arguments.
I'd highly appreciate any help with this.
I don't think we currently support adding symbolic::Expression as constraint in pydrake yet. On the other hand, we do support ExpressionConstraint in C++ version of Drake.
May I ask why you would like to impose the constraint using symbolic Expression? It is generally much faster to evaluate the constraint, if pass a function directly, something like this
def foo(x):
return np.array([x[0] **2])
prog.AddConstraint(foo, np.array([0.]), np.array([0.]), vars=v)
#Hongkai Dai's answer with the ExpressionConstraint in C++ led me in the right direction. There is such a constraint in pydrake (see here). However, it currently does not support array inputs. The second required insight was that it is possible to use prog.NewContinuousVariables in symbolic expression operations (e.g. Jacobian).
Using these insights, I solved my problem with something similar to the following:
prog = MathematicalProgram()
x = prog.NewContinuousVariables(2)
expression = x[0]**2
J = expression.Jacobian([x[0]])
for i in range(2):
prog.AddConstraint(J[i], 0.0, 0.0)
result = Solve(prog)
In Maxima, I am trying to simplify the expression
sqrt(1 - sin(x)) * sqrt(1 + sin(x))
to yield
cos(x)
I properly restricted the definition of x
declare(x, real) $
assume(x > 0, x < %pi/2) $
and tried several simplification commands including radcan, trigsimp, trigreduce and trigexpand, but without any success. How can this be done?
Try trigsimp(rootscontract(expr))
The restrictions you assert do not uniquely determine the simplified result you request.
It would seem both harmless and obviously unnecessary to declare or assume the following:
declare(9, real)
assume(9>0)
and yet, sqrt(9) is still the set {-3, +3}, mathematically speaking, as opposed to "what I learned in 6th grade".
Stavros' suggestion give |cos(x)|, which is not quite what the original questioner wanted.
Another way of getting the same result, one which may more explicitly exhibit the -in general falseness - of the result, is to square and then use the semi-bogus sqrt, that attempts to pick the positive answer.
trigsimp (sqrt(expand(expr^2)));
If you think this is a way of simplifying expr, note that it changes -3 to 3.
I want to find the range of valid values that a variable can have, given some constraints. Eg,
x = Int('x')
s = Solver()
s.add(x >= 1)
s.add(x < 5+2)
Is there some way that I can get z3 to print 1..6 for this variable?
I tried using the following, but range() applies only to declarations.
print("x.range():", x.range()) # this does not work
Note: 1. This question seems to ask the same, but I did not understand its answers, and I am looking for python answer.
in reply to #Malte: I am not looking for all the answers, I just want to simplify multiple constraints in to a valid range. If constraints on both sides of the variable cannot be merged, then at least only on one side as is mentioned in above mentioned question.
This question comes up occasionally, and the answer isn't very trivial, unfortunately. It really depends on what your constraints are and exactly what you are trying to do. See:
Is it possible to get a legit range info when using a SMT constraint with Z3
And
(Sub)optimal way to get a legit range info when using a SMT constraint with Z3
Essentially, the problem is too difficult (and I'd say not even well defined) if you have multiple variables. If you have exactly one variable, you can use the optimizer to some extent, assuming the variable is indeed bounded. In case you have multiple variables, one idea might be to fix all but one to satisfying constants, and compute the range of that last variable based on the constant assignment to the others. But again, it depends on what you're really trying to achieve.
Please take a look at the above two answers and see if it helps you. If not, please show us what you tried: Stack-overflow works the best when you post some code and see how it can be improved/fixed.
As a SAT/SMT solver, Z3 "only" needs to find a single model (satisfying assignment) to show that a formula is satisfiable. Finding all models is therefore not directly supported.
The question comes up regularly, though, and the solution is to repeatedly find and then block (assume in negated form) models until no further model can be found. For example, for your snippet of code:
x = Int('x')
s = Solver()
s.add(x >= 1)
s.add(x < 5+2)
result = s.check()
while result == sat:
m = s.model()
print("Model: ", m)
v_x = m.eval(x, model_completion=True)
s.add(x != v_x)
result = s.check()
print(result, "--> no further models")
Executing the script yields the solution you asked for, albeit in a less concise form:
Model: [x = 1]
Model: [x = 2]
Model: [x = 3]
Model: [x = 4]
Model: [x = 5]
Model: [x = 6]
unsat --> no further models
In general,
you would have iterate over all variables (here: just x)
model completion is necessary for variables whose value doesn't affect satisfiability; since any value will do, they won't be explicit in the model
Related questions whose answers provide additional details:
(Z3Py) checking all solutions for equation
Why Z3Py does not provide all possible solutions
Getting all solutions of a boolean expression in Z3Py never ends
I have a fairly large expression that involves a lot of subexpressions of the form (100*A^3 + 200*A^2 + 100*A)*x or (-A^2 - A)*y or (100*A^2 + 100*A)*z
I know, but I don't know how to tell Maxima this, that it in this case is valid to make the approximation A+1 ~ A, thereby effectively removing anything but the highest power of A in each coefficient.
I'm now looking for functions, tools, or methods that I can use to guide Maxima in dropping various terms that aren't important.
I have attempted with subst, but that requires me to specify each and every factor separately, because:
subst([A+1=B], (A+2)*(A+1)*2);
subst([A+1=B], (A+2)*(A*2+2));
(%o1) 2*(A+2)*B
(%o2) (A+2)*(2*A+2)
(that is, I need to add one expression for each slightly different variant)
I tried with ratsimp, but that's too eager to change every occurrence:
ratsubst(B, A+1, A*(A+1)*2);
ratsubst(B, A+1, A*(A*2+2));
(%o3) 2*B^2-2*B
(%o4) 2*B^2-2*B
which isn't actually simpler, as I would have preferred the answer to have been given as 2*B^2.
In another answer, (https://stackoverflow.com/a/22695050/5999883) the functions let and letsimp were suggested for the task of substituting values, but I fail to get them to really do anything:
x:(A+1)*A;
let ( A+1, B );
letsimp(x);
(x)A*(A+1)
(%o6) A+1 --\> B
(%o7) A^2+A
Again, I'd like to approximate this expression to A^2 (B^2, whatever it's called).
I understand that this is, in general, a hard problem (is e.g. A^2 + 10^8*A still okay to approximate as A^2?) but I think that what I'm looking for is a function or method of calculation that would be a little bit smarter than subst and can recognize that the same substitution could be done in the expression A^2+A as in the expression 100*A^2+100*A or -A^2-A instead of making me create a list of three (or twenty) individual substitutions when calling subst. The "nice" part of the full expression that I'm working on is that each of these A factors are of the form k*A^n*(A+1)^m for various small integers n, m, so I never actually end up with the degenerate case mentioned above.
(I was briefly thinking of re-expressing my expression as a polynomial in A, but this will not work as the only valid approximation of the expression (A^3+A^2+A)*x + y is A^3*x + y -- I know nothing about the relative sizes of x and y.
Can I ask Z3 to search from certain starting values to satisfy the constraints ?
Say, If I have two RealExprs x and y, and I have x==y as the constraint.
Can I ask Z3 to search from x=-9999, y=-9997 such that Z3 might return to me a model with x=-9998 and y=-9998 and say "SAT" ?
As far as I understand your question, you are kind of looking for a solution to a maximisation/minimisation problem, namely, of the following function
f(x, y) = |x + 9999| + |y + 9997|
together with the constraint x = y. As stated in the answers to this question, Z3 currently doesn't support this directly. However, as also stated, you can try to solve such problems by querying Z3 inside a Python loop that adds previously found solutions as new constraints of the next query.