Evaluate[] seems to not work inside Button[] - wolfram-mathematica

Any idea how to get this to work?
y = {}; Table[Button[x, AppendTo[y, Evaluate[x]]], {x, 5}]
Result: Click [1] , click [2], get {6,6}
I'm trivializing the actual task, but the goal is to set what a button does inside a Map or a Table or ParallelTable.
Please Help!
EDIT
Figured it out... Evaluate works at first level only. Here, it's too deep. So I used ReplaceRule:
Remove[sub]; y = {}; Table[Button[x, AppendTo[y, sub]] /. sub -> x, {x, 5}]

This is a job for With. With is used to insert an evaluated expression into another expression at any depth -- even into parts of the expression that are not evaluated right away like the second argument to Button:
y = {}; Table[With[{x = i}, Button[x, AppendTo[y, x]]], {i, 5}]
In simple cases like this, some people (myself included) prefer to use the same symbol (x in this case) for both the With and Table variables, thus:
y = {}; Table[With[{x = x}, Button[x, AppendTo[y, x]]], {x, 5}]

Replacement rules and pure functions offer concise alternatives to With. For example:
y={}; Range[5] /. x_Integer :> Button[x, AppendTo[y, x]]
or
y = {}; Replace[Range[5], x_ :> Button[x, AppendTo[y, x]], {1}]
or
y = {}; Array[Button[#, AppendTo[y, #]] &, {5}]
or
y = {}; Button[#, AppendTo[y, #]] & /# Range[5]
For another example comparing these techniques, see my post here, where they are applied to a problem of creating a list of pure functions with parameter embedded in their body (closures).

Evaluate works at first level only. Here, it's too deep. So I used ReplaceRule:
Remove[sub]; y = {}; Table[ Button[x, AppendTo[y, sub]] /. sub -> x, {x, 5}]

Related

Syntax to figure out the y value for a particular x value in Mathematica

Here's the problem statement:
Two non-linear inter-dependent, initial value first order differential equations were solved using NDSolve to yield an analytical solution. The solution was used to calculate another parameter, as a function of the same x value.
Let's say we have the ODEs as:
X'[t]=a*S[t]*X[t]/(b+S[t]
S'[t]=-a*S[t]*X[t]/(c(b+S[t])) where a,b,c are also known constants
X[0]=constant
S[0]=constant
soln = NDSolve[{X'[t]=a*S[t]*X[t]/(b+S[t],S'[t]=-a*S[t]*X[t]/(c(b+S[t])),X[0]=constant,S[0]=constant},{X,S},{t,0,50}]
The solution is of the form
X-> InterpolatingFunction[{{0.0,50}},<>],S->InterpolationFunction[{{0.0,50}},<>}}
Now the new parameter is: Yvalue=(S[t]/.soln)+(X[t]/.soln)
I'm trying to figure out the correct syntax to calculate Yvalue for an entered t value.
Ex- One needs to calculate Yvalue at t=0.1,0.56, 2.3 etc
Thank you for your time.
Regards,
Ankur
NDSolve demands that all parameters be given specific numeric values. If you assign values to a,b,c,X[0],S[0] and carefully match up all your parens and carefully use == versus = correctly, then this can work
In[1]:= a = 2; b = 3; c = 5;
soln = NDSolve[{X'[t] == a*S[t]*X[t]/(b + S[t]),
S'[t] == -a*S[t]*X[t]/(c(b+S[t])), X[0]==7, S[0]==11}, {X,S}, {t,0,50}][[1]]
Out[2]= {X -> InterpolatingFunction[{{0.,50.}}, <>],
S -> InterpolatingFunction[{{0.,50.}}, <>]}
In[3]:= Yvalue = S[t] + X[t] /. soln /. t -> 0.1
Out[3]= 18.9506
In[4]:= Yvalue = S[t] + X[t] /. soln /. t -> 0.56
Out[4]= 25.6919
In[5]:= Yvalue = S[t] + X[t] /. soln /. t -> 2.3
Out[5]= 61.9823
and even
In[6]:= Plot[S[t] + X[t] /. soln, {t, 0, 50}, PlotRange -> {0, 70}]
Out[6]= ...PlotSnipped...

Mathematica, nested optimization

I want to use the solution of Maximization, defined as a function, in another function. Here's an example:
f1[y_] := x /. Last[Maximize[{Sin[x y], Abs[x] <= y}, x]] (* or any other function *)
This definition is fine, for example if I give f1[4], I get answer -((3 \[Pi])/8).
The problem is that when I want to use it in another function I get error. For example:
FindRoot[f1[y] == Pi/4, {y, 1}]
Gives me the following error:
ReplaceAll::reps: {x} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>
FindRoot::nlnum: The function value {-0.785398+(x/.x)} is not a list of numbers with dimensions {1} at {y} = {1.}. >>
I've been struggling with this for several days now! Any comment, idea, help, ... is deeply appreciated! Thank you very much!
When y is not a number, your Maximize cannot be resolved, in which case the Last element of it is x, which is why you get that odd error message. You can resolve this by clearing the bad definition of f1 and making a new one that ensures only numeric arguments are evaluated:
ClearAll[f1]
f1[y_?NumericQ] := x /. Last[Maximize[{Sin[x y], Abs[x] <= y}, x]]
FindRoot[f1[y] == \[Pi]/4, {y, 1}]
(* {y -> 0.785398} *)

Creating points while using Mathematica's Table Function

I'm trying to plot points that I've created in a table in mathematica but for some reason one component of my points seems to have double braces around it while the other only has one as below:
{{x},y},{{x1},y1}....{{xn},yn}
and list plot will not recognize these as points and will not plot them.
Here is my mathematica code:
Remove["Global`*"]
b = .1;
w = 1;
Period = 1;
tstep = 2 Pi/Period;
s = NDSolve[{x''[t] + b x'[t] - x[t] + x[t]^3 - .5 Cos[w t] == 0,
x'[0] == 0, x[0] == 0}, x[t], {t, 0, 1000}, MaxSteps -> Infinity];
x[t_] = x[t] /. s
data = Table[Evaluate[{x'[t], .5}], {t, 0, 1000, tstep}]
ListPlot[data]
I've also tried using the command
ListPlot[Flatten[Table[Evaluate[{x'[t], .5}], {t, 0, 1000, tstep}]]]
to no avail as well as
ListPlot[Table[Evaluate[{Flatten[x'[t]], .5}], {t, 0, 1000, tstep}]]]
How can I remove the {}?
You may try something along these lines:
Clear["Global`*"]
b = .1;
w = 1;
s = NDSolve[{x''[t] + b x'[t] - x[t] + x[t]^3 - .5 Cos[w t] == 0,
x'[0] == 0, x[0] == 0}, x[t], {t, 0, 1000}, MaxSteps -> Infinity];
xr[u_] := ((x[t] /. s[[1]]) /. t -> u)
Plot[(xr'[u]), {u, 0, 30}]
But I am not sure what are you trying to get from the {x'[t], .5} part
My colleagues are correct, but I think there is more that can be said. First, to your actual question. The output of NDSolve is a list of the form
{{x[t]->InterpolatingFunction[...]}, {x[t]->InterpolatingFunction[...]}, ...}
where the second and subsequent replacement rules are only there if more than one solution is present. I have never encountered a case using NDSolve where that is true, but it makes the answer consistent with Solve, where multiple solutions is not uncommon. Therefor, with only one solution, you have a double list, i.e.
{{x[t]->InterpolatingFunction[...]}}
As per Mr. Wizard, you can use First, or you can use Part, i.e.
NDSolve[ ... ][[ 1 ]]
which is my preferred method, although it is slightly more difficult to read and may obscure your intent. You should be aware that the InterpolatingFunction that NDSolve returns is a function, and it will accept variables directly. So, the variables on the left hand side of the declarations
x[t_] = x[t] /. s
and from Belisarius
xr[u_] := ((x[t] /. s[[1]]) /. t -> u)
are superfluous at best, and the second one requires the replacement to occur every time xr is used. Instead, you can declare
x = x[t] /. s
and then writing x[t] afterwards will return IntepolatingFunction[t], exactly like you want. Then, as Belisarius points out, you can use it, or its derivative, in Plot directly, instead of first building a table of values and feeding them into ListPlot.
Edit: when I first posted this, I didn't notice a quirk with NDSolve. If you explicitly solve for x[t] not x, then NDSolve returns InterpolatingFunction[...][t], but if you just solve for x you get what I posted. This quirk allows both the OP's and Belisarius's solutions to function, otherwise the replacement shouldn't occur.
It is most likely that x'[t] is returning something of the form {x_i}. Try replacing the data=Table... line with this
data = Table[Evaluate[{First[x'[t]], .5}], {t, 0, 1000, tstep}]
An alternative would be to do
data=data /. {{x_}, y_} :> {x, y};
which uses ReplaceAll (/.) to replace every occurrence of {{x_i},y_i} with {x_i,y_i}
Example:
There are arguably better ways to accomplish what you are doing, but that is not what you asked.
To remove the extra {} recognize this comes from the result of NDSolve, and therefore use:
s = First # NDSolve[{x''[t] + b x'[t] - x[t] + x[t]^3 - .5 Cos[w t] == 0,
x'[0] == 0, x[0] == 0}, x[t], {t, 0, 1000}, MaxSteps -> Infinity];

Using `With` with a list of `Rules` - but without affecting the normal behaviour of `With`

Say I have a list of Rules
rules = {a -> b, c -> d};
which I use throughout a notebook. Then, at one point, it makes sense to want the rules to apply before any other evaluations take place in an expression. Normally if you want something like this you would use
In[2]:= With[{a=b,c=d}, expr[a,b,c,d]]
Out[2]= expr[b, b, d, d]
How can I take rules and insert it into the first argument of With?
Edit
BothSome solutions fail do all that I was looking for - but I should have emphasised this point a little more. See the bold part above.
For example, let's look at
rules = {a -> {1, 2}, c -> 1};
If I use these vaules in With, I get
In[10]:= With[{a={1,2},c=1}, Head/#{a,c}]
Out[10]= {List,Integer}
Some versions of WithRules yield
In[11]:= WithRules[rules, Head/#{a,c}]
Out[11]= {Symbol, Symbol}
(Actually, I didn't notice that Andrew's answer had the Attribute HoldRest - so it works just like I wanted.)
You want to use Hold to build up your With statement. Here is one way; there may be a simpler:
In[1]:= SetAttributes[WithRules, HoldRest]
In[2]:= WithRules[rules_, expr_] :=
With ## Append[Apply[Set, Hold#rules, {2}], Unevaluated[expr]]
Test it out:
In[3]:= f[args___] := Print[{args}]
In[4]:= rules = {a -> b, c -> d};
In[5]:= WithRules[rules, f[a, c]]
During evaluation of In[5]:= {b,d}
(I used Print so that any bug involving me accidentally evaluating expr too early would be made obvious.)
I have been using the following form of WithRules for a long time. Compared to the one posted by Andrew Moylan, it binds sequentially so that you can say e.g. WithRules[{a->b+1, b->2},expr] and get a expanded to 3:
SetAttributes[WithRules, HoldRest]
WithRules[rules_, expr_] := ReleaseHold#Module[{notSet}, Quiet[
With[{args = Reverse[rules /. Rule[a_, b_] -> notSet[a, b]]},
Fold[With[{#2}, #1] &, Hold#expr, args]] /. notSet -> Set,
With::lvw]]
This was also posted as an answer to an unrelated question, and as noted there, it has been discussed (at least) a couple of times on usenet:
A version of With that binds variables sequentially
Add syntax highlighting to own command
HTH
EDIT: Added a ReleaseHold, Hold pair to keep expr unevaluated until the rules have been applied.
One problem with Andrew's solution is that it maps the problem back to With, and that does not accept subscripted variables. So the following generates messages.
WithRules[{Subscript[x, 1] -> 2, Subscript[x, 2] -> 3},
Power[Subscript[x, 1], Subscript[x, 2]]]
Given that With performs syntactic replacement on its body, we can set WithRules alternatively as follows:
ClearAll[WithRules]; SetAttributes[WithRules, HoldRest];
WithRules[r : {(_Rule | _RuleDelayed) ..}, body_] :=
ReleaseHold[Hold[body] /. r]
Then
In[113]:= WithRules[{Subscript[x, 1] -> 2,
Subscript[x, 2] -> 3}, Subscript[x, 1]^Subscript[x, 2]]
Out[113]= 8
Edit: Addressing valid concerns raised by Leonid, the following version would be safe:
ClearAll[WithRules3]; SetAttributes[WithRules3, HoldRest];
WithRules3[r : {(_Rule | _RuleDelayed) ..}, body_] :=
Developer`ReplaceAllUnheld[Unevaluated[body], r]
Then
In[194]:= WithRules3[{Subscript[x, 1] -> 2, Subscript[x, 2] -> 3},
Subscript[x, 1]^Subscript[x, 2]]
Out[194]= 8
In[195]:= WithRules3[{x -> y}, f[y_] :> Function[x, x + y]]
Out[195]= f[y_] :> Function[x, x + y]
Edit 2: Even WithRules3 is not completely equivalent to Andrew's version:
In[206]:= WithRules3[{z -> 2}, f[y_] :> Function[x, x + y + z]]
Out[206]= f[y_] :> Function[x, x + y + z]
In[207]:= WithRules[{z -> 2}, f[y_] :> Function[x, x + y + z]]
Out[207]= f[y$_] :> Function[x$, x$ + y$ + 2]

Mathematica: branch points for real roots of polynomial

I am doing a brute force search for "gradient extremals" on the following example function
fv[{x_, y_}] = ((y - (x/4)^2)^2 + 1/(4 (1 + (x - 1)^2)))/2;
This involves finding the following zeros
gecond = With[{g = D[fv[{x, y}], {{x, y}}], h = D[fv[{x, y}], {{x, y}, 2}]},
g.RotationMatrix[Pi/2].h.g == 0]
Which Reduce happily does for me:
geyvals = y /. Cases[List#ToRules#Reduce[gecond, {x, y}], {y -> _}];
geyvals is the three roots of a cubic polynomial, but the expression is a bit large to put here.
Now to my question: For different values of x, different numbers of these roots are real, and I would like to pick out the values of x where the solutions branch in order to piece together the gradient extremals along the valley floor (of fv). In the present case, since the polynomial is only cubic, I could probably do it by hand -- but I am looking for a simple way of having Mathematica do it for me?
Edit: To clarify: The gradient extremals stuff is just background -- and a simple way to set up a hard problem. I am not so interested in the specific solution to this problem as in a general hand-off way of spotting the branch points for polynomial roots. Have added an answer below with a working approach.
Edit 2: Since it seems that the actual problem is much more fun than root branching: rcollyer suggests using ContourPlot directly on gecond to get the gradient extremals. To make this complete we need to separate valleys and ridges, which is done by looking at the eigenvalue of the Hessian perpendicular to the gradient. Putting a check for "valleynes" in as a RegionFunction we are left with only the valley line:
valleycond = With[{
g = D[fv[{x, y}], {{x, y}}],
h = D[fv[{x, y}], {{x, y}, 2}]},
g.RotationMatrix[Pi/2].h.RotationMatrix[-Pi/2].g >= 0];
gbuf["gevalley"]=ContourPlot[gecond // Evaluate, {x, -2, 4}, {y, -.5, 1.2},
RegionFunction -> Function[{x, y}, Evaluate#valleycond],
PlotPoints -> 41];
Which gives just the valley floor line. Including some contours and the saddle point:
fvSaddlept = {x, y} /. First#Solve[Thread[D[fv[{x, y}], {{x, y}}] == {0, 0}]]
gbuf["contours"] = ContourPlot[fv[{x, y}],
{x, -2, 4}, {y, -.7, 1.5}, PlotRange -> {0, 1/2},
Contours -> fv#fvSaddlept (Range[6]/3 - .01),
PlotPoints -> 41, AspectRatio -> Automatic, ContourShading -> None];
gbuf["saddle"] = Graphics[{Red, Point[fvSaddlept]}];
Show[gbuf /# {"contours", "saddle", "gevalley"}]
We end up with a plot like this:
Not sure if this (belatedly) helps, but it seems you are interested in discriminant points, that is, where both polynomial and derivative (wrt y) vanish. You can solve this system for {x,y} and throw away complex solutions as below.
fv[{x_, y_}] = ((y - (x/4)^2)^2 + 1/(4 (1 + (x - 1)^2)))/2;
gecond = With[{g = D[fv[{x, y}], {{x, y}}],
h = D[fv[{x, y}], {{x, y}, 2}]}, g.RotationMatrix[Pi/2].h.g]
In[14]:= Cases[{x, y} /.
NSolve[{gecond, D[gecond, y]} == 0, {x, y}], {_Real, _Real}]
Out[14]= {{-0.0158768, -15.2464}, {1.05635, -0.963629}, {1.,
0.0625}, {1., 0.0625}}
If you only want to plot the result then use StreamPlot[] on the gradients:
grad = D[fv[{x, y}], {{x, y}}];
StreamPlot[grad, {x, -5, 5}, {y, -5, 5},
RegionFunction -> Function[{x, y}, fv[{x, y}] < 1],
StreamScale -> 1]
You may have to fiddle around with the plot's precision, StreamStyle, and the RegionFunction to get it perfect. Especially useful would be using the solution for the valley floor to seed StreamPoints programmatically.
Updated: see below.
I'd approach this first by visualizing the imaginary parts of the roots:
This tells you three things immediately: 1) the first root is always real, 2) the second two are the conjugate pairs, and 3) there is a small region near zero in which all three are real. Additionally, note that the exclusions only got rid of the singular point at x=0, and we can see why when we zoom in:
We can then use the EvalutionMonitor to generate the list of roots directly:
Map[Module[{f, fcn = #1},
f[x_] := Im[fcn];
Reap[Plot[f[x], {x, 0, 1.5},
Exclusions -> {True, f[x] == 1, f[x] == -1},
EvaluationMonitor :> Sow[{x, f[x]}][[2, 1]] //
SortBy[#, First] &];]
]&, geyvals]
(Note, the Part specification is a little odd, Reap returns a List of what is sown as the second item in a List, so this results in a nested list. Also, Plot doesn't sample the points in a straightforward manner, so SortBy is needed.) There may be a more elegant route to determine where the last two roots become complex, but since their imaginary parts are piecewise continuous, it just seemed easier to brute force it.
Edit: Since you've mentioned that you want an automatic method for generating where some of the roots become complex, I've been exploring what happens when you substitute in y -> p + I q. Now this assumes that x is real, but you've already done that in your solution. Specifically, I do the following
In[1] := poly = g.RotationMatrix[Pi/2].h.g /. {y -> p + I q} // ComplexExpand;
In[2] := {pr,pi} = poly /. Complex[a_, b_] :> a + z b & // CoefficientList[#, z] & //
Simplify[#, {x, p, q} \[Element] Reals]&;
where the second step allows me to isolate the real and imaginary parts of the equation and simplify them independent of each other. Doing this same thing with the generic 2D polynomial, f + d x + a x^2 + e y + 2 c x y + b y^2, but making both x and y complex; I noted that Im[poly] = Im[x] D[poly, Im[x]] + Im[y] D[poly,[y]], and this may hold for your equation, also. By making x real, the imaginary part of poly becomes q times some function of x, p, and q. So, setting q=0 always gives Im[poly] == 0. But, that does not tell us anything new. However, if we
In[3] := qvals = Cases[List#ToRules#RReduce[ pi == 0 && q != 0, {x,p,q}],
{q -> a_}:> a];
we get several formulas for q involving x and p. For some values of x and p, those formulas may be imaginary, and we can use Reduce to determine where Re[qvals] == 0. In other words, we want the "imaginary" part of y to be real and this can be accomplished by allowing q to be zero or purely imaginary. Plotting the region where Re[q]==0 and overlaying the gradient extremal lines via
With[{rngs = Sequence[{x,-2,2},{y,-10,10}]},
Show#{
RegionPlot[Evaluate[Thread[Re[qvals]==0]/.p-> y], rngs],
ContourPlot[g.RotationMatrix[Pi/2].h.g==0,rngs
ContourStyle -> {Darker#Red,Dashed}]}]
gives
which confirms the regions in the first two plots showing the 3 real roots.
Ended up trying myself since the goal really was to do it 'hands off'. I'll leave the question open for a good while to see if anybody finds a better way.
The code below uses bisection to bracket the points where CountRoots changes value. This works for my case (spotting the singularity at x=0 is pure luck):
In[214]:= findRootBranches[Function[x, Evaluate#geyvals[[1, 1]]], {-5, 5}]
Out[214]= {{{-5., -0.0158768}, 1}, {{-0.0158768, -5.96046*10^-9}, 3}, {{0., 0.}, 2}, {{5.96046*10^-9, 1.05635}, 3}, {{1.05635, 5.}, 1}}
Implementation:
Options[findRootBranches] = {
AccuracyGoal -> $MachinePrecision/2,
"SamplePoints" -> 100};
findRootBranches::usage =
"findRootBranches[f,{x0,x1}]: Find the the points in [x0,x1] \
where the number of real roots of a polynomial changes.
Returns list of {<interval>,<root count>} pairs.
f: Real -> Polynomial as pure function, e.g f=Function[x,#^2-x&]." ;
findRootBranches[f_, {xa_, xb_}, OptionsPattern[]] := Module[
{bisect, y, rootCount, acc = 10^-OptionValue[AccuracyGoal]},
rootCount[x_] := {x, CountRoots[f[x][y], y]};
(* Define a ecursive bisector w/ automatic subdivision *)
bisect[{{x1_, n1_}, {x2_, n2_}} /; Abs[x1 - x2] > acc] :=
Module[{x3, n3},
{x3, n3} = rootCount[(x1 + x2)/2];
Which[
n1 == n3, bisect[{{x3, n3}, {x2, n2}}],
n2 == n3, bisect[{{x1, n1}, {x3, n3}}],
True, {bisect[{{x1, n1}, {x3, n3}}],
bisect[{{x3, n3}, {x2, n2}}]}]];
(* Find initial brackets and bisect *)
Module[{xn, samplepoints, brackets},
samplepoints = N#With[{sp = OptionValue["SamplePoints"]},
If[NumberQ[sp], xa + (xb - xa) Range[0, sp]/sp, Union[{xa, xb}, sp]]];
(* Start by counting roots at initial sample points *)
xn = rootCount /# samplepoints;
(* Then, identify and refine the brackets *)
brackets = Flatten[bisect /#
Cases[Partition[xn, 2, 1], {{_, a_}, {_, b_}} /; a != b]];
(* Reinclude the endpoints and partition into same-rootcount segments: *)
With[{allpts = Join[{First#xn},
Flatten[brackets /. bisect -> List, 2], {Last#xn}]},
{#1, Last[#2]} & ### Transpose /# Partition[allpts, 2]
]]]

Resources