How to store punch of equations / constants to solve for any element equation or numerical value - algorithm

Lets say, that problems are fairly simple - something, that pre-degree theoretical physics student would solve. And student does the hardest part of the task - functional reading: parsing linguistically free form text, to get input and output variables and input variable values.
For example: a problem about kinematic equations, where there are variables {a,d,t,va,vf} and few functions that describe, how thy are dependent of each-other. So using skills acquired in playing fitting blocks where thy fit, you play with the equations to get the output variable you where looking for.
In any case, there are exactly 2 possible outputs you might want and thy are (with working example):
1) Equation for that variable
Physics[have_, find_] := Solve[Flatten[{
d == vf * t - (a * t^2) /2, (* etc. *)
have }], find]
Physics[True, {d}]
{{d -> (1/2)*(2*t*vf - a*t^2)}}
2) Exact or general numerical value for that variable
Physics[have_, find_] := Solve[Flatten[{
d == vf * t - (a * t^2) /2, (* etc. *)
have }], find]
Physics[{t == 9.7, vf == -104.98, a == -9.8}, {d}]
{{d->-557.265}}
I am not sure, that I am approaching the problem correctly.

I think that I would probably prefer an approach like
In[1]:= Physics[find_, have_:{}] := Solve[
{d == vf*t - (a*t^2)/2 (* , etc *)} /. have, find]
In[2]:= Physics[d]
Out[2]= {{d -> 1/2 (-a t^2 + 2 t vf)}}
In[2]:= Physics[d, {t -> 9.7, vf -> -104.98, a -> -9.8}]
Out[2]= {{d -> -557.265}}
Where the have variables are given as a list of replacement rules.
As an aside, in these types of physics problems, a nice thing to do is define your physical constants like
N[g] = -9.8;
which produces a NValues for g. Then
N[tf] = 9.7;N[vf] = -104.98;
Physics[d, {t -> tf, vf -> vf, a -> g}]
%//N
produces
{{d->1/2 (-g tf^2+2 tf vf)}}
{{d->-557.265}}

Let me show some advanges of Simon's approach:

You are at least approaching this problem reasonably. I see a fine general purpose function and I see you're getting results, which is what matters primarily. There is no 'correct' solution, since there might be a large range of acceptable solutions. In some scenario's some solutions may be preferred over others, for instance because of performance, while that might be the other way around in other scenarios.
The only slight problem I have with your example is the dubious parametername 'have'.
Why do you think this would be a wrong approach?

Related

Combine boolean and integer logic in linear arithmetic using the Z3 Solver?

I would like to solve problems combining boolean and integer logic in linear arithmetic with a SAT/SMT solver. At first glance, Z3 seems promising.
First of all, is it at all possible to solve the following problem? This answer makes it seem like it works.
int x,y,z
boolean a,b,c
( (3x + y - 2z >= 10) OR (A AND (NOT B OR C)) OR ((A == C) AND (x + y >= 5)) )
If so, how does Z3 solve this kind of problem in theory and is there any documentation about it?
I could think of two ways to solve this problem. One would be to convert the Boolean operations into a linear integer expression. Another solution I read about is to use the Nelson-Oppen Combination Method described in [Kro 08].
I found a corresponding documentation in chapter 3.2.2. Solving Arithmetical Fragments, Table 1 a listing of the implemented algorithms for a certain logic.
Yes, SMT solvers are quite good at solving problems of this sort. Your problem can be expressed using z3's Python interface like this:
from z3 import *
x, y, z = Ints('x y z')
A, B, C = Bools('A B C')
solve (Or(3*x + y - 2*z >= 10
, And(A, Or(Not(B), C))
, And(A == C, x + y >= 5)))
This prints:
[A = True, z = 3, y = 0, B = True, C = True, x = 5]
giving you a (not necessarily "the") model that satisfies your constraints.
SMT solvers can deal with integers, machine words (i.e., bit-vectors), reals, along with many other data types, and there are efficient procedures for combinations of linear-integer-arithmetic, booleans, uninterpreted-functions, bit-vectors amongst many others.
See http://smtlib.cs.uiowa.edu for many resources on SMT solving, including references to other work. Any given solver (i.e., z3, yices, cvc etc.) will be a collection of various algorithms, heuristics and tactics. It's hard to compare them directly as each shine in their own way for certain sublogics, but for the base set of linear-integer arithmetic, booleans, and bit-vectors, they should all perform fairly well. Looks like you already found some good references, so you can do further reading as necessary; though for most end users it's neither necessary nor that important to know how an SMT solver internally works.

How do you interpret negative levels in Mathematica?

I am trying to gain a deeper understanding of how Mathematica expressions are represented internally, and am puzzled by the logic of the Level command in Mathematica. If we have the following input:
In[1]:= a = z*Sin[x + y] + z1*Cos[x1 + y1]
Out[1]= z1 Cos[x1 + y1] + z Sin[x + y]
In[2]:= FullForm[a]
Out[2]= Plus[Times[z1,Cos[Plus[x1,y1]]],Times[z,Sin[Plus[x,y]]]]
In[3]:= TreeForm[a]
We get the following tree:
If we ask Mathematica to return Level 4 only, we get:
In[4]:= Level[a,{4}]
Out[4]= {x1,y1,x,y}
I understand that we are 4 levels down from the "stem" (the Plus operator at Level 0). In fact, I think I understand that positive indexes are always in relation to the stem position of the tree. (I hope I'm correct about that??)
In contrast, when you ask for a negative level, there is no common reference point (like the stem above), because different branches of the tree are of varying lengths. So, if you ask Mathematica to provide only Level -1, we get:
In[6]:= Level[a,{-1}]
Out[6]= {z1,x1,y1,z,x,y}
I was surprised by this output, when I had guessed that I should get back {x1, y1, x, y} (without z1 & z). But ok, if I try to understand this, I take -1 to mean "the end of each branch". If this is so, then I would expect Level[a,{-2}] to return:
{z1*Cos[x1+y1],z*Sin[x+y],x1+y1,x+y}
But, this is not what I get back, Mathematica yields:
In[8]:= Level[a,{-2}]
Out[8]= {x1+y1,x+y}
So, now I am confused, and don't see a consistent way of understanding the output of negative levels.
Is there a consistent, easier way of understanding this topic? Is there a certain "correct" way I should be reading the structure of the tree?
Sorry for the "long-winded question", but I hope you understand what I am asking.
If you look at the docs, they say:
A negative level -n consists of all parts of expr with depth n.
So negative levels are not counted from a reference point, but are defined based on the depth of subexpressions. z1*Cos[x1+y1] is of depth 4, so it's not returned when you ask for Level[..., {-2}].

Complex Error Function in Mathematica

The complex error function w(z) is defined as e^(-x^2) erfc(-ix). The problem with using w(z) as defined above is that the erfc tends to explode out for larger x (complemented by the exponential going to 0 so everything stays small), so that Mathematica reverts to arbitrary precision calculations that make life VERY slow. The function is used in implementing the voigt profile - a line shape commonly used in spectroscopy and other related areas. Right now I'm reverting to calculating the lineshape once and using an interpolation to speed things up, however this doesn't let me alter the parameters of the lineshape (or fit to them) easily.
scipy has a nice and fast implementation of w(z) as scipy.special.wofz, and I was wondering if there is an equivalent in Mathematica.
The complex error function can be written in terms of the Hermite "polynomial" H_{-1}(x):
In[1]:= FullSimplify[2 HermiteH[-1,I x] == Sqrt[Pi] Exp[-x^2] Erfc[I x]]
Out[1]= True
And the evaluation does not suffer as many underflows and overflows
In[68]:= 2 HermiteH[-1, I x] /. x -> 100000.
Out[68]= 6.12323*10^-22 - 0.00001 I
In[69]:= Sqrt[Pi] E^-x^2 Erfc[I x] /. x -> 100000.
During evaluation of In[69]:= General::unfl: Underflow occurred in computation. >>
During evaluation of In[69]:= General::ovfl: Overflow occurred in computation. >>
Out[69]= Indeterminate
That said, some quick tests show that the evaluation speed of the Hermite function to be slower than that of the product of the exponential and error function...
A series expansion at infinity shows that the real and imaginary parts are of very different scales. I'd suggest computing them separately and not adding them. Below I use the first few terms of the series expansion to get the imaginary part.
In[186]:=
w[x_?NumericQ] := {N[Exp[-SetPrecision[x, 25]^2], 20],
N[(3 /(4 Sqrt[\[Pi]] x^5) + 1/(2 Sqrt[\[Pi]] x^3) + 1/(
Sqrt[\[Pi]] x))]}
In[187]:= w[11]
Out[187]= {2.8207700884601354011*10^-53, 0.05150453151309212}
In[188]:= w[1000]
Out[188]= {3.296831478088558579*10^-434295, 0.0005641898656429712}
Not sure how badly you want that very small real part. If you can drop it that will keep the numbers in a reasonable range. In some ranges (or if higher than machine precision is desired) you may want to use more terms from the expansion on that imaginary part.
Daniel Lichtblau
Wolfram Research
The real and imaginary parts of the complex error function on the real line can be explicitly and efficiently computed in Mathematica using Dawson integral:
In[9]:= Sqrt[Pi] Exp[-x^2] Erfc[I x] ==
E^-x^2 Sqrt[\[Pi]] - 2 I DawsonF[x] // FullSimplify
Out[9]= True
This is about 4 times faster than using HermiteH[-1,z].
In[10]:= w1[x_] := E^-x^2 Sqrt[\[Pi]] - 2 I DawsonF[x]
w2[x_] := 2 HermiteH[-1, I x]
In[15]:= AbsoluteTiming[w1 /# Range[-5.0, 5.0, 0.001];]
Out[15]= {2.3272327, Null}
In[16]:= AbsoluteTiming[w2 /# Range[-5.0, 5.0, 0.001];]
Out[16]= {10.2400239, Null}
A program in language C for the complex error function (aka the Faddeeva function) that can be run from Mathematica is also available in RooFit. Read the article by Karbach et al. arXiv:1407.0748 for more information.
Just wrap the C library libcerf.

Problem performing a substitution in a multiple derivative

I have a basic problem in Mathematica which has puzzled me for a while. I want to take the m'th derivative of x*Exp[t*x], then evaluate this at x=0. But the following does not work correct. Please share your thoughts.
D[x*Exp[t*x], {x, m}] /. x -> 0
Also what does the error mean
General::ivar: 0 is not a valid variable.
Edit: my previous example (D[Exp[t*x], {x, m}] /. x -> 0) was trivial. So I made it harder. :)
My question is: how to force it to do the derivative evaluation first, then do substitution.
As pointed out by others, (in general) Mathematica does not know how to take the derivative an arbitrary number of times, even if you specify that number is a positive integer.
This means that the D[expr,{x,m}] command remains unevaluated and then when you set x->0, it's now trying to take the derivative with respect to a constant, which yields the error message.
In general, what you want is the m'th derivative of the function evaluated at zero.
This can be written as
Derivative[m][Function[x,x Exp[t x]]][0]
or
Derivative[m][# Exp[t #]&][0]
You then get the table of coefficients
In[2]:= Table[%, {m, 1, 10}]
Out[2]= {1, 2 t, 3 t^2, 4 t^3, 5 t^4, 6 t^5, 7 t^6, 8 t^7, 9 t^8, 10 t^9}
But a little more thought shows that you really just want the m'th term in the series, so SeriesCoefficient does what you want:
In[3]:= SeriesCoefficient[x*Exp[t*x], {x, 0, m}]
Out[3]= Piecewise[{{t^(-1 + m)/(-1 + m)!, m >= 1}}, 0]
The final output is the general form of the m'th derivative. The PieceWise is not really necessary, since the expression actually holds for all non-negative integers.
Thanks to your update, it's clear what's happening here. Mathematica doesn't actually calculate the derivative; you then replace x with 0, and it ends up looking at this:
D[Exp[t*0],{0,m}]
which obviously is going to run into problems, since 0 isn't a variable.
I'll assume that you want the mth partial derivative of that function w.r.t. x. The t variable suggests that it might be a second independent variable.
It's easy enough to do without Mathematica: D[Exp[t*x], {x, m}] = t^m Exp[t*x]
And if you evaluate the limit as x approaches zero, you get t^m, since lim(Exp[t*x]) = 1. Right?
Update: Let's try it for x*exp(t*x)
the mth partial derivative w.r.t. x is easily had from Wolfram Alpha:
t^(m-1)*exp(t*x)(t*x + m)
So if x = 0 you get m*t^(m-1).
Q.E.D.
Let's see what is happening with a little more detail:
When you write:
D[Sin[x], {x, 1}]
you get an expression in with x in it
Cos[x]
That is because the x in the {x,1} part matches the x in the Sin[x] part, and so Mma understands that you want to make the derivative for that symbol.
But this x, does NOT act as a Block variable for that statement, isolating its meaning from any other x you have in your program, so it enables the chain rule. For example:
In[85]:= z=x^2;
D[Sin[z],{x,1}]
Out[86]= 2 x Cos[x^2]
See? That's perfect! But there is a price.
The price is that the symbols inside the derivative get evaluated as the derivative is taken, and that is spoiling your code.
Of course there are a lot of tricks to get around this. Some have already been mentioned. From my point of view, one clear way to undertand what is happening is:
f[x_] := x*Exp[t*x];
g[y_, m_] := D[f[x], {x, m}] /. x -> y;
{g[p, 2], g[0, 1]}
Out:
{2 E^(p t) t + E^(p t) p t^2, 1}
HTH!

Targeted Simplify in Mathematica

I generate very long and complex analytic expressions of the general form:
(...something not so complex...)(...ditto...)(...ditto...)...lots...
When I try to use Simplify, Mathematica grinds to a halt, I am assuming due to the fact that it tries to expand the brackets and or simplify across different brackets. The brackets, while containing long expressions, are easily simplified by Mathematica on their own. Is there some way I can limit the scope of Simplify to a single bracket at a time?
Edit: Some additional info and progress.
So using the advice from you guys I have now started using something in the vein of
In[1]:= trouble = Log[(x + I y) (x - I y) + Sqrt[(a + I b) (a - I b)]];
In[2]:= Replace[trouble, form_ /; (Head[form] == Times) :> Simplify[form],{3}]
Out[2]= Log[Sqrt[a^2 + b^2] + (x - I y) (x + I y)]
Changing Times to an appropriate head like Plus or Power makes it possible to target the simplification quite accurately. The problem / question that remains, though, is the following: Simplify will still descend deeper than the level specified to Replace, e.g.
In[3]:= Replace[trouble, form_ /; (Head[form] == Plus) :> Simplify[form], {1}]
Out[3]= Log[Sqrt[a^2 + b^2] + x^2 + y^2]
simplifies the square root as well.
My plan was to iteratively use Replace from the bottom up one level at a time, but this clearly will result in vast amount of repeated work by Simplify and ultimately result in the exact same bogging down of Mathematica I experienced in the outset. Is there a way to restrict Simplify to a certain level(s)?
I realize that this sort of restriction may not produce optimal results, but the idea here is getting something that is "good enough".
There are a number of ways you can do this, but it can be a little tricky and depends on the structure of your actual expression. However, usually a product of a number of terms in brackets will have the head Times, and you can use FullForm to verify this:
In[1]:= FullForm[(a+b)(c+d)]
Out[1]= Times[Plus[a, b], Plus[c, d]]
You can use the higher-order function Map with expressions with head Times the same way you use it with expressions with head List, and that may allow you to Simplify the expression one term at a time, like so:
Map[Simplify, yourGinormousExpression]
You can use Expand on the result if you need to subsequently expand out the brackets.
EDIT to add: If you want to specify the forms that you do want to simplify, you can use Replace or ReplaceAll instead of one of the relatives of Map. Replace is particularly useful because it takes a level specification, allowing you to only affect the factors in the topmost product. As a simple example, consider the following:
In[1]:= expr = Sqrt[(a + 1)/a] Sqrt[(b + 1)/b];
In[2]:= Simplify[expr]
Out[2]= Sqrt[1 + 1/a] Sqrt[1 + 1/b]
If you don't want to simplify factors that depend on a. you can do this instead:
In[3]:= Replace[expr, form_ /; FreeQ[form, a] :> Simplify[form], {1}]
Out[3]= Sqrt[(1 + a)/a] Sqrt[1 + 1/b]
Only the second term, which depends on b, has been changed. One thing to bear in mind though is that some transformations are done automatically by Times or Plus; for instance a + a will be turned into 2 a even without use of Simplify.
I beg to differ with my colleagues, in that using Map to apply Simplify to each subexpression may not save any time as it will still be applied to each one. Instead try, MapAt, as follows:
In[1]:= MapAt[f, SomeHead[a,b,c,d], {4}]
Out[1]:= SomeHead[a, b, c, f[d]]
The tricky part is determining the position specification. Although, if the expression you want to simplify is at the first level, it shouldn't be any more difficult then what I've written above.
Now if you would still like to simplify everything, but you wish to preserve some structure, try using the option ExcludedForms. In the past, I've used to prevent this simplification:
In[2]:= Simplify[d Exp[I (a + b)] Cos[c/2]]
Out[2]:= Exp[I(a + b + c)](d + d Exp[c])
which Mathematica seems to like, so I do
In[3]:= Simplify[d Exp[I (a + b)] Cos[c/2], ExcludedForms -> {_Cos,_Sin}]
Out[3]:= d Exp[I (a + b)] Cos[c/2]
Also, don't forget that the second parameter for Simplify is for assumptions, and can greatly ease your struggles in getting your expressions into a useful form.
You should try Map.
In general, Map[foo, G[a, b, c, ...]] gives G[foo[a], foo[b], foo[c], ...] for any head G and any expression foo, so for
Map[Simplify, a b c d e]
it gives
Simplify[a] Simplify[b] Simplify[c] Simplify[d] Simplify[e]
Note you can denote Map[foo, expr] als foo /# expr if you find that more convenient.

Resources