setdelayed inside manipulate originates a loop of evaluations. Why? - wolfram-mathematica

Why does this:
Manipulate[test[a_] := 2*b; test[c], {b, 0, 1}, {c, 0, 1}]
turns into an evaluation loop?
Shouldn't Manipulate only evaluate when b or c changes?

To fix the problem with minimal changes, do
Manipulate[
test[a_] := 2*b;
test[c], {b, 0, 1}, {c, 0, 1},
TrackedSymbols \[Rule] {b, c}]
instead (i.e., add TrackedSymbols to tell Mathematica what to track for changes).

Yes, the Manipulate will re-evaluate when b or c changes, but also if test changes -- and test is being re-assigned every time any one of those values changes. Hence the endless re-evaluation loop.
As a rule, side-effects should be avoided in the display expressions of constructs like Manipulate and Dynamic in order to avoid evaluation loops, race conditions and other surprising behaviour. In the case at hand, I would suggest removing the implicit dependency on b in test and hoisting its definition outside of the Manipulate:
test[b_, c_] := 2*b; Manipulate[test[b, c], {b, 0, 1}, {c, 0, 1}]
In the real application, there may be obstacles to such a simple refactoring -- but the key point is to remove the := from the dynamic expression.

Related

Unevaluated form of a[[i]]

Consider following simple, illustrating example
cf = Block[{a, x, degree = 3},
With[{expr = Product[x - a[[i]], {i, degree}]},
Compile[{{x, _Real, 0}, {a, _Real, 1}}, expr]
]
]
This is one of the possible ways to transfer code in the body of a Compile statement. It produces the Part::partd error, since a[[i]] is at the moment of evaluation not a list.
The easy solution is to just ignore this message or turn it off. There are of course other ways around it. For instance one could circumvent the evaluation of a[[i]] by replacing it inside the Compile-body before it is compiled
cf = ReleaseHold[Block[{a, x, degree = 3},
With[{expr = Product[x - a[i], {i, degree}]},
Hold[Compile[{{x, _Real, 0}, {a, _Real, 1}}, expr]] /.
a[i_] :> a[[i]]]
]
]
If the compiled function a large bit of code, the Hold, Release and the replacement at the end goes a bit against my idea of beautiful code. Is there a short and nice solution I have not considered yet?
Answer to the post of Szabolcs
Could you tell me though why you are using With here?
Yes, and it has to do with the reason why I cannot use := here. I use With, to have something like a #define in C, which means a code-replacement at the place I need it. Using := in With delays the evaluation and what the body of Compile sees is not the final piece of code which it is supposed to compile. Therefore,
<< CompiledFunctionTools`
cf = Block[{a, x, degree = 3},
With[{expr := Product[x - a[[i]], {i, degree}]},
Compile[{{x, _Real, 0}, {a, _Real, 1}}, expr]]];
CompilePrint[cf]
shows you, that there is a call to the Mathematica-kernel in the compiled function
I4 = MainEvaluate[ Function[{x, a}, degree][ R0, T(R1)0]]
This is bad because Compile should use only the local variables to calculate the result.
Update
Szabolcs solution works in this case but it leaves the whole expression unevaluated. Let me explain, why it is important that the expression is expanded before it is compiled. I have to admit, my toy-example was not the best. So lets try a better one using With and SetDelayed like in the solution of Szabolcs
Block[{a, x}, With[
{expr := D[Product[x - a[[i]], {i, 3}], x]},
Compile[{{x, _Real, 0}, {a, _Real, 1}}, expr]
]
]
Say I have a polynomial of degree 3 and I need the derivative of it inside the Compile. In the above code I want Mathematica to calculate the derivative for unassigned roots a[[i]] so I can use the formula very often in the compiled code. Looking at the compiled code above
one sees, that the D[..] cannot be compiled as nicely as the Product and stays unevaluated
11 R1 = MainEvaluate[ Hold[D][ R5, R0]]
Therefore, my updated question is: Is it possible to evaluate a piece of code without evaluating the Part[]-accesses in it better/nicer than using
Block[{a, x}, With[
{expr = D[Quiet#Product[x - a[[i]], {i, 3}], x]},
Compile[{{x, _Real, 0}, {a, _Real, 1}}, expr]
]
]
Edit: I put the Quiet to the place it belongs. I had it in front of code block to make it visible to everyone that I used Quiet here to suppress the warning. As Ruebenko pointed already out, it should in real code always be as close as possible to where it belongs. With this approach you probably don't miss other important warnings/errors.
Update 2
Since we're moving away from the original question, we should move this discussion maybe to a new thread. I don't know to whom I should give the best answer-award to my question since we discussed Mathematica and Scoping more than how to suppress the a[[i]] issue.
Update 3
To give the final solution: I simply suppress (unfortunately like I did all the time) the a[[i]] warning with Quiet. In a real example below, I have to use Quiet outside the complete Block to suppress the warning.
To inject the required code into the body of Compile I use a pure function and give the code to inline as argument. This is the same approach Michael Trott is using in, e.g. his Numerics book. This is a bit like the where clause in Haskell, where you define stuff you used afterwards.
newtonC = Function[{degree, f, df, colors},
Compile[{{x0, _Complex, 0}, {a, _Complex, 1}},
Block[{x = x0, xn = 0.0 + 0.0 I, i = 0, maxiter = 256,
eps = 10^(-6.), zeroId = 1, j = 1},
For[i = 0, i < maxiter, ++i,
xn = x - f/(df + eps);
If[Abs[xn - x] < eps,
Break[]
];
x = xn;
];
For[j = 1, j <= degree, ++j,
If[Abs[xn - a[[j]]] < eps*10^2,
zeroId = j + 1;
Break[];
];
];
colors[[zeroId]]*(1 - (i/maxiter)^0.3)*1.5
],
CompilationTarget -> "C", RuntimeAttributes -> {Listable},
RuntimeOptions -> "Speed", Parallelization -> True]]##
(Quiet#Block[{degree = 3, polynomial, a, x},
polynomial = HornerForm[Product[x - a[[i]], {i, degree}]];
{degree, polynomial, HornerForm[D[polynomial, x]],
List ### (ColorData[52, #] & /# Range[degree + 1])}])
And this function is now fast enough to calculate the Newton-fractal of a polynomial where the position of the roots is not fixed. Therefore, we can adjust the roots dynamically.
Feel free to adjust n. Here it runs up to n=756 fluently
(* ImageSize n*n, Complex plange from -b-I*b to b+I*b *)
With[{n = 256, b = 2.0},
DynamicModule[{
roots = RandomReal[{-b, b}, {3, 2}],
raster = Table[x + I y, {y, -b, b, 2 b/n}, {x, -b, b, 2 b/n}]},
LocatorPane[Dynamic[roots],
Dynamic[
Graphics[{Inset[
Image[Reverse#newtonC[raster, Complex ### roots], "Real"],
{-b, -b}, {1, 1}, 2 {b, b}]}, PlotRange -> {{-b, b}, {-
b, b}}, ImageSize -> {n, n}]], {{-b, -b}, {b, b}},
Appearance -> Style["\[Times]", Red, 20]
]
]
]
Teaser:
Ok, here is the very oversimplified version of the code generation framework I am using for various purposes:
ClearAll[symbolToHideQ]
SetAttributes[symbolToHideQ, HoldFirst];
symbolToHideQ[s_Symbol, expandedSymbs_] :=! MemberQ[expandedSymbs, Unevaluated[s]];
ClearAll[globalProperties]
globalProperties[] := {DownValues, SubValues, UpValues (*,OwnValues*)};
ClearAll[getSymbolsToHide];
Options[getSymbolsToHide] = {
Exceptions -> {List, Hold, HoldComplete,
HoldForm, HoldPattern, Blank, BlankSequence, BlankNullSequence,
Optional, Repeated, Verbatim, Pattern, RuleDelayed, Rule, True,
False, Integer, Real, Complex, Alternatives, String,
PatternTest,(*Note- this one is dangerous since it opens a hole
to evaluation leaks. But too good to be ingored *)
Condition, PatternSequence, Except
}
};
getSymbolsToHide[code_Hold, headsToExpand : {___Symbol}, opts : OptionsPattern[]] :=
Join ## Complement[
Cases[{
Flatten[Outer[Compose, globalProperties[], headsToExpand]], code},
s_Symbol /; symbolToHideQ[s, headsToExpand] :> Hold[s],
Infinity,
Heads -> True
],
Hold /# OptionValue[Exceptions]];
ClearAll[makeHidingSymbol]
SetAttributes[makeHidingSymbol, HoldAll];
makeHidingSymbol[s_Symbol] :=
Unique[hidingSymbol(*Unevaluated[s]*) (*,Attributes[s]*)];
ClearAll[makeHidingRules]
makeHidingRules[symbs : Hold[__Symbol]] :=
Thread[List ## Map[HoldPattern, symbs] -> List ## Map[makeHidingSymbol, symbs]];
ClearAll[reverseHidingRules];
reverseHidingRules[rules : {(_Rule | _RuleDelayed) ..}] :=
rules /. (Rule | RuleDelayed)[Verbatim[HoldPattern][lhs_], rhs_] :> (rhs :> lhs);
FrozenCodeEval[code_Hold, headsToEvaluate : {___Symbol}] :=
Module[{symbolsToHide, hidingRules, revHidingRules, result},
symbolsToHide = getSymbolsToHide[code, headsToEvaluate];
hidingRules = makeHidingRules[symbolsToHide];
revHidingRules = reverseHidingRules[hidingRules];
result =
Hold[Evaluate[ReleaseHold[code /. hidingRules]]] /. revHidingRules;
Apply[Remove, revHidingRules[[All, 1]]];
result];
The code works by temporarily hiding most symbols with some dummy ones, and allow certain symbols evaluate. Here is how this would work here:
In[80]:=
FrozenCodeEval[
Hold[Compile[{{x,_Real,0},{a,_Real,1}},D[Product[x-a[[i]],{i,3}],x]]],
{D,Product,Derivative,Plus}
]
Out[80]=
Hold[Compile[{{x,_Real,0},{a,_Real,1}},
(x-a[[1]]) (x-a[[2]])+(x-a[[1]]) (x-a[[3]])+(x-a[[2]]) (x-a[[3]])]]
So, to use it, you have to wrap your code in Hold and indicate which heads you want to evaluate. What remains here is just to apply ReleseHold to it. Note that the above code just illustrates the ideas, but is still quite limited. The full version of my method involves other steps which make it much more powerful but also more complex.
Edit
While the above code is still too limited to accomodate many really interesting cases, here is one additional neat example of what would be rather hard to achieve with the traditional tools of evaluation control:
In[102]:=
FrozenCodeEval[
Hold[f[x_, y_, z_] :=
With[Thread[{a, b, c} = Map[Sqrt, {x, y, z}]],
a + b + c]],
{Thread, Map}]
Out[102]=
Hold[
f[x_, y_, z_] :=
With[{a = Sqrt[x], b = Sqrt[y], c = Sqrt[z]}, a + b + c]]
EDIT -- Big warning!! Injecting code using With or Function into Compile that uses some of Compile's local variables is not reliable! Consider the following:
In[63]:= With[{y=x},Compile[x,y]]
Out[63]= CompiledFunction[{x$},x,-CompiledCode-]
In[64]:= With[{y=x},Compile[{{x,_Real}},y]]
Out[64]= CompiledFunction[{x},x,-CompiledCode-]
Note the renaming of x to x$ in the first case. I recommend you read about localization here and here. (Yes, this is confusing!) We can guess about why this only happens in the first case and not the second, but my point is that this behaviour might not be intended (call it a bug, dark corner or undefined behaviour), so relying on it is fragile ...
Replace-based solutions, like my withRules function do work though (this was not my intended use for that function, but it fits well here ...)
In[65]:= withRules[{y->x},Compile[x,y]]
Out[65]= CompiledFunction[{x},x,-CompiledCode-]
Original answers
You can use := in With, like so:
cf = Block[{a, x, degree = 3},
With[{expr := Product[x - a[[i]], {i, degree}]},
Compile[{{x, _Real, 0}, {a, _Real, 1}}, expr]
]
]
It will avoid evaluating expr and the error from Part.
Generally, = and := work as expected in all of With, Module and Block.
Could you tell me though why you are using With here? (I'm sure you have a good reason, I just can't see it from this simplified example.)
Additional answer
Addressing #halirutan's concern about degree not being inlined during compilation
I see this as exactly the same situation as if we had a global variable defined that we use in Compile. Take for example:
In[18]:= global=1
Out[18]= 1
In[19]:= cf2=Compile[{},1+global]
Out[19]= CompiledFunction[{},1+global,-CompiledCode-]
In[20]:= CompilePrint[cf2]
Out[20]=
No argument
3 Integer registers
Underflow checking off
Overflow checking off
Integer overflow checking on
RuntimeAttributes -> {}
I0 = 1
Result = I2
1 I1 = MainEvaluate[ Function[{}, global][ ]]
2 I2 = I0 + I1
3 Return
This is a common issue. The solution is to tell Compile to inline globals, like so:
cf = Block[{a, x, degree = 3},
With[{expr := Product[x - a[[i]], {i, degree}]},
Compile[{{x, _Real, 0}, {a, _Real, 1}}, expr,
CompilationOptions -> {"InlineExternalDefinitions" -> True}]]];
CompilePrint[cf]
You can check that now there's no callback to the main evaluator.
Alternatively you can inject the value of degree using an extra layer of With instead of Block. This will make you wish for something like this very much.
Macro expansion in Mathematica
This is somewhat unrelated, but you mention in your post that you use With for macro expansion. Here's my first (possibly buggy) go at implementing macro expansion in Mathematica. This is not well tested, feel free to try to break it and post a comment.
Clear[defineMacro, macros, expandMacros]
macros = Hold[];
SetAttributes[defineMacro, HoldAllComplete]
defineMacro[name_Symbol, value_] := (AppendTo[macros, name]; name := value)
SetAttributes[expandMacros, HoldAllComplete]
expandMacros[expr_] := Unevaluated[expr] //. Join ## (OwnValues /# macros)
Description:
macros is a (held) list of all symbols to be expanded.
defineMacro will make a new macro.
expandMacros will expand macro definitions in an expression.
Beware: I didn't implement macro-redefinition, this will not work while expansion is on using $Pre. Also beware of recursive macro definitions and infinite loops.
Usage:
Do macro expansion on all input by defining $Pre:
$Pre = expandMacros;
Define a to have the value 1:
defineMacro[a, 1]
Set a delayed definition for b:
b := a + 1
Note that the definition of b is not fully evaluated, but a is expanded.
?b
Global`b
b:=1+1
Turn off macro expansion ($Pre can be dangerous if there's a bug in my code):
$Pre =.
One way:
cf = Block[{a, x, degree = 3},
With[{expr = Quiet[Product[x - a[[i]], {i, degree}]]},
Compile[{{x, _Real, 0}, {a, _Real, 1}}, expr]]]
be careful though, it you really want this.
Original code:
newtonC = Function[{degree, f, df, colors},
Compile[{{x0, _Complex, 0}, {a, _Complex, 1}},
Block[{x = x0, xn = 0.0 + 0.0 I, i = 0, maxiter = 256,
...
RuntimeOptions -> "Speed", Parallelization -> True]]##
(Quiet#Block[{degree = 3, polynomial, a, x},
polynomial = HornerForm[Product[x - a[[i]], {i, degree}]];
...
Modified code:
newtonC = Function[{degree, f, df, colors},
Compile[{{x0, _Complex, 0}, {a, _Complex, 1}},
Block[{x = x0, xn = 0.0 + 0.0 I, i = 0, maxiter = 256,
...
RuntimeOptions -> "Speed", Parallelization -> True],HoldAllComplete]##
( (( (HoldComplete###)/.a[i_]:>a[[i]] )&)#Block[{degree = 3, polynomial, a, x},
polynomial = HornerForm[Product[x - a[i], {i, degree}]];
...
Add HoldAllComplete attribute to the function.
Write a[i] in place of a[[i]].
Replace Quiet with (( (HoldComplete###)/.a[i_]:>a[[i]] )&)
Produces the identical code, no Quiet, and all of the Hold stuff is in one place.

Evaluation of Expressions inside Manipulate Statements

I have problems getting Manipulate to work with code assigned to variables that should be evaluated inside the Manipulate statement. Here is how it goes ...
test1={a,b,c};
Manipulate[test1,{a,0,10,.1},{b,0,10,.1},{c,0,10,.1}]
So {a, b, c} are not updated. Ok, whatever, let's enforce the evaluation of test1
Manipulate[Evaluate[test1],{a,0,10,.1},{b,0,10,.1},{c,0,10,.1}]
Now it works. But if I want to plot the list of manipulated elements, like this
Manipulate[ListPlot[Evaluate[test1]],{a,0,10,.1},{b,0,10,.1},{c,0,10,.1}]
Manipulate[Evaluate[ListPlot[test1]],{a,0,10,.1},{b,0,10,.1},{c,0,10,.1}]
I end up with
in both chases.
I am aware of 'Evaluate Expressions inside Dynamic or Manipulate' in Mathematica's documentation, but I am pretty sure that it does not provide a solution to my problem.
So the problem is that test1 is defined in terms of global variable Global`a,
but the a defined in the manipulate is created by a DynamicModule and is thus local. This is what acl showed with his Hold[a] example.
Maybe the easiest way to fix this is to use With to insert test1 into the manipulate:
Clear[a, b, c]
test1 = {a, b, c};
With[{test1 = test1},
Manipulate[test1, {a, 0, 10, .1}, {b, 0, 10, .1}, {c, 0, 10, .1}]]
This way the Manipulate never actually sees test1, all it sees is {a,b,c} which it then goes on to correctly localize. Although, this will run into problems if a,b,c have been given a value before the Manipulate is run - thus the Clear[a,b,c] command.
I think that the best practice is to make all local variables completely explicit in the manipulate. So you should do something like
Clear[a, b, c, test1]
test1[a_, b_, c_] := {a, b, c};
Manipulate[test1[a, b, c], {a, 0, 10, .1}, {b, 0, 10, .1}, {c, 0, 10, .1}]
This avoids problems with the global vs local variables that you were having. It also makes it easier for you when you have to come back and read your own code again.
Edit to answer the question in the comments "I really would like to understand why Evaluate does not work with the somewhat nested ListPlot?". IANLS (I am not Leonid Shifrin) and so I don't have a perfect Mathematica (non)standard evaluation sequence running in my brain, but I'll try to explain what's going on.
Ok, so unlike Plot, ListPlot does not need to localize any variables, so it does not have the Attribute HoldAll.
Let's define something similar to your example:
ClearAll[a, test]
test = {a, a + 1};
The final example you gave is like
Manipulate[Evaluate[ListPlot[test]], {a, 0, 1}]
By looking at the Trace, you see that this first evaluates the first argument which is ListPlot[test] ~> ListPlot[{a,a+1}]
and since a is not yet localized, it produces an empty list plot. To see this, simply run
ListPlot[{a, a + 1}]//InputForm
to get the empty graphics object
Graphics[{}, {AspectRatio -> GoldenRatio^(-1), Axes -> True, AxesOrigin -> {0, 0}, PlotRange -> {{0., 0.}, {0., 0.}}, PlotRangeClipping -> True, PlotRangePadding -> {Scaled[0.02], Scaled[0.02]}}]
As the symbolic values a have been thrown out, they can not get localized by the Manipulate and so not much else happens.
This could be fixed by still evaluating the first argument, but not calling ListPlot until after Manipulate has localized the variables. For example, both of the following work
Manipulate[Evaluate[listPlot[test]], {a, 0, 1}] /. listPlot -> ListPlot
Manipulate[Evaluate[Hold[ListPlot][test]], {a, 0, 1}] // ReleaseHold
The fact that ListPlot throws away non-numeric values without even the slightest complaint, is probably a feature, but can lead to some annoyingly hard to track bugs (like the one this question pertains to). Maybe a more consistent (but less useful?) behaviour would be to return an unevaluated ListPlot if the plot values are non-numeric... Or to at least issue a warning that some non-numeric points have been discarded.
The penultimate example you gave is (more?) interesting, it looks like
Manipulate[ListPlot[Evaluate[test]], {a, 0, 1}]
Now since Manipulate has the attribute HoldAll, the first thing it does is wrap the arguments in Hold, so if you look at the Trace, you'll see Hold[ListPlot[Evaluate[test]]] being carried around. The Evaluate is not seen, since as described in the Possible Issues section, "Evaluate works only on the first level, directly inside a held function". This means that test is not evaluated until after the variables have been localized and so they are taken to be the global a and not the local (DynamicModule) a.
It's worth thinking about how the following variations work
ClearAll[a, test, f, g]
SetAttributes[g, HoldAll];
test = {a, a + 1};
Grid[{
{Manipulate[test, {a, 0, 1}], Manipulate[Evaluate[test], {a, 0, 1}]},
{Manipulate[f[test], {a, 0, 1}],
Manipulate[f[Evaluate[test]], {a, 0, 1}]},
{Manipulate[g[test], {a, 0, 1}],
Manipulate[g[Evaluate[test]], {a, 0, 1}]}
}]
Here is why it doesn't work:
Manipulate[
{
Hold[a]
},
{a, 0, 10, .1},
{b, 0, 10, .1},
{c, 0, 10, .1}
]
One may fix this in various ways. One is to simply define test1 with the localized variables, like so:
ClearAll[test1, a, b, c];
Manipulate[
test1 = {a, b, c};
{
test1
},
{a, 0, 10, .1},
{b, 0, 10, .1},
{c, 0, 10, .1}
]
and then eg
ClearAll[test1, a, b, c];
Manipulate[
test1 = {a, b, c};
ListPlot#test1,
{a, 0, 10, .1},
{b, 0, 10, .1},
{c, 0, 10, .1}
]
works.
If you prefer to define test1 globally, this
ClearAll[test1, a, b, c];
test1 = {a, b, c};
Manipulate[
test1,
{a, 0, 10, .1},
{b, 0, 10, .1},
{c, 0, 10, .1},
LocalizeVariables -> False,
TrackedSymbols -> test1
]
works.

Update Manipulate[]'d plots when parameters change

I've been fighting with Mathematica's Manipulate function for the last few days for a project.
I'm working on tweaking assumptions and boundary conditions that go into a physical model. For this, I want to be able to plot different equations and adjust the parameters and have the graphs update on the fly. Manipulate seems to be the perfect tool for the job -- except that I can't get it to work. The plots won't update when the parameters are changed.
Basic example:
a =.;
b =.;
c =.;
func1[x_] := a*x;
func2[x_] := a*x^2 + b*x + c;
funcNamesList := {"Linear", "Quadratic"};
funcList := {func1[x], func2[x]}
Manipulate[
Plot[function, {x, -5, 5}], {function,MapThread[Function[#1 -> #2],
{funcList, funcNamesList}]}, {a, -5, 5}, {b, -5, 5}, {c, -5, 5},
LocalizeVariables -> False
]
I can get, for example, func1 to refresh by clicking func1, adjusting a, and then clickingfunc1 again, but I'm hoping to have it update when I adjust a because the real functions I'm using are rather temperamental with respect to their parameters.
-Because I'll be dealing with long functions that have different parameters, using a list of functions is useful.
EDIT:
In case it produces any ideas for anyone, here are some working examples of the individual components of what I want to do (from the Wolfram documentation):
Plot graphs and have them update when parameters are changed:
Manipulate[
Plot[Sin[a x + b], {x, 0, 6}], {{a, 2, "Multiplier"}, 1, 4},
{{b, 0, "Phase Parameter"}, 0, 10}
]
Note: This breaks when the function is taken outside:
func[x] := Sin[a x + b];
Manipulate[
Plot[func[x], {x, 0, 6}], {{a, 2, "Multiplier"}, 1, 4},
{{b, 0, "Phase Parameter"}, 0, 10}, LocalizeVariables -> False
]
Example of changing the function being plotted:
Manipulate[
Plot[f[x], {x, 0, 2 Pi}], {f, {Sin -> "sine", Cos -> "cosine", Tan -> "tangent"}}
]
Edit 2
Changed func2 from a*x^2 to a*x^2 + b*x + c to reflect the fact that the functions may have different parameters.
Edit 3 Added the tidbit I use to get nice names on the function buttons.
There are two problems that prevent your Manipulate statement from working.
First, while the Manipulate variable a is global due to the LocalizeVariables -> False setting, the Plot variable x is not. x is local to the Plot expression.
The second problem is that Manipulate, by default, assumes TrackedSymbols -> Full. This means that only symbols that explicitly appear in the manipulated expression are tracked. Note that a does not appear in the expression, so it is not tracked.
We can correct both problems thus:
a =.;
function =.;
func1[x_] := a*x;
func2[x_] := a*x^2;
funcList := {func1, func2}
Manipulate[
Plot[function[x], {x, -5, 5}], {function, funcList}, {a, -5, 5},
LocalizeVariables -> False, TrackedSymbols :> {a, function}
]
The changes are:
funcList was changed to {func1, func2}
The Plot expression was changed to function[x], thereby referencing the local x variable.
The Manipulate option TrackedSymbols :> {a, function} was added.
function is initially unset.
I'd do this in a slightly different way:
func1[x_, a_] := a*x;
func2[x_, a_] := a*x^2;
funcList = {func1, func2};
Manipulate[
Plot[Evaluate[function[x, b]],
{x, -5, 5},
PlotLabel \[Rule] funcList
],
{function, funcList},
{b, -5, 5}
]
but this may be unsuitable for what you want. Do your functions have different signatures?
EDIT: I've renamed the parameter to b to make it clearer that is it just a parameter being passed, as opposed to a global variable as you were using it.

problem with using some Functions with LocatorPane Dynamic point

I can't figure out why Mathematica behaves this way, may be someone can see the problem. I am no expert on Dynamics, so I might be overlooking something.
I show the code first and then say what the problem is.
Clear[t, s, n, z];
Grid[{
{LocatorPane[Dynamic[p], Graphics[Circle[{0, 0}, 1], ImageSize -> 200],{{-1, -1}, {1, 1}}]},
{Dynamic[{Print#Date[]; Print[ZTransform[n^2/2^n, n, z]]; p}]}}
]
When running the above, you will see that it keeps looping all the time, since it keeps printing. You will see the print messages come out without doing anything to the LocatorPane or moving the mouse.
But when I changed the function above which is ZTransform, to something else, say Laplace, then the looping stops:
Clear[t, s, n, z];
Grid[{
{LocatorPane[Dynamic[p], Graphics[Circle[{0, 0}, 1], ImageSize -> 200],{{-1, -1}, {1, 1}}]},
{Dynamic[{Print#Date[]; Print[LaplaceTransform[t^4*Sin[t], t, s]]; p}]}}
]
It seems functions related Fourier causes this, since I tried this one also and it had the same problem:
Clear[t, s, n, z,w];
Grid[{
{LocatorPane[Dynamic[p], Graphics[Circle[{0, 0}, 1], ImageSize -> 200],{{-1, -1}, {1, 1}}]},
{Dynamic[{Print#Date[]; Print[FourierSequenceTransform[(1/2)^n UnitStep[n], n, w]]; p}]}}
]
Another way of doing the above is using a Module:
process[p_] := Module[{n, z, t, s, w},
Print[Date[]];
ZTransform[n^2 2^(-n), n, z];
p
]
Grid[{
{LocatorPane[Dynamic[p],
Graphics[Circle[{0, 0}, 1],ImageSize -> 200], {{-1, -1}, {1, 1}}]},
{Dynamic[process[p]]}
}]
And again, same problem, I see the looping again. I have to wrap the call to process[p] above with Dynamics to pass the current value of 'p'.
So, my question is why when I use some functions such as ZTransform, Dynamics continue to update, but some other functions such as Laplace, I do not see this problem.
And what can I do to fix this? I do need to call ZTransform using the updated point 'p' in this example.
This is on version 8.01 on windows.
thanks
EDIT1:
I found something which might help. When I add FinishDynamic[] after the call to ZTransform[], it blocks. But not with another call such as Laplace. This means, according to documenation, that ZTransform generates a Dynamic which has not finished updating. What object is this?
Here is an example:
process[p_] := Module[{n, z},
Print[Date[]];
ZTransform[n^2 2^(-n), n, z]; (*bad*)
FinishDynamic[]; (*BLOCKS*)
p
]
Grid[{
{LocatorPane[Dynamic[p],
Graphics[Circle[{0, 0}, 1],
ImageSize -> 200], {{-1, -1}, {1, 1}}]},
{Dynamic[process[p]]}
}]
Again, changing ZTransform[] to some other call, say Laplace[] does not have this problem.
So, it seems to me that ZTransform[] is generating some Dynamic which never finish updating or something along these lines?
EDIT2:
I found the solution. Add trackedSymbols. Here it is
process[p_] := Module[{n, z},
Print[Date[]];
ZTransform[n^2 2^(-n), n, z];(*bad*)
p]
Grid[{
{LocatorPane[Dynamic[p], Graphics[Circle[{0, 0}, 1],ImageSize -> 200], {{-1, -1}, {1, 1}}]},
{Dynamic[process[p], TrackedSymbols :> {p}]
}
}]
Not sure why it is needed when calling ZTransform and not needed with other functions. My guess is this: ZTransform generated a dynamic internally that never finished 'updating' (that is why it blocked as per EDIT1 above).
By explicitly adding TrackedSymbols only on the LocatorPane variable 'p', it now works since whatever other dynamic was causing the problem inside ZTrasnform is not tracked now.
Have you tried turning off SynchronousUpdating? (see documentation)
I am not entirely sure why some functions are doing this and not others, but it might be that the particular kind of transform you are doing doesn't finish evaluating before the Dynamic tries to update. If so, another thing to try would be to change the value of the SynchronousInitialization option to False (default is True). Then the transform is queued even while the Dynamic or Manipulate construct is updating, instead of (according to the documentation), waiting until the evaluation of the initialization expression is complete before proceeding.

Using the solution of a differential equation in two separate plot commands in Mathematica

I've encountered a problem while trying to use the answer from a NDSolve in two separate plot commands. To illustrate the problem, I'll use a simple differential equation and only one plot command. If I write something like this:
{Plot[x[t], {t, 0, 10}], x[4]}
/. NDSolve[{x'[s] == - x[s], x[0] == 1}, x, {s, 0, 10}]
It solves the equation and calculates x[4] with no problem, but the plot turns empty, and I have no idea why.
In my actual problem, my equation is a quite complicated system for several functions, and instead of x[4] I draw a parametric plot of the solved functions. I ultimately intend to include all this in a Manipulate statement so I don't want the NDSolve statement to appear more than once (takes too long) and I can't just calculate it in advance (since it has a lot of parameters).
Edit: I would like to clarify and expand my question: What I actually want to do is to include my plotting statement in a Manipulate statement in the following way:
Manipulate[{Plot[x[t], {t, 0, 10}], x[4]}
/. NDSolve[{x'[s] == - a*x[s], x[0] == 1}, x, {s, 0, 10}]
,{{a,1},0,5}]
Since only the Manipulate statement gives value to the parameter a, I can't calculate the answer to the NDSolve beforehand. Also, since my actual equation system is very complicated and non-linear, I can't use the symbolic function DSolve.
Sorry if it wasn't clear before.
Your problem is that Plot[] does some funny things to make plotting more convenient, and one of the things it does is just not plot things it can't evaluate numerically. So in the expression you posted,
Plot[x[t], {t, 0, 10}]
just goes ahead and evaluates before doing the rule substitution with the solution from NDSolve, producing a graphics object of an empty plot. That graphics object contains no reference to x, so there's nothing to substitute for.
You want to make sure the substitution is done before the plotting. If you also want to make sure the substitution can be done in multiple places, you want to store the solution into a variable.
sol = NDSolve[{x'[s] == - x[s], x[0] == 1}, x, {s, 0, 10}];
{Plot[Evaluate[x[t] /. sol], {t, 0, 10}], x[4] /. sol}
The Evaluate[] in the Plot makes sure that Mathematica only does the substitution once, instead of once for each plot point. It's not important for a simple rule substitution like this, but it's a good habit to use it in case you ever want to plot something more complicated.
In order to make this work in a Manipulate, the simple way is to use With[], which is one of Mathematica's scoping constructs; it's the one to use where you just want to substitute something in without using it as variable you can mutate.
For example,
Manipulate[
With[{sol = NDSolve[{x'[s] == - x[s], x[0] == 1}, x, {s, 0, 10}]},
{Plot[x[t] /. sol // Evaluate, {t, 0, 10}, PlotRange -> {0, 1}],
x[4] /. sol}],
{{a, 1}, {0, 5}}]
Use the PlotRange option to keep the y-axis fixed; otherwise things will jump around in an ugly way as the value of a changes. When you do more complex things with Manipulate, there are a number of options for controlling the speed of updates, which can be important if your ODE is complicated enough that it takes a while to solve.
Meanwhile, I found another way to do this. It's less elegant, but it only uses one substitution so I've thought I'll post it here also.
The idea is to use Hold on the Plot so it wouldn't get evaluated, do the rule substitution and then ReleaseHold, just before the Manipulate.
Manipulate[ReleaseHold[
Hold[ {Plot[x[t], {t, 0, 10}, PlotRange -> {0, 1}], x[4]} ]
/.NDSolve[{x'[s] == -a x[s], x[0] == 1}, x, {s, 0, 10}]
], {{a, 1}, 0, 5}]

Resources