source_id
int64
1
4.64M
question
stringlengths
0
28.4k
response
stringlengths
0
28.8k
metadata
dict
15,605
I have a linear differential operator, for instance, $L\left (\partial _{t} \right )=\partial _{tt} - 3\partial _{t} + 2$. I use it in 2 different ways: apply the operator to a function: $L\left (\partial _{t} \right )\sin(t)=-\sin(t)-3\cos(t)+2\sin(t)=\sin(t)-3\cos(t)$ find roots of the polynomial $L(p)=0$, in this case $p=1,p=2$ What is the best way to define such operator?
Define the operator as op[t_]=(D[#,{t,2}]-3D[#,t]+2#)& Then you get op[t][Sin[t]] (* -3 Cos[t]+Sin[t] *) and also op[t][Exp[p t]]/Exp[p t]//Factor (* (-2+p) (-1+p) *) where I have used that $\partial_t \exp(p t) = p\exp(p t)$ to "convert" the action of the operator $\partial_t$ into multiplication by $p$, and then I tidy up by dividing out the $\exp(p t)$ afterwards.
{ "source": [ "https://mathematica.stackexchange.com/questions/15605", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/4745/" ] }
15,607
I know you can hit F1 to pop up the documentation center, and then type the name of a function and search for it. I'd like to know if there's a key that just pops up the help page of the function the cursor is in right now. For instance, when writing Integrate[ , sometimes I forget the right syntax for it, so I just want to immediately see the help page for it without having to manually search for it.
Define the operator as op[t_]=(D[#,{t,2}]-3D[#,t]+2#)& Then you get op[t][Sin[t]] (* -3 Cos[t]+Sin[t] *) and also op[t][Exp[p t]]/Exp[p t]//Factor (* (-2+p) (-1+p) *) where I have used that $\partial_t \exp(p t) = p\exp(p t)$ to "convert" the action of the operator $\partial_t$ into multiplication by $p$, and then I tidy up by dividing out the $\exp(p t)$ afterwards.
{ "source": [ "https://mathematica.stackexchange.com/questions/15607", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/4788/" ] }
15,637
I have the function: $F(\omega) = \frac{5\; - \;i\;\omega}{5^2\; +\; \omega^2}$ When $\omega$ has the values : $\{ -7, -2,\; 0,\; 2,\; 7\}$ How would I plot the Argand diagram in Mathematica? Or should I just treat it as a normal plot? The graph should look like a circle with radius $\frac{1}{10}$ passing through the points specified.
Defining the function F and a subset of its domain : pts : F[z_] := (5 - I z)/(5^2 + z^2) pts = {-7, -2, 0, 2, 7}; the most straightforward way fulfilling the task is based on ParametricPlot and Epilog . We can also make a diagram with the basic graphics primitives like e.g. : Line , Circle , Point . Here are the both ways enclosed in GraphicsRow : GraphicsRow[{ Graphics[{Line[{{0, -0.1}, {0, 0.1}}], Line[{{0, 0}, {0.21, 0}}], Blue, Thick, Circle[{0.1, 0}, 0.1], Red, PointSize[.03], Point[{Re @ #, Im @ #} & /@ F[pts]]}], ParametricPlot[{Re @ #, Im @ #}& @ F[z], {z, -200, 200}, PlotRange -> All, PlotStyle -> Thick, Epilog -> { Red, PointSize[0.03], Point[{Re @ F @ #, Im @ F @ #} & /@ pts]}] }] Studying properties of holomorphic complex mappings is really rewarding, therefore one should take a closer look at it. This function has a simple pole in 5 I : Residue[ F[z], {z, 5 I}] -I and it is conformal in its domain : Reduce[ D[ F[z], z] == 0, z] False i.e. it preserves angles locally. One can easily recognize the type of F evaluating Simplify[ F[z]] , namely it is a composition of a translation, rescaling and inversion. We should look at images (via F ) of simple geometric objects. To visualize the structure of the mapping F we choose an appropriate grid in the complex domain of F and look at its image. We take a continuous parameter $t$ varying in a range $(-25, 25)$ and contours $\;t+ i\;y $ for $y$ in a discrete set of values $\{-3, -2,-1, 0, 1, 2, 3 \}$ and another orthogonal contours $\;x+ i\;t$ for $x$ in a discrete set $\{-7,-5,-3, -2, 0, 2, 3, 5, 5\;\}$, i.e.we have a grid of straight lines in the complex plane. Next we'd like to plot the image of this grid through the mapping $F$. Images of every line in the grid will be circles with centers on the abscissa and ordinate respectively intersecting orthogonally. The red points denote values of $F(x)$ on the complex plane for $x$ in $\{-7, -2, 0, 2, 7 \}$. On the lhs we have the original grid in the domain of F and on the rhs we have the plot of its image : Animate[ GraphicsRow[ ParametricPlot[ ##, Evaluated -> True, PlotStyle -> Thick] & @@@ { { Join @@ {Table[{t, k}, {k, -3, 3}], Table[{k, t}, {k, {-7, -5, -3, -2, 0, 2, 3, 5, 7}}]}, {t, -25, a}, PlotRange -> {{-30, 30}, {-30, 30}}, Epilog -> {Red, PointSize[0.015], Point[{#, 0} & /@ pts]} }, { Join @@ {Table[{Re @ F[t + I k], Im @ F[t + I k]}, {k, -3, 3}], Table[{Re @ F[k + I t], Im @ F[k + I t]}, {k, {-7, -5, -3, -2, 0, 2, 3, 5, 7}}]}, {t, -25, a}, PlotRange -> {{-.4, .6}, {-.51, .51}}, Epilog -> { Red, PointSize[0.015], Point[{Re @ F[#], Im @ F[#]} & /@ pts]}}}, ImageSize -> 800 ], {a, -25 + 0.1, 25}] and slightly modyfing the ranges of the last ParametricPlot : {t, -300, 300} , and PlotRange -> {{-.2, .3}, {-.25, .25}} : ParametricPlot[ Join @@ { Table[{Re @ F[t + I k], Im @ F[t + I k]}, {k, -3, 3}], Table[{Re @ F[k + I t], Im @ F[k + I t]}, {k, {-7, -5, -3, -2, 0, 2, 3, 5, 7}}]}, {t, -300, 300}, PlotRange -> {{-.2, .3}, {-.25, .25}}, Epilog -> {Red, PointSize[0.015], Point[{Re @ #, Im @ #} & /@ F @ pts]}, Evaluated -> True, PlotStyle -> Thick]
{ "source": [ "https://mathematica.stackexchange.com/questions/15637", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/4375/" ] }
15,718
I'd like to define a function with several optional arguments, some of which default to the value supplied for other arguments. For example, I'd like to be able to write something like f[x_, y_: 0, z_: y] := {x, y, z} and have {f[1, 2], f[1]} produce {{1, 2, 2}, {1, 0, 0}} Instead I get {{1, 2, y}, {1, 0, y}} Can I make a default for an optional argument the value of another argument? If not, what's the best approach for accomplishing this?
You can't easily do this with optional arguments (but see Leonid's answer for a work around), but you can use the fact that you can have multiple definitions for a given function: f[x_, y_:0] := {x, y, y} f[x_, y_, z_] := {x, y, z} will do what you want. For further use of this style you could also do this as: f[x_] := {x, 0, 0} f[x_, y_] := {x, y, y} f[x_, y_, z_] := {x, y, z} which makes the "pattern" of your function even more explicit
{ "source": [ "https://mathematica.stackexchange.com/questions/15718", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/37/" ] }
15,884
I need to typeset large number of equations to be used for PlotLabel and Titles and such. These have to look nice. Hence I use TraditionalForm with HoldForm and this works well, except for a tiny little annoying thing. This below is just an example: TraditionalForm[HoldForm[(v/w) Sin[w t]]] displays as $\frac{v \ \sin(t)}{w}$ and not as $\frac{v}{w} \sin(t)$. In otherwords, the Sin[x] was put in the numerator as well, where I'd like it to remain on its own as was typed. I used () above as a hint to leave Sin[] alone, but this hint did nothing. An easy fix is to use HoldForm around each small sub-expression as follows TraditionalForm[Row[{HoldForm[(v/w)], HoldForm[Sin[w t]]}]] which now generates $\frac{v}{w} \sin(t)$ But the above is a small example. I have much larger equations, and would be nice if I could tell Mathematica when I type it, using () or another trick, to please not group these subexpression as it did in the above example (I'd like the equations to look exactly as they appear in the text book. It is not a big issue really to use HoldForm many times to force the shape to look exactly as I wanted, but just thought to check if someone knows an easier way to do this other than what I have shown. I just had a thought! is it possible to use $\LaTeX$ directly to typeset things in Mathematica for purpose of display? i.e. it would be nice if one can write something like Text["$\frac{v}{w} \sin(t)$"] and have Mathematica interpret this as $\LaTeX$, and typeset it as $\LaTeX$ output. If possible, I can just write everything in $\LaTeX$ as strings, and problems solved. What I mean by the above is as follows (only to help explain the point): In MATLAB I can do this: text(.5,.5,'$\frac{v}{w} \sin(t)$','interpreter','latex','FontSize',18) which generates Notice I had to tell MATLAB to use the $\LaTeX$ interpreter. But that is all. It will be really nice to be able to do something like this in Mathematica if possible. Using String s also avoids many other problems when typesetting symbolic expressions in Mathematica since a string is inert and a raw Symbol and can't have value other than itself. Thanks.
I'll treat this question as being mainly about annotating graphics using LaTeX syntax. For that purpose, here is a template that you could use: Plot[Sin[x], {x, 0, 2 Pi}, Epilog -> Text[Style[ ToExpression["\\sin\\alpha", TeXForm, HoldForm], Large], {Pi, .5}]] However, there are several caveats because the ability of Mathematica to interpret $\LaTeX$ is limited. I'm copying this in slightly edited form from a list of issues that I had lying around on my web site : Note that all backslashes should be doubled because a single \ counts as an escape character. In the above code, the argument HoldForm (or alternatively Hold if you want to do calculations later) prevents evaluation so that it is possible to display everything without re-arranging the order. The $\LaTeX$ conversion will throw an error if Mathematica thinks the expression has incorrect syntax. So you won't always be able to get literal translations of arbitrary $\LaTeX$ fragments. Spaces are completely ignored by Mathematica , even in products of variables such as $z = x y$. The Mathematica expression will become z = xy which incorrectly references a single variable with a two-letter name xy . You have to explicitly insert thin spaces (" \\, ") in the string argument of ToExpression wherever you want an implicit multiplication to appear. Note that $\LaTeX$ ignores spaces too, but it defaults to defining each letter as a separate variable in the above expression. Mathematica simply uses the wrong default assumption here. Spaces between digits as in 3.1 103 are also ignored, so this example would be translated as 3.1103 . As above, you have to force Mathematica to recognize spaces, or use a multiplication operator such as \times in your $\LaTeX$ code. To translate integrals properly, Mathematica expects the integration variable in the $\LaTeX$ code to be preceded by \\, d . Only with the additional space will it recognize the d as the differential part of the integral. Express derivatives using the \partial symbol: ToExpression["\\frac{\\partial^2 f(x)}{\\partial x^2}", TeXForm, HoldForm] All matrices and vectors must be written in list form using escaped curly brackets, as in \{x,y,f (z)\} because the conversion of array environments or commands such as \pmatrix to Mathematica produces wrong formatting. To group expressions , use only round parentheses, i.e., \left( and \right) , not square [...] or curly {...} brackets. The latter are interpreted differently by Mathematica . Do not use Mathematica 's built-in symbols as names for variables in your $\LaTeX$ code. They can lead to syntax errors or will be replaced by different-looking output forms. An example is ToExpression["E = mc^2", TeXForm, HoldForm] where the output contains $\mathbb{e}$ instead of $E$. Finally, when Mathematica fails to translate from $\LaTeX$, create a snippet of the MMA code that you think should be generated. Put this into TeXForm. From the result, you can often guess the required $\LaTeX$ form that will work in reverse as an input to ToExpression . If this is close to what you wanted, maybe you can edit the title of the question to include $\LaTeX$.
{ "source": [ "https://mathematica.stackexchange.com/questions/15884", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/70/" ] }
15,898
I am finding Pythagorean_triple , it worked slowly. I tried to compile, but it gives some warnings. I also use "Case" or "Do" ,both of them failed.I'm sure my CCompiler has been set correctly. How can I compile the following code? With[{m = 200}, Select[Flatten[Table[{x, y, z}, {x, m}, {y, x, m}, {z, y, m}], 2], (#1^2 + #2^2 == #3^2 &) @@ # &] ]
There are much faster ways to generate Pythagorean triples. Update: Now twice as fast . genPTunder[lim_Integer?Positive] := Module[{prim}, prim = Join @@ Table[ If[CoprimeQ[m, n], {2 m n, m^2 - n^2, m^2 + n^2}, ## &[]], {m, 2, Floor @ Sqrt @ lim}, {n, 1 + m ~Mod~ 2, m, 2} ]; Union @@ (Range[lim ~Quotient~ Max@#] ~KroneckerProduct~ {Sort@#} & /@ prim) ] genPTunder[50] {{3, 4, 5}, {5, 12, 13}, {6, 8, 10}, {7, 24, 25}, {8, 15, 17}, {9, 12, 15}, {9, 40, 41}, {10, 24, 26}, {12, 16, 20}, {12, 35, 37}, {14, 48, 50}, {15, 20, 25}, {15, 36, 39}, {16, 30, 34}, {18, 24, 30}, {20, 21, 29}, {21, 28, 35}, {24, 32, 40}, {27, 36, 45}, {30, 40, 50}} genPTunder[100000] // Length // Timing {0.125, 161436} Over 160,000 triples in an eighth of a second should be serviceable, even without compilation.
{ "source": [ "https://mathematica.stackexchange.com/questions/15898", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/2090/" ] }
15,920
I want $\left\{\frac{1}{1+\sqrt{2}-\sqrt{3}},\sqrt{5-2 \sqrt{6}},\sqrt{4+\sqrt{15}}\right\}$ to be simplified to $\left\{\frac{1}{4} \left(2+\sqrt{2}+\sqrt{6}\right), \sqrt{3}-\sqrt{2}, \frac{1}{2} \left(\sqrt{6}+\sqrt{10}\right)\right\}$ But I haven't been able to get that result with Mathematica. How could I get it?
There is a literature on denesting radicals. Not really my strength. In cases where you know (or suspect) the specific radicals that should appear in the result you can use a Groebner basis computation to recast your algebraic value via a minimal polynomial. Then factor over the extension defined by those radicals, solve, and pick the solution that is numerically correct (the others being algebraic conjugates). I illustrate with that first example. rootpoly = GroebnerBasis[{x*xrecip - 1, xrecip - (1 + y - z), y^2 - 2, z^2 - 3}, x, {xrecip, y, z}][[1]] (* -1 + 4*x + 4*x^2 - 16*x^3 + 8*x^4 *) fax = Select[FactorList[rootpoly, Extension -> {Sqrt[2], Sqrt[3]}][[All, 1]], ! FreeQ[#, x] &] (* {2 + Sqrt[2] + Sqrt[6] - 4*x, -2 - Sqrt[2] + Sqrt[6] + 4*x, 2 - Sqrt[2] + Sqrt[6] - 4*x, -2 + Sqrt[2] + Sqrt[6] + 4*x} *) candidates = Flatten[Map[x /. Solve[# == 0, x] &, fax]]; First[Select[candidates, (N[#] == 1/(1 + Sqrt[2] - Sqrt[3])) &]] (* (1/4)*(2 + Sqrt[2] + Sqrt[6]) *) If you are more familiar with manipulating algebraic numbers than you are with Groebner bases, here is a better way to get that defining polynomial. RootReduce[1/(1 + Sqrt[2] - Sqrt[3])][[1]][x] (* Out[35]= -1 + 4 x + 4 x^2 - 16 x^3 + 8 x^4 *) --- edit --- I will show this in a way that is more automated, in terms of deciding what to use in the extension for factoring. The idea is to allow roots of all factors of all integers that appear in the nested radical. val = Sqrt[4 + Sqrt[15]]; rootpoly = RootReduce[val][[1]][x] (* 1 - 8 x^2 + x^4 *) ints = Flatten[Map[FactorInteger, Cases[val, _Integer, -1]][[All, All, 1]]] (* {2, 3, 5} *) fax = Select[FactorList[rootpoly, Extension -> Sqrt[ints]][[All, 1]], ! FreeQ[#, x] &] (* {Sqrt[6] + Sqrt[10] - 2 x, Sqrt[6] - Sqrt[10] + 2 x, Sqrt[6] - Sqrt[10] - 2 x, Sqrt[6] + Sqrt[10] + 2 x} *) candidates = Flatten[Map[x /. Solve[# == 0, x] &, fax]]; First[Select[candidates, (N[#] == val) &]] (* 1/2 (Sqrt[6] + Sqrt[10] *) --- end edit ---
{ "source": [ "https://mathematica.stackexchange.com/questions/15920", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/2090/" ] }
15,985
I've been trying to find some kind of mathematical computer software to solve the Travelling Salesman Problem. The Excel Solver is able to do it, but I've noticed there is a built-in function in Mathematica : TravelingSalesman[g] finds an optimal traveling salesman tour in graph g. I've been given a matrix which represents the costs of traveling between six cities. I could start typing them in to the Graph function and then use the TravelingSalesman function to solve it. But I'm too lazy for such work. Is there a way to type in the matrix, convert it to some kind of graph, and then apply the TravelingSalesman function directly to the graph? Hope you understand my question! Thanks in advance.
True traveling salesman problem FindShortestTour is the function you are looking for. This defines a sparse distance matrix among six points and finds the shortest tour: d = SparseArray[{{1, 2} -> 1, {2, 1} -> 1, {6, 1} -> 1, {6, 2} -> 1, {5, 1} -> 1, {1, 5} -> 1, {2, 6} -> 1, {2, 3} -> 10, {3, 2} -> 10, {3, 5} -> 1, {5, 3} -> 1, {3, 4} -> 1, {4, 3} -> 1, {4, 5} -> 15, {4, 1} -> 1, {5, 4} -> 15, {5, 2} -> 1, {1, 4} -> 1, {2, 5} -> 1, {1, 6} -> 1}, {6, 6}, Infinity]; {len, tour} = FindShortestTour[{1, 2, 3, 4, 5, 6}, DistanceFunction -> (d[[#1, #2]] &)] {6, {1, 4, 3, 5, 2, 6}} This plots the shortest tour in red, and the distance on each edge: HighlightGraph[ WeightedAdjacencyGraph[d, GraphStyle -> "SmallNetwork", EdgeLabels -> "EdgeWeight"], Style[UndirectedEdge[#1, #2], Thickness[.01], Red] & @@@ Partition[tour, 2, 1, 1]] Some other experiments with graphs Another interesting thing to look at is ( FindPostmanTour function ), but below method is also interesting. Sample matrix of cost quantities (distances, times, expenses, etc.) between the cities: m = RandomReal[1, {10, 10}]; (m[[#, #]] = Infinity) & /@ Range[10]; m // MatrixForm Matrix should be of course symmetric, but DirectedEdges -> False below takes care of it. A default embedding would of course give a complete graph: g = WeightedAdjacencyGraph[m, DirectedEdges -> False, VertexLabels -> "Name"] While weighted embedding results in edges length reflecting upon distances: g = WeightedAdjacencyGraph[m, DirectedEdges -> False, GraphLayout -> {"SpringElectricalEmbedding", "EdgeWeighted" -> True}, VertexLabels -> "Name"] Now get vertex coordinates, find shortest tour: p = GraphEmbedding[g] {{1.28207, 1.43548}, {0.63296, 0.7209}, {1.01456, 0.812491}, {1.27993,0.}, {1.16843, 1.46467}, {0.0713373, 1.23935}, {1.29842, 1.4204}, {0., 1.22425}, {0.167924, 0.587497}, {0.643434, 1.17666}} st = FindShortestTour[p] {5.02343, {1, 5, 10, 6, 8, 9, 2, 4, 3, 7}} Show[g, Graphics[{Red, Thick, Line[p[[Last[st]]]]}]] Just shortest path (not through all cities) Lets choose a test weighted matrix: m = {{\[Infinity], 1, 7, \[Infinity]}, {1, \[Infinity], 2, 5}, {7, 2, \[Infinity], 1}, {\[Infinity], 5, 1, \[Infinity]}}; m // MatrixForm Infinity means no edge between vertices. This builds the graph: g = WeightedAdjacencyGraph[m, EdgeLabels -> "EdgeWeight", GraphStyle -> "SmallNetwork"] Find shortest path between vertices 1 and 4 and visualize: sp = FindShortestPath[g, 1, 4] {1, 2, 3, 4} HighlightGraph[g, PathGraph[sp]] which is obviously correct. Known positions of the cities If you know locations or names of the cities, then take a look at this . A short example traveling through the centro-ids of countries in Europe: Graphics[{EdgeForm[White], Gray, CountryData[#, "Polygon"] & /@ CountryData["Europe"], Thick, Red, Line[#[[Last[FindShortestTour[#]]]] & [Reverse[CountryData[#, "CenterCoordinates"]] & /@ CountryData["Europe"]]]}]
{ "source": [ "https://mathematica.stackexchange.com/questions/15985", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/4815/" ] }
16,108
I am not sure how to find out what all is included as curated data. For example, are the individual images of each of the 52 cards in a standard deck of playing cards included? If not, is there a way to systematically access these from web images?
You can get some nice vector playing cards from this site , licensed under GNU LGPL (read more here ). Download this folder to your computer and then try the following: (* replace with your download dir *) files = Flatten@With[{dir = "~/Downloads/Chrome/mma/SVG_and_EPS_Vector_Playing_Cards_Version_1.3/EPS_Vector_Playing_Cards_Version_1.3/52-Individual-Vector-Playing-Cards-1.2_(EPS-Format)/"}, FileNames["*.eps", dir, 2]]; Clear@CardData SetAttributes[CardData, Listable] StringCases[Last@FileNameSplit@#, card__ ~~ ".eps" :> (CardData[card] = ImageCrop@Import@#)] & /@ files; You can then use this like any other curated data: GraphicsRow[CardData@{"2C", "KH", "AS", "QD", "JC"}] Random hand generator: You can extend this further and also create a random hand generator using Mathematica as follows: deck = Flatten@With[ { ranks = CharacterRange["2", "9"] ~Join~ {"10", "J", "Q", "K", "A"}, suits = {"C", "S", "H", "D"} }, Outer[StringJoin, ranks, suits] ]; dealHand[n_Integer] /; 1 ≤ n ≤ 52 := CardData@RandomSample[deck, n] Use this to deal a hand as dealHand[5] , for instance. You'll have to modify this a bit to deal randomly and exhaust the deck at the same time (as you would in a game). There was a question on this previously on this site and I gave an answer based on Internal`Bag[] that will be useful here (along with some of the other answers there).
{ "source": [ "https://mathematica.stackexchange.com/questions/16108", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1629/" ] }
16,115
Possible Duplicate: List-operations only when restrictions are fulfilled (Part 1) I have a set of data like: list = {{Tim, 45},{Mary,100},{Tim,500},{Bob,499},{Mary,50}}; I'm looking for a simple way to total the values based off of the name so that the output would look like: {{Tim,545},{Mary,150},{Bob,499}}
You can get some nice vector playing cards from this site , licensed under GNU LGPL (read more here ). Download this folder to your computer and then try the following: (* replace with your download dir *) files = Flatten@With[{dir = "~/Downloads/Chrome/mma/SVG_and_EPS_Vector_Playing_Cards_Version_1.3/EPS_Vector_Playing_Cards_Version_1.3/52-Individual-Vector-Playing-Cards-1.2_(EPS-Format)/"}, FileNames["*.eps", dir, 2]]; Clear@CardData SetAttributes[CardData, Listable] StringCases[Last@FileNameSplit@#, card__ ~~ ".eps" :> (CardData[card] = ImageCrop@Import@#)] & /@ files; You can then use this like any other curated data: GraphicsRow[CardData@{"2C", "KH", "AS", "QD", "JC"}] Random hand generator: You can extend this further and also create a random hand generator using Mathematica as follows: deck = Flatten@With[ { ranks = CharacterRange["2", "9"] ~Join~ {"10", "J", "Q", "K", "A"}, suits = {"C", "S", "H", "D"} }, Outer[StringJoin, ranks, suits] ]; dealHand[n_Integer] /; 1 ≤ n ≤ 52 := CardData@RandomSample[deck, n] Use this to deal a hand as dealHand[5] , for instance. You'll have to modify this a bit to deal randomly and exhaust the deck at the same time (as you would in a game). There was a question on this previously on this site and I gave an answer based on Internal`Bag[] that will be useful here (along with some of the other answers there).
{ "source": [ "https://mathematica.stackexchange.com/questions/16115", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/4981/" ] }
16,262
When plotting two curves on one plot, you can specify different colors for each function: Plot[{Sin@x, Cos@x}, {x, 0, 4π}, PlotStyle -> {Red, Blue}] To plot the curves using different ColorFunction s, you can manually combine the plots: Show[ Plot[Sin@x, {x, 0, 4 \[Pi]}, ColorFunction -> ({x, y} \[Function] Opacity[y, Red])], Plot[Cos@x, {x, 0, 4 \[Pi]}, ColorFunction -> ({x, y} \[Function] Opacity[y, Blue])] ] But if you try to combine them into one Plot[] expression, it doesn't work: Plot[{Sin@x, Cos@x}, {x, 0, 4 \[Pi]}, ColorFunction -> {({x, y} \[Function] Opacity[y, Red]), ({x, y} \[Function] Opacity[y, Blue])}] How can you easily plot multiple curves, specifying the ColorFunction to use for each?
To my knowledge, as soon as you specify a ColorFunction , every point {x,y} no matter to which function it belongs is colorized by the same function. If you want to achieve this behavior without modifying built-in functions, you could use the UpValues of an arbitrary symbol, for instance MultiColorFunction . With this, you specify how a plot-command has to be divided into several calls which are then combined with Show . Luckily, we have to do this only once for all plot-commands (I use here only Plot and Plot3D ) MultiColorFunction /: (h : (Plot | Plot3D))[{fs__}, before___, MultiColorFunction[cf__], after___] := Show[h[#1, before, ColorFunction -> #2, after] & @@@ Transpose[{{fs}, {cf}}]] Now you can simply call Plot[{Sin@x, Cos@x}, {x, 0, 4 \[Pi]}, MultiColorFunction["Rainbow", "Pastel"], PlotStyle -> Thick] and it works similar for Plot3D Plot3D[{Sin[x y], Cos[x]}, {x, 0, 3}, {y, 0, 3}, MultiColorFunction[Function[{x, y, z}, RGBColor[x, y, 0.]], "Pastel"]] Further notes Someone might say that when this works, why don't we use TagSet to make it possible to input this as e.g. Plot[{Sin@x, Cos@x}, {x, 0, 4 \[Pi]}, MultiColorFunction -> {"Rainbow", "Pastel"}] without actually defining a new option MultiColorFunction . The reason is simple, TagSet only works when the symbol we want to set is in the outer two levels. Therefore, while this g /: f[g[h[x]]] := "blub" works, this h /: f[g[h[x]]] := "blub" is not possible. Our Plot construct would have the form Plot[....,Rule[MultiColorFunction,...],..] so it would be equivalent to h of the example. There is of course an alternative. The last reachable level is the one of Rule but we don't want to change a built-in function. But what, if we don't use the normal Rule but a symbol which only looks like a rule-arrow? Let's try it. A quick check brings up \[RightArrow] which has no built-in meaning and looks perfect. Do you see the difference? You can input this arrow with Esc Space - > Esc and it gets automatically transformed into RightArrow[x,y] . RightArrow /: (h : (Plot | Plot3D))[{fs__}, before___, RightArrow[ColorFunction, {cf__}], after___] := Show[h[#1, before, ColorFunction -> #2, after] & @@@ Transpose[{{fs}, {cf}}]] Plot[{Sin@x, Cos@x}, {x, 0, 4 \[Pi]}, ColorFunction\[RightArrow]{"Rainbow", "Pastel"}, PlotStyle ->Thick]
{ "source": [ "https://mathematica.stackexchange.com/questions/16262", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1285/" ] }
16,324
Possible Duplicate: How can I get exactly 5 logarithmic divisions of an interval? I want to use Table to generate a list of items, but want the indices to be logarithmically spaced. Is there a simple way of doing this, or will I have to explicitly run linearly spaced indices through Exp to get my list?
Here's a somewhat simpler way: logspace[a_, b_, n_] := 10.0^Range[a, b, (b - a)/(n - 1)] This gives a sequence starting at 10^a and ending at 10^b , with n points logarithmically spaced, as does MATLAB's logspace() function.
{ "source": [ "https://mathematica.stackexchange.com/questions/16324", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/2162/" ] }
16,375
I have been wrapping my head around this for a while now and I have not found a solution so far. I want to work with an arbitrary number of variables in Mathematica and use some built in functions. To make things more specific for starters I want to do the following. Define a sum with $n$ summands each containing a new variable x[i] (in the $i$-th summand): sum[n_] = Sum[i x[i], {i, 1, n}] Then I want to differentiate the expression with respect to some x[i] like: D[sum[n], x[2]] Mathematica returns $0$ instead of $2$. However if I supply a specific $n$ like: D[sum[2], x[2]] everything works fine. I thought about using Assumption for $n$, but with no success so far. How can I do that right?
Here is the simplest answer: sum[n_] := Sum[i x[i], {i, 1, n}] x /: D[x[i_], x[j_], NonConstants -> {x}] := KroneckerDelta[i, j] D[sum[n], x[2], NonConstants -> x] $\begin{cases} 2 & n>1 \\ 1-n & \text{True} \end{cases}$ The trick here is the use of the NonConstants option of the derivative operator. This then has to be combined with a definition stating that the x[i] are independent variables for the purposes of this differentiation (hence the KroneckerDelta on the second line). Edit: more discussion And here is another cool result, completely symbolic: Assuming[m ∈ Integers, D[sum[n], x[m], NonConstants -> x]] $\left( \begin{array}{cc} \{ & \begin{array}{cc} m & m\geq 1 \\ 0 & \text{True} \\ \end{array} \\ \end{array} \right)-\left( \begin{array}{cc} \{ & \begin{array}{cc} m & m>2\land m\geq n+1 \\ n+1 & m=2\land n=1 \\ \end{array} \\ \end{array} \right)$ This isn't easy to absorb, but it works if you check it with specific examples by doing condition = %; Simplify[condition /. m -> 10] $\begin{cases} 10 & n>9 \\ 0 & \text{True} \end{cases}$ In summary, it's worth pointing out that a lot of symbolic differentiation tasks can be achieved by using either NonConstants specifications in D or conversely using Constants specifications in Dt .
{ "source": [ "https://mathematica.stackexchange.com/questions/16375", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5033/" ] }
16,383
How to generate a picture like the following (from Paolo Čerić's blog )? I'd like the surface of the manifold to randomly distort.
Needs["PolyhedronOperations`"] poly = Geodesate[PolyhedronData["Dodecahedron", "Faces"], 4]; amplitude = 0.15; twist = 4; verts = poly[[1]]; faces = poly[[2]]; phases = RandomReal[2 Pi, Length[verts]]; newverts[t_] := MapIndexed[{Sequence @@ (RotationMatrix[twist Last[#1]].Most[#1]), Last[#1]} (1 + amplitude Sin[t + phases[[First@#2]]]) &, verts]; newpoly[t_] := GraphicsComplex[newverts[t], faces]; duration = 1.5; fps = 24; frames = Most@ Table[Graphics3D[{EdgeForm[], newpoly[t]}, PlotRange -> Table[{-(1 + amplitude), (1 + amplitude)}, {3}], ViewPoint -> Front, Background -> Black, Boxed -> False], {t, 0, 2 Pi, 2 Pi/(duration fps)}]; ListAnimate[frames, fps] The next thing you need is global illumination , but Mathematica doesn't have that as far as I know.
{ "source": [ "https://mathematica.stackexchange.com/questions/16383", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/357/" ] }
16,421
RegionPlot3D is awesome. Unfortunately, it appears to work only for Cartesian coordinates. While there are ways to draw surfaces in spherical or cylindrical coordinates, I can't find a way to draw solids. Is there a way to do so that doesn't involve translating the equations to Cartesian coordinates? Thanks.
You can always hide away the coordinate transformations inside a function that calls RegionPlot3D . Here's a quick & dirty sphericalRegionPlot3D : sphericalRegionPlot3D[ ineq_, {r_, rmin_: 0, rmax_: 1}, {th_, thmin_: 0, thmax_}, {ph_, phmin_, phmax_}, opts___] := RegionPlot3D[With[{ r = Sqrt[x^2 + y^2 + z^2], th = ArcCos[z/Sqrt[x^2 + y^2 + z^2]], ph = ArcTan[x, y] + Pi}, ineq && rmin <= r <= rmax && thmin <= th <= thmax && phmin <= ph <= phmax], {x, -rmax, rmax}, {y, -rmax, rmax}, {z, -rmax, rmax}, MeshFunctions -> {Sqrt[#1^2 + #2^2 + #3^2] &, ArcTan[#1, #2] &, ArcCos[#3/Sqrt[#1^2 + #2^2 + #3^2]] &}, opts]; SetAttributes[sphericalRegionPlot3D, HoldAll]; Example: sphericalRegionPlot3D[ Mod[ph, Pi/3] < Pi/6, {r, 2, 3}, {th, 1, Pi}, {ph, 0, 2 Pi}, PlotPoints -> 100, Mesh -> {3, 60, 30}]
{ "source": [ "https://mathematica.stackexchange.com/questions/16421", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/790/" ] }
16,485
I recently contacted McGraw-Hill to see if they have a mechanism in place for printing out-of-print books that are still of interest. Specifically, I asked about "Power programming with Mathematica" by David Wagner , as I am personally interested in obtaining a copy, and suspect that others might also be interested. Here is the literal response I received from McGraw-Hill: Good morning Todd, If there was a high enough demand for the book there is a possibility. If you can let me know how many you're looking for, and the name of the school or business you're with I can contact the editor and check to see if there's something that can be done. McGraw-Hill Education First, please don't get your hopes up, as nothing may come of this; however, I am committed to seeing this through if there is sufficient community support to get the publisher to make it available again, if only for a limited time. If you would be interested in purchasing a copy of Wagner's text, please respond in the affirmative by making a comment to this question, such as "yes, I would like to purchase a copy." In this way, I can directly "show" our community's interest to the publisher. At this time, I can't speak to cost, but it is clear that we need a "critical mass" to get the publisher's attention to make it worthwhile. Keep your fingers crossed and show your support!
To download a licensed copy of Power Programming with Mathematica by David B. Wagner, please click here: https://www.dropbox.com/s/j2dsyvptnxjd369/Wagner%20All%20Parts-RC.pdf Thank you to McGraw-Hill for granting me the license to scan and distribute this out-of-print text to the Mathematica community! Thank you to Manfred Plagmann (aka matariki) for taking the time to carefully scan the entire text. Thank you to Sophia Scheibe (aka halirutan's wife) for providing select scans of pages to Manfred to allow him to complete his work. Thank you to Mr. Wagner for writing this text! Happy computing everyone! Todd
{ "source": [ "https://mathematica.stackexchange.com/questions/16485", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/249/" ] }
16,542
Does Mathematica have an interactive date input control that lets the user choose a date by browsing to a calendar view and returning the selected date as a date list? For example, something like the Datepicker in jQuery.
Date-picker implementation in Mathematica The following is my implementation of a simple date-picker. The current date is highlighted in LightBlue and the weekends are highlighted in LightGreen . The selected date is always highlighted in LightRed (the default selection is the current date). You can tap into this calendar by using the Dynamic values for year , month and date for your custom function (a simple example in the last Panel ). Code: Note that the following implementation uses DayName , which was introduced in version 9. You might have to roll your own if you want to use this in earlier versions of Mathematica . With[{startDayOffset = Thread[{Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday} -> Range@7]}, DynamicModule[{month, year, date, today = DateList[][[;;3]], daysInMonth, calendarView}, {year, month, date} = today; daysInMonth[m_Integer,y_Integer] := DatePlus[{y, m, 1}, {{1, "Month"}, {-1, "Day"}}][[3]]; calendarView[m_Integer, y_Integer] := Grid[ {Style[#, FontWeight -> Bold]& /@ {"Su","M","Tu","W","Th","F","Sa"}} ~Join~ Partition[Range@daysInMonth[m, y], 7, 7, {DayName[{y, m, 1}] /. startDayOffset, 1}, {""}], Frame -> All, FrameStyle -> LightGray ] /. { i_Integer :> Button[ i, date=i, Appearance->"Palette", Background -> Which[ date==i, LightRed, {year, month, i} === today, LightBlue, !FreeQ[DayName[{year, month, i}],Saturday|Sunday],LightGreen, True,White ], ImageSize->{32,32} ], s_String :> Button[ s, , Appearance -> "Palette", Enabled -> False, Background -> If[!s == "", LightGray], ImageSize->{32,32} ] }; Panel[ Column[{ Row[{ Style["Year ",FontSize->16], PopupMenu[Dynamic@year, 1970 ~Range~ 2020],Spacer[10] Style["Month ",FontSize->16],PopupMenu[Dynamic@month, Range@12 ] }], Dynamic@calendarView[month, year], Panel[Dynamic@StringForm["Selected date: `1`/`2`/`3`", date, month, year]] }] ] ] ]
{ "source": [ "https://mathematica.stackexchange.com/questions/16542", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/68/" ] }
16,556
Given lst = {a, b, c, d} I'd like to generate {{a}, {a, b}, {a, b, c}, {a, b, c, d}} but using built-in functions only, such as Subsets , Partitions , Tuples , Permutations or any other such command you can choose. But it has to be done only using built-in commands. You can use a pure function, if inside a built-in command, i.e. part of the command arguments. That is OK. It is of course trivial to do this by direct coding. One way can be lst[[1 ;; #]] & /@ Range[Length[lst]] (* {{a}, {a, b}, {a, b, c}, {a, b, c, d}} *) or even LowerTriangularize[Table[lst, {i, Length[lst]}]] /. 0 -> Sequence @@ {} (* {{a}, {a, b}, {a, b, c}, {a, b, c, d}} *) But I have the feeling there is a command to do this more directly as it looks like a common operation, but my limited search could not find one so far. Sorry in advance if this was asked before. Searching is hard for such general questions.
lst={a,b,c,d}; ReplaceList[lst,{x__, ___} :> {x}] Speaking of "common operation": Table[lst[[;; i]], {i, Length@lst}]
{ "source": [ "https://mathematica.stackexchange.com/questions/16556", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/70/" ] }
16,599
In this answer Brett Champion describes how one can intercept and modify the suggestions used for auto-completion. Question: Is it possible to modify the suggestion for the automatic auto-completion in Mathematica version 9? Background I think it's possible to improve the auto-completion significantly by using camel humps completion . If you want to see it in action, I made a small screen-cast to demonstrate it for Mathematica version 8 (please switch to 1080p and fullscreen): For all users from good old Germany or for users who prefer classical music: here is a GEMA friendly, musically educating version . Users from Germany can enjoy this screen-cast in comforting silence! The basic idea is to allow ListLiPlo , ListLPlot or even LLP to be expanded to ListLinePlot . Since all Mathematica built-in functions are consistently named, this works pretty well to sort the list of suggestions by importance. In the screencast, I used the appearance of built-in functions in all packages of the AddOns directory as measure. The more often a function was used, the more likely it is to be on top of the list if it matches. To give an example: When you expand Pl in version 8, you get a list consisting of Placed , Placeholder , PlaceholderRepeated , Plain , Play , ... Those are all functions I barely use. I the auto-expansion I wrote, Plot , PlotRange and Plus are on the top of the list and after them all the others follow. In version 9 this was fixed and the completion box seems to have a better ordering.
Preface With Mathematica version 9.0.1 the following answer not valid anymore because the underlying protocol between front end and kernel was changed. Fortunately, we started to implement an open-source Mathematica plugin for IntelliJIDEA which has a full support for camel-hump completion. Please see this post for more information Camel-humps auto-completion for Mathematica The answer to my question is yes, we can expand the auto-completion capabilities of Mathematica . For those who want to know, how exactly this can be done, I suggest reading the Reverse engineering section below. There I explained how you can investigate in the default completion in Mathematica and how you can modify its behavior. For all those who cannot wait to test it: A simple Get of my package from my GitHub repository turns the camel-humps completion on: Get["http://goo.gl/wtVze"] In Mathematica 9 you should now see a suggestion box when you type e.g. PP . If you want to turn it off again can simply restart the kernel or you use FE`RecoverDefaultCompletion[] . If you want to install it permanently you can for instance copy the contents of the package to your init.m . Usage To be really fast with this kind of help you have to try avoiding arrow-keys for going down the suggestion list. Instead, you should specify your wanted function further and further by leaving out the small letters between capital camel-hump letters. A very good example is Hypergeometric0F1 . Instead of typing Hy and going down the list very far, you leave out 12 letters and type Hy0 . In many, many cases this leads to only one unique choice of an expansion and you only have to press Enter (or Tab ) to accept it. If there are still several choices in the end, then you can use your arrow keys. One example here is, when you typed (heroically) LLLP to shorten ListLogLinearPlot and see that there is a ListLogLogPlot with the same abbreviation. Unfortunately, at this point even typing LLLPlot does not help to make it clear and you have to use the arrow key to choose the right function. Let me show you, what works and how it works. Completion of usual function names works now both ways: You get valid expansions if you type a prefix of the function like Integ for IntegerDigits . Additionally, you can type IntDig , InDi or just ID to get IntegerDigits too. Important is that you take care of the capital letters in the names. Support for completion of Options was added too. Additionally, camel-humps even work after context specifications . Note, that the context-names themselves cannot be camel-humps expanded because in most cases like Developer , Experimental , Internal , etc. this would be useless anyway. How it was reverse-engineered Let me explain in detail how you can investigate into how the auto-completion works. What I used is the JLink Link Snooper . With this you don't start the Mathematica kernel as usual. Instead a special JLink program listens and prints the communication between front-end and kernel. The installation is straight forward: You go to Evaluation -> Kernel Configuration Options and create a new kernel exactly as described in the documentation to LinkSnooper I linked above. Then you set either Default Kernel or the Notebook Kernel (in the Evaluation menu) to the LinkSnooper and restart the kernel. A java window pops up showing you all traffic. When the message-war of the initialisation is over you can clear the window and then type for instance Pl and you see that at this very moment the front-end sends a packet to the kernel. The LinkSnooper tells me System`EvaluatePacket[FrontEnd`SynchronousDynamicEvaluate[TimeConstrained[ FE`CAFC["Pl", False] , 6.0], 0, 9.0, 0.2563962936401367]] The important line is of course the second one. Here you see, that the function FE`CAFC is called. Let's have a look a the implementation (I killed all context prefixes in the output): ??FE`CAFC CAFC[nameString_,ignoreCase_:False]/;$Notebooks:= MathLink`CallFrontEnd[FrontEnd`CompletionsListPacket[ nameString, Names[nameString<>"*",IgnoreCase->ignoreCase], Contexts["*"<>(nameString<>"*")] ],NoResult] The kernel sends a CompletionListPacket to the front-end which has 3 parameters. As far as I could find out they mean the following: nameString is not only a repetition of the input-string! This is used as filter. So when Pl is expanded and the list of suggestions (the second parameter) would contain the word BarbieAndKen the front-end won't show this in the choice-box, because Barbie.. does not match Pl... . This is important for our camel hump expansion, because we try to expand something like LLP to ListLinePlot . The solution here is to take only the first letter of the input-string which will hopefully always match. So if I try to expand LLP and I give ListLinePlot in my suggestions list, then the L... will match and ListLinePlot is displayed in the suggestion box. The second parameter is simply a list of suggestions which are displayed if they match the first parameter. Currently, only all matching names are displayed. We will extend this, so that we calculate possible function-names from camel hump shorties. This is the list of possible matching context names. How options-matching works Unfortunately, the matching of options seems to works differently. Here, Mathematica uses the syntax information of the function to decide whether you are on a possible option position. Here are two equivalent calls: Plot[x, {x, 0, 1}] Plot[Sequence[x, {x, 0, 1}]] If you now go behind the closing curly braces of each example, make a comma and type Pl you shouldn't be too surprised that the first list contains all options, where the second choice-box contains usual function. If you check the output of the LoopSnooper , then you see that only in the first case the function FE`OC["Plot", "Pl"] is called. This is the option-completion function and it looks like OC[nameString_,patternString_]/;$Notebooks:= MathLink`CallFrontEnd[FrontEnd`OptionCompletionsListPacket[ nameString, patternString, (ToString[#1]&)/@(InputForm[#1]&)/@ Options[ToExpression[nameString]]], NoResult] See, that here a OptionCompletionsListPacket is send to the front-end. Therefore, the front-end handles options-expansion differently. For the moment I will not touch this, because I haven't tested the stuff, but I will. What you should see here is, that our camel hump expansion will currently only work on function names and not, when you are inside a function at an option-position. Implementation Here are the important details of the following lines. First, I will import the file with the function informations of all Mathematica functions. This contains function names, call patterns and template constructs, but I will only use the function names. The difference to a call to Names is, that this contains the function names only and not some options. For the current purpose this is maybe better. The next one-liner is maybe the most important function: nameParts[in_String] := StringCases[in, _?(UpperCaseQ[#] || DigitQ[#] &) ~~ ___?LowerCaseQ]; This has the purpose to split a Mathematica -style function name into its parts. When a capital letter is seen, a new part starts nameParts["ListPointPlot3D"] (* {"List", "Point", "Plot", "3", "D"} *) What you could do is, you take from every part as many lower case letters as you want from the back and put it back together and you have a valid, expandable camel hump short-cut. Important is, that such a word-part starts always with a capital letter and is followed only by lower-case letters. Numbers are like capital letters. This is then used in the getMatch function. There, we take some input and calculate all possible function expansions by using the name-parts to create a regular expression. Then we implant this into the FE`CAFC function and after executing this, the advanced expansion should work. So typing FiAM for instance gives The complete implementation can be found on my GitHub site Known issues and limitations and bug-report To report bugs or unusual behavior please use the issues section here . The front-end does not call on every keystroke the auto-completion function. You can watch this on the LinkSnooper . This means for instance, that you won't get a choice box when you type FAM , although FindArgMin matches. Our function is simply not called. What you can do is type another i or press Cmd + k . On Linux there seems to be a bug regarding the above point: When you type Pl and close the appearing suggestion-box with Esc it is not possible to use Ctrl + k to reopen this box. Using arrow-keys to move around and going then to the same place and it works. jensbob reported that a message was generated about Throwing False when the code is put into init.m . This issue is fixed and was not related to the autocompletion code itself. sebhofer asked in the comments: Would it in principle be possible to get completion similar to most shells where hitting tab completes to the longest common sequence and not to the first match? Answer: In principal yes, but there's a very big but attached to this. In version 8 where you have to hit Ctrl + K for expansion the suggestion-box shows the entries exactly in the same order as I supply it (at least in Linux!). Here, the thing you would have to implement is the calculation of the longest common sequence and then you prepend it to the list of suggestions you return. Then this is always on top of of list and you can simply expand it always. In version 9 the list of suggestions is sorted by the FE (front end) and I don't know how to influence the ordering. This all happens inside the FE where you have not really a chance to re-engineer what happens. The only possibility I see here is to supply the longest common sequence as only suggestion when it exists. One problem in both versions is that the FE closes the suggestion and don't asks the kernel again whether there exist more possible expansions because it believes you already found the function you like to have. You can test this: type Plo and you see the Plot is LCS here. Accepting this closes the window and you would have to type another letter or Ctrl + K to reopen it. I don't think this is a good idea. 18/01/2013 I forgot to include $ as separator and therefore variables like $KernelID can not be shortened by e.g. $KID . Furthermore, I think about adding symbols in the Global` which don't start with a capital letter. In this way it's possible to expand user-defined symbols too.
{ "source": [ "https://mathematica.stackexchange.com/questions/16599", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/187/" ] }
16,657
I have enjoyed working with R inside Mathematica . But it would be nice If I could have a special R cell. For example, instead of typing REvaluate["{ data(iris) reg <- lm( Sepal.Length ~ Species, data=iris ) summary.text <- capture.output(print( summary(reg)) ) }"] I would change the cell style to the special R code one and simply type in the code as I would do in a terminal window. Like so: data(iris) reg <- lm( Sepal.Length ~ Species, data=iris ) summary.text <- capture.output(print( summary(reg)) ) Is there some way to create such a FrontEnd cell? In the future I would like Mathematica to have code highlighting and autocompletion for such cells. This would make Mathematica the best environment for working with R.
The R code highlighter There is an undocumented symbol RLink`Private`rcell When you type it and press Shift+Enter, you get a syntax-highlighted R code cell based on my real-time syntax highlighter , which is connected to REvaluate and highlights the code as you type. Note that the cell where you type RLink`Private`rcell will be gone, replaced with the new R code cell. If it is too much typing, you can make an alias like so: rc := RLink`Private`rcell and then evaluate rc instead. Here is a sample screenshot: Some details As noted in my answer about the highlighter, it does perform bracket and parentheses matching / highlighting as well. To make it more responsive, I disables re-parsing on all keys except left/right arrows and space bar, so you will have to press one of those to re-render. Normally they are pressed most frequently when working with code, so this should not be very noticable. Also, the cursor may disappear at times, but again, pressing these keys should make it re-appear. The same remark goes to the visibility of block selection. Note that, as present, rcell does not understand the multi-line code string without curly braces. One way to fix this is to execute this code: ClearAll[RLink`Private`replR] RLink`Private`replR[code_String] := REvaluate["{" <> code <> "}"] Limitations For Windows, the highlighter works fine. For other platforms, the highlighter was giving me crashes on some Linux flavors and on Mac. But, I got reports for other Linux flavors that it worked fine there. So, ymmv, but you can give it a try. Apart from problems on specific platforms, the highlighter may have a few glitches. If you find some, I would appreciate if you report them to me.
{ "source": [ "https://mathematica.stackexchange.com/questions/16657", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/2266/" ] }
16,697
Is there a command / menu entry / keyboard shortcut to evaluate all cells above / up to the current cursor position? I have the feeling I am missing something elementary here... Addendum : In fact, it is more about selection of those cells, evaluation is not the problem as such.
One possibility is to modify your personal KeyEventTranslations.tr (only tested on Windows). Evaluate the following, then restart Mathematica, then Ctrl + Shift + Home will select all cells above the insertion point. For 9.0.1. use: Import["http://www.mertig.com/shortcuts.m"] mymenuitems=" (* Select all cells upwards *) Item[KeyEvent[\"Home\", Modifiers -> {Control, Shift}], KernelExecute[ Module[{ enb = EvaluationNotebook[], tag = StringJoin[\"tmp\", ToString[Round[AbsoluteTime[]/$TimeUnit]]],editable }, editable = ReplaceAll[Editable, Options[enb, Editable]]; SetOptions[enb, Editable -> False]; SelectionMove[enb, Previous, Cell, AutoScroll -> False]; MathLink`CallFrontEnd[FrontEnd`SelectionAddCellTags[enb, {tag}]]; SelectionMove[enb, Before, Notebook, AutoScroll -> False]; SelectionMove[enb, Next, Cell, AutoScroll -> False]; While[FreeQ[ReplaceAll[CellTags,Options[NotebookSelection[]]], tag], MathLink`CallFrontEnd[FrontEnd`SelectionAddCellTags[enb, {tag}]]; SelectionMove[enb, Next, Cell, AutoScroll -> False] ]; NotebookFind[enb, tag, All, CellTags, AutoScroll -> False]; MathLink`CallFrontEnd[FrontEnd`SelectionRemoveCellTags[enb, {tag}]]; SetOptions[enb, Editable -> editable] ] ], MenuEvaluator -> Automatic ] "; With[{os = Switch[$OperatingSystem,"MacOSX","Macintosh","Windows","Windows","Unix","X"]}, Quiet@CreateDirectory@FileNameJoin[{$UserBaseDirectory,"SystemFiles","FrontEnd","TextResources",os}]; mykeyeventtrans=FileNameJoin[{$UserBaseDirectory,"SystemFiles","FrontEnd","TextResources",os,"KeyEventTranslations.tr"}]; (*If[FileExistsQ[mykeyeventtrans],DeleteFile@mykeyeventtrans];*) If[!FileExistsQ[mykeyeventtrans], CopyFile[FileNameJoin[{$InstallationDirectory,"SystemFiles","FrontEnd","TextResources",os,"KeyEventTranslations.tr"}],mykeyeventtrans] ]]; keytext=Import[mykeyeventtrans,"Text"]; mykeytext=StringReplace[keytext,"EventTranslations[{":>StringJoin["EventTranslations[{\n(* User defined *)\n",mymenuitems,",\n"]]; Export[mykeyeventtrans,mykeytext,"Text"];
{ "source": [ "https://mathematica.stackexchange.com/questions/16697", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/131/" ] }
16,723
I'm studying time-series in R with this book , and there is a nice command in R that creates decompositions. Inside Mathematica 9 the command can be executed as: Needs["RLink`"] InstallR[]; REvaluate["{ url <- \"http://www.massey.ac.nz/~pscowper/ts/cbe.dat\" CBE <- read.table(url, header = T) Elec.ts <- ts(CBE[, 3], start = 1958, freq = 12) plot(decompose(Elec.ts, type = \"multi\")) }"] and creates this plot: The first part of my attempt to reproduce this in Mathematica is: url = "http://www.massey.ac.nz/~pscowper/ts/cbe.dat"; CBE = Import[url]; elecTS = TemporalData[CBE[[2 ;; -1, 3]], {{1958}, Automatic, "Month"}]; DateListPlot[elecTS["Path"], Joined -> True, AspectRatio -> 0.2] How do I continue this to perform the decomposition wholly within Mathematica ?
Based on @b.gatessucks answer and on @RahulNarain comment tip, I created this functions for the multiplicative decompose case. I changed @b.gatessucks method for seasonality to keep it closer from R method, and used TemporalData to easily handle time interval. decompose[data_,startDate_]:=Module[{dateRange,plot,plotOptions,observedData,observedPlot,trendData,trendPlot,dataDetrended,seasonalData,seasonalPlot,randomData,randomPlot}, dateRange={{startDate,1},Automatic,"Month"}; (*Setting Plot Options*) plotOptions={AspectRatio -> 0.2,ImageSize-> 600,ImagePadding->{{30,10},{10,5}},Joined->True}; (*Observed data*) observedData=TemporalData[data,dateRange]["Path"]; observedPlot=DateListPlot[observedData,Sequence@plotOptions]; (*Extracting trend component*) trendData=Interpolation[MovingAverage[observedData,12],InterpolationOrder->1]; trendPlot=DateListPlot[{#,trendData[#]}&/@observedData[[All,1]],Sequence@plotOptions]//Quiet; dataDetrended=N@{#[[1]],#[[2]]/trendData[#[[1]]]}&/@observedData//Quiet; (*Extracting seasonal component*) seasonalData=Mean/@Flatten[Partition[N@dataDetrended[[All,2]],12,12,1,{}],{2}]; seasonalData=TemporalData[PadRight[seasonalData,Length[data],seasonalData],dateRange]["Path"]; seasonalPlot=DateListPlot[seasonalData,Sequence@plotOptions]; (*Extracting random component*) randomData=TemporalData[dataDetrended[[All,2]]/seasonalData[[All,2]],dateRange]["Path"]; randomPlot=DateListPlot[randomData,Sequence@plotOptions]; (*Plotting data*) plot=Labeled[ Grid[Transpose[{Rotate[Style[#,15,Bold],90\[Degree]]&/@{"observed","trend","seasonal","random"} ,{observedPlot,trendPlot,seasonalPlot,randomPlot}} ] ] ,Style["Decomposition of multiplicative time series",Bold,17] ,Top ] ] Using the functions like this: rawData = Import["http://www.massey.ac.nz/~pscowper/ts/cbe.dat"][[2 ;;, 3]]; decompose[rawData, 1958] We get: Almost exactly as in R! I say "almost" because R don't use interpolation, so the MovingAverage lost 12 point in R that we don't lose in this function due to interpolation method. I prefer to keep the ticks in each plot, I find it's better to read. It's a question of personal options.
{ "source": [ "https://mathematica.stackexchange.com/questions/16723", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/2266/" ] }
16,802
In an attempt to squeeze more plots and controls into the limited space for a demo UI, I am trying to remove any extra white spaces I see. I am not sure what options to use to reduce the amount of space between the ticks labels and the actual text that represent the labels on the axes. Here is a small Plot example using Frame->True (I put an outside Frame as well, just for illustration, it is not part of the problem here) Framed[ Plot[Sin[x], {x, -Pi, Pi}, Frame -> True, FrameLabel -> {{Sin[x], None}, {x, Row[{"This is a plot of ", Sin[x]}]}}, ImagePadding -> {{55, 10}, {35, 20}}, ImageMargins -> 0, FrameTicksStyle -> 10, RotateLabel -> False ], FrameMargins -> 0 ] Is there an option or method to control this distance? Notice that ImagePadding affects distance below the frame label, and not between the frame label and the ticks. Hence changing ImagePadding will not help here. Depending on the plot and other things, this space can be more than it should be. The above is just a small example I made up. Here is a small part of a UI, and I think the space between the t(sec) and the ticks is too large. I'd like to reduce it by few pixels. I also might like to push the top label down closer to the plot by few pixels also. I am Using V9 on windows. update 12/22/12 Using Labeld solution by @kguler below is a good solution, one just need to be little careful with the type-sitting for the labels. Plot automatically typeset things as Text in TraditionalFormat , which is a nice feature. To do the same when using Labeled one must do this manually using TraditionalForm and Text as well. Here is example to show the difference 1) Labeled used just with TraditionalForm . The left one uses Plot and the right one uses Labeled with TraditionalForm . Notice the difference in how labels look. Grid[{ { Plot[Sin[x], {x, -Pi, Pi}, Frame -> True, FrameLabel -> {{Sin[x], None}, {x, E Tan[x] Sin[x]}}, ImageSize -> 300, FrameTicksStyle -> 10, FrameStyle -> 16,RotateLabel -> False], Labeled[ Plot[Sin[x], {x, -Pi, Pi}, Frame -> True, ImageSize -> 300], TraditionalForm /@ {Sin[x], x, E Tan[x] Sin[x]}, {Left, Bottom, Top}, Spacings -> {0, 0, 0}, LabelStyle -> "Panel"] } }, Frame -> All] 2) Now we do the same, just need to add Text to get the same result as Plot . Grid[{ { Plot[Sin[x], {x, -Pi, Pi}, Frame -> True, FrameTicksStyle -> 10, FrameStyle -> 16, FrameLabel -> {{Sin[x], None}, {x, E Tan[x] Sin[x]}}, ImageSize -> 300, RotateLabel -> False], Labeled[ Plot[Sin[x], {x, -Pi, Pi}, Frame -> True, ImageSize -> 300], Text /@ TraditionalForm /@ {Sin[x], x, E Tan[x] Sin[x]}, {Left, Bottom, Top}, Spacings -> {0, 0, 0}, LabelStyle -> "Panel"] } }, Frame -> All] Update 12/22/12 (2) There is a big problem with controlling the spacing. Labeled spacing only seem to work for horizontal and vertical spacing, taken togother. i.e. One can't control spacing on each side of the plot separately? Here is an example, where I tried to move the bottom axes label up, this ended with moving the top label down as well. Which is not what I want. Labeled[Plot[Sin[x], {x, -Pi, Pi}, Frame -> True, ImageSize -> 300], Text /@ TraditionalForm /@ {Sin[x], x, E Tan[x] Sin[x]}, {Left, Bottom, Top}, Spacings -> {-.2, -0.7}] Will see if there is a way to control each side spacing on its own. Trying Spacing->{-0.2,{-0.7,0}} does not work, it seems to take the zero in this case and ignored the -0.7 This gives the same result as above: Labeled[Plot[Sin[x], {x, -Pi, Pi}, Frame -> True, ImageSize -> 300], Text /@ TraditionalForm /@ {Sin[x], x, E Tan[x] Sin[x]}, {Left, Bottom, Top}, Spacings -> {-.2, -0.7, .0}] ps. there might be a way to specify the spacing for each side with some tricky syntax. I have not figured it out yet. Still trying thing.... http://reference.wolfram.com/mathematica/ref/Spacings.html update 12/22/12 (3) Using combination of ImagePadding and Spacing should have worked, but for some reason, the top label now is cut off. Please see screen shot. Using V9 on windows Note: The above seems to be related to the issue reported here: some Graphics output do not fully render on the screen until an extra click is made into the notebook Need an extra click inside the notebook. Then label become un-chopped !
The most convenient way I found is to wrap Plot (without FrameLabels and PlotLabel and with appropriate ImagePadding and ImageMargins ) inside Labeled and use the Spacings option to position the labels: Labeled[Plot[Sin[x], {x, -Pi, Pi}, Frame -> True, ImagePadding -> {{20, 1}, {15, 2}}, ImageMargins -> 0, FrameTicksStyle -> 10], TraditionalForm /@ {Sin[x], x, Row[{"This is a plot of ", Sin[x]}]}, {Left, Bottom, Top}, Spacings -> {0, 0}, LabelStyle -> "Panel"]
{ "source": [ "https://mathematica.stackexchange.com/questions/16802", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/70/" ] }
16,834
Using the following code, I downloaded an image from the web and adjusted the image to obtain the "negation" of the image: im1 = Import["http://www.furnituremaker.com/images/Craftsman.gif"] im2 = ColorConvert[ ImageAdjust[ ColorQuantize[ColorNegate[im1], 20, Dithering -> False], 1], "Grayscale" ] Now, I would like to convert this to an image that is "nearly" black and white. By "nearly," I mean that the resulting image may have a small amount of gray at the interface of the black and white, so as to keep the resulting image smooth. (It seems like simply rasterizing an image can sometimes look bad.) How can I accomplish this? I tried using Darker , but it just makes the background gray again: im3 = Darker[im2] Instead I would like to somehow adjust the saturation so that the line art and text appears black. ColorConvert seems like a possibility, but in the documentation I do not see how to specify a black and white color space. Can you please help me?
im1 = Import["http://www.furnituremaker.com/images/Craftsman.gif"] Perhaps something like this? ColorNegate@Binarize@ImageResize[im1, Scaled[4]]~Image~ ImageType[im1]~ImageResize~ImageDimensions[im1] (thanks to @RahulNarain's for his suggestions)
{ "source": [ "https://mathematica.stackexchange.com/questions/16834", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1185/" ] }
16,869
Recently I came across a set of problems which would be solved most easily within an object-oriented approach. I first attempted to solve them by other means, but found the complexity of the code growing too fast and, while individual functions used a mixture of styles, the overall feel and organization of the code was de-facto procedural. Having looked at the final code, I saw that I would have written it much faster and cleaner in Java, which is when I realized that OO was needed. Basically, I needed it to reuse some behavior and decrease coupling between components. We all know that there were a number of attempts on implementing OO extensions for Mathematica. However, none of them IMO were very simple, and none of those I looked at had a natural "look and feel" for Mathematica (I could have missed some). OTOH, we also know that Mathematica has powerful metaprogramming capabilities, which should make it possible to implement the core of an OO extension rather easily. Since OO is a broad paradigm, here are some requirements to restrict the problem. The desired OO extension should Be idiomatic . Programming in it should feel natural for experienced Mathematica users. In particular, it should go well with immutable Mathematica expressions, and have the least possible problems concerning interoperability with Mathematica (garbage collection - related problems etc). Support instantiation, inheritance and polymorphism . By inheritance I mean reuse of behavior (methods) rather than state (fields). Reuse as much of the Mathematica's core constructs as possible Limit the things that can be done with it as little as possible , compared to the programming techniques and tricks we are used to in Mathematica If possible, have at least minimally convenient syntax for things like method calls. Implementation should be simple in the sense that it should not introduce too many exterior constructs, such as ToString - ToExpression cycles, needless manipulations with contexts, creation of new symbols which are not strictly necessary, etc. I am not so much worried about efficiency here, since the intended purpose for such an extension is more to help with larger-scale code organization for certain classes of tasks, than to be used with millions of light-weight objects. In many previous questions on similar topics, the two rather separate topics were often mixed together. One concerns mutable struct-like data structures and their possible implementations in Mathematica, and the other was about OO proper. So, to clarify a bit more, I am not so much interested in the former topic here. I am rather more interested in the dynamic aspects (behavior reuse), and ways to conveniently package code and organize larger projects, but not so much in efficient mutable data structures. In other words, the subject matter is what can the object orientation bring to the table for larger Mathematica projects, and how can we make the most out of it in Mathematica. So, the question is : can we have a core of such an OO extension in under 100 lines of Mathematica code?
The answer seems to be yes. At least, I will try to describe an attempt which would pass the "under 100 lines of code" test. How well it satisfies the other criteria is a subjective matter, but I have already used it for larger-scale project with so far very positive results. I will present two implementations. One is an absolute toy, but extremely simple. The other is also a toy, but having all the core requested features. The one I now use in real project is somewhat more complex, but has the same core. A toy implementation in under 25 lines of code Implementation Here is the toy implementation. It is small enough that I can present it first and explain afterwards. The following implements the type declaration operator, where the type is represented by a symbol: ClearAll[DeclareType]; DeclareType[s_Symbol] := Function[Null, ClearAll[s]; SetAttributes[s, HoldAll]; defineMethods[s, ##]; s, HoldAll]; This does not do much until defineMethods has been defined. Neither does this support inheritance, so we add the following: DeclareType[s_Symbol ~ Extends ~ p_Symbol] := Function[Null, DeclareType[s][##]; SuperType[s] = p; s[self_][lhs_] := p[self][lhs]; s, HoldAll]; Here, Extends is an inert head introduced for clarity only, and SuperType holds a value of the supertype, if there is any. Finally, ClearAll[defineMethods]; SetAttributes[defineMethods, HoldRest]; defineMethods[s_] := s; defineMethods[s_, SetDelayed[lhs_, rhs_], rest___] := Module[{}, s[cont_][lhs] := Block[{$self = s[cont], $super = SuperType[s][cont]}, rhs ]; defineMethods[s, rest]]; This is all there is here. This introduces two special symbols $self and $super , which can be used inside the body of any method defined for a type, to refer to the object itself or call methods of its supertype. The way this works is as follows: I use rules to define methods as SubValues for the type symbol, and the patterns used in the method definitions naturally become the parts of the resulting SubValues . Examples This declares the type Animal : DeclareType[Animal][ breathe[] := Print["I am breathing ", $self[[1, 1]]], sleep[duration_String: "one hour"] := "I have been sleeping for " <> duration, sleep[duration_Integer] := $self@sleep[ToString[duration] <> " hours"], move[] := Print["I move ", $self[[1,2]]] ] (* Animal *) Now we create an instance of this type: an = Animal[{"oxygen","fast"}] (* Animal[{oxygen,fast}] *) Note that the instance is completely stateless, it is fully defined by an expression (list) containing its content. We can now call methods: an@breathe[] During evaluation of In[68]:= I am breathing oxygen an@sleep[] (* I have been sleeping for one hour *) an@sleep["two hours"] (* "I have been sleeping for two hours" *) an@sleep[5] (* "I have been sleeping for 5 hours" *) Already here, we can note one very important big advantage of this scheme: one can use the usual sweet Mathematica pattern-matching to define methods, including all (well, most of) the nice stuff, such as default values, overloading, etc. But what about inheritance? Well, here is an example: DeclareType[Cat ~ Extends ~ Animal][ sleep[] := StringJoin[$super@sleep[], $self[[1, 3]]] ] (* Cat *) We now create an instance: cat = Cat[{"oxygen","fast"," on the floor"}] (* Cat[{oxygen,fast, on the floor}] *) and call the methods: cat@breathe[] During evaluation of In[125]:= I am breathing oxygen cat@sleep[] (* I have been sleeping for one hour on the floor *) cat@sleep["three hours"] (* I have been sleeping for three hours *) Note that inheritance works as one would expect. In particular, the Cat 's version of sleep method is called for zero arguments, while Animal 's version is called for other calls for sleep . Note also that the Cat 's sleep method has access to the parent's method via $super . In a sense, this is probably as close to an ideal mix of OO and Mathematica as it gets: objects are completely stateless and based on immutable Mathematica expressions. However, this approach has a number of flaws. In particular, it requires that all the symbols used as method names do not have definitions such that they can prematurely evaluate. For example, having defined something like breathe[] := Print["breathe"] would spoil the above behavior. It is rather desirable that things be more robust. Another problem (which would persist to my other implementations) is shadowing. If two different users define types with the same method names which live in different contexts, shadowing will happen. It could probably be solved by converting symbol names to strings and then using only the short symbol names, but I think this is not an idiomatic Mathematica solution, in many ways. So, the other way to solve this (and this is what I do) is by convention: introduce a special context (e.g. OO`Methods` ), and place all symbols used for method names there. This can also solve the evaluation problem, if in addition one adopts a convention to not assign any rules to those symbols. The above declaration for Animal would then look like: DeclareType[Animal][ OO`Methods`breathe[] := Print["I am breathing ", $self[[1, 1]]], OO`Methods`sleep[duration_String: "one hour"] := "I have been sleeping for " <> duration, OO`Methods`sleep[duration_Integer] := $self@OO`Methods`sleep[ToString[duration] <> " hours"], OO`Methods`move[] := Print["I move ", $self[[1,2]]] ] Note that the user of the type does not have to use long names, as long as both the type's context and OO`Methods` are on the $ContextPath . A more real thing The implementation I am going to show now is the core of what I ended up using, but is based on the same set of ideas. The main technical difference is that, in order to prevent premature evaluation of method calls, I found no other way than to introduce some state into the objects / instances. They will be now represented by unique (within a given Mathematica session, but this restriction can be lifted) symbols. This is similar in spirit to how JLink implements references to Java objects. And I will use UpValues as a tool to attach both state and behavior to these symbols. While this scheme would help to solve the premature evaluation problem I mentioned, it also opens additional possibilities not easily possible in the simple setting of the previous section, such as attaching new methods to a single instance(rather than a type) at run-time. This by itself is a powerful enough feature to justify this approach (it is not supported by e.g. Java, but is supported by e.g. Javascript). So, without further due, here is the new DeclareType : ClearAll[DeclareType]; DeclareType[Object] = Null; DeclareType[type_Symbol] := DeclareType[type~ Extends ~ Object]; DeclareType[Object ~ Extends ~ _] = Null; DeclareType[type_Symbol ~ Extends ~ superType_Symbol] := Function[ Null , ClearAll[type]; If[ValueQ[vtable[type]], vtable[type] =.]; SetAttributes[type, HoldAll]; defineMethods[type, ##]; SuperType[type] = superType; type , HoldAll ]; It is not so much different from what we had before. The new symbols it relies on are defined as: ClearAll[Object, object]; Object::nomethod = "Unknown method for type Object. The method call was `1`"; SetAttributes[{Object, object}, HoldAll]; Object[__] := object; object[args___,methodCall_] := ( Message[Object::nomethod,ToString@HoldForm[methodCall]]; $Failed ); (this is similar in spirit to Java Object - so that there is a single object hierarchy). Also, SuperType is now defined as ClearAll[SuperType]; SuperType[Object] = Null; SuperType[_] = Object; A symbol vtable stores a reference to a dispatch function for any type. It is initially defined as ClearAll[vtable]; vtable[Object]:=object; but is dynamically acquires new definitions as new types are being defined. Here is a new defineMethods , and this is where things start to get substantially different: ClearAll[defineMethods]; SetAttributes[defineMethods, HoldRest]; defineMethods[s_] := s; defineMethods[s_, args___] := Module[{ff}, SetAttributes[{ff}, HoldAll]; vtable[s] = ff; s[content_] := Module[{sym}, SetAttributes[sym, HoldAll]; sym /: instanceValue[sym] = content; sym /: Normal[sym] := With[{cont = instanceValue[sym]}, HoldForm[s[cont]] ]; (* Note: this forces the arguments to be evaluated *) sym[f_[argums___]] := Hold[f][argums]/.Hold[h_][x___]:> ff[sym,f[x]]; sym /: Set[sym, newcontent_] := sym /: instanceValue[sym] = newcontent; sym/: TypeOf[sym] = s; sym ]; addMethods[args][s]; ]; Here, the input symbol s stands for the name of the type. What happens here is that every time I call SomeType[some-content] , I get a new symbol with the content attached via UpValues and the instanceValue container, and the behavior attached via DownValues and the ff symbol, which is a dispatch function for a given type. The latter is defined only once per type definition, and is stored in vtable[SomeType] . Also, the TypeOf operation is defined (similar to Java getClass ), and one can also replace the full content of the object using Set . The instanceValue container is defined as ClearAll[instanceValue]; SetAttributes[instanceValue,HoldAll]; instanceValue[_]:= Throw[$Failed, {instanceValue,"invalid_instance"}]; The final piece we need is addMethods . Here is the code: ClearAll[addMethods]; SetAttributes[addMethods, HoldAll]; addMethods[SetDelayed[lhs_, rhs_], rest___][s_] := With[{ff = vtable[s]}, ff[sym_, lhs] := Block[{ $self = sym, $content = instanceValue[sym], $super } , SetAttributes[$super,HoldAll]; $content /: Set[$content, expr_] := Set[sym, expr]; $super[call_]:= vtable[SuperType[s]][sym,call]; rhs ]; addMethods[rest][s] ]; addMethods[][s_] := vtable[s][sym_, lhs_] := vtable[SuperType[s]][sym,lhs]; What happens here is that the definitions for the type's dispatch function ff are formed based on the definitions of the methods, supplied by the user. Again, we win big due to the generality of patterns, which allows us to automatically create valid definitions for ff by doing a scope surgery on the original definitions of the methods. Another thing worth noting is again the user of Block which allows the user to use symbols $self , $super and $content inside a body of a method. The same examples as before should work here. In one piece, the code lives here . I left out some more advanced things such as formatting, per-instance method addition at run-time, automatic object release (when objects are no longer needed), etc. These are all implemented in the complete full version that lives here . In particular, the full version has a very simple installation procedure described in the README file in that linked gist. It has an example notebook, which is opened by a simple command GetExampleNotebook[] , once the project has been installed and loaded. Use cases and limitations The OO extension described above is intended to be used as a tool for large-scale project organization. In this capacity, I tested it already on real projects and so far have had very positive results, in terms of code complexity management, modularization of component, and making code more reusable. Some real use cases Here I will list some real examples which rely on it: Generic manipulations with trees of rules (nested options of sorts), including their automatic persistence on disk and a pretty-printer In-memory manipulations with a directory of files , including persistence of changes on disk. Simple version control system to enable automatic versioning of Mathematica projects and hosting them on Github (in gists) - under development. I will add more documentation to these, so that it will be easier to explore them, but in fact they are very easy to use. The code of these example projects also shows how one can do practical things, such as attaching or changing the state of an object. The basic idea is that it is better to avoid adding explicit state (in fact, the current version of OO does not support object fields, only object methods. This was intentional, but such a support can be easily added if there will be a consensus that they are needed). Instead, one can add new methods which would encapsulate the state. This allows to avoid introducing mutable state in objects in many cases, which arguably leads to a cleaner code. Limitations This OO extension has not been designed with high-performance applications in mind. While you can create thousands of objects and use it also for lightweight objects, you will face more or less the usual high-level Mathematica overhead (in my view, this is not so much of a real limitation, since Mathematica has other means for high-performance programming, and OO is often not really needed on such a "fine-grained" scale). Also, one must be careful to avoid the memory leaks. Certain types of patterns in method definitions may also not work, in particular conditional patterns where condition is attached to the left-hand side, such as myMethod[x_,y_]/;x<y:=body Again, this limitation can be rather easily removed by making a slightly more complex parser for addMethods . OTOH, the definitions like myMethod[x_,y_]:=body/;x<y should work, so this is perhaps not so much of an issue. Further developments While I feel that the current state of OO is minimally complete, in the sense that it can be used in serious applications, I plan some further developments, such as Reflection a-la Java (meta-information on methods, etc) Integrated unit-tests Some other enhancements The extension was initially build not just for its own sake, but to provide a base for the development of other projects of interest to me (and very possibly also to a wider audience). So I expect that it will be further shaped by the needs of those projects people build using it. So, any feedback on the system is much appreciated, and will affect further developments.
{ "source": [ "https://mathematica.stackexchange.com/questions/16869", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/81/" ] }
16,881
Well, the title is self-explanatory. What sorts of snowfall can we generate using Mathematica ? There are two options I suggest to consider: 1) Continuous GIF animations with smallest possible number of frames. 2) Dynamic -based animations.
My simple version using Image : size = 300; r = ListConvolve[DiskMatrix[#], RandomInteger[BernoulliDistribution[0.001], {5 size, size}], {1, 1}] & /@ {1.5, 2, 3}; Dynamic[Image[(r[[#]] = RotateRight[r[[#]], #]) & /@ {1, 2, 3}; Total[r[[All, ;; size]]]]] Update A slightly prettier version, same basic idea but now with flakes. flake := Module[{arm}, arm = Accumulate[{{0, 0.1}}~Join~RandomReal[{-1, 1}, {5, 2}]]; arm = arm.Transpose@RotationMatrix[{arm[[-1]], {0, 1}}]; arm = arm~Join~Rest@Reverse[arm.{{-1, 0}, {0, 1}}]; Polygon[Flatten[arm.RotationMatrix[# \[Pi]/3] & /@ Range[6], 1]]]; snowfield[flakesize_, size_, num_] := Module[{x = 100/flakesize}, ImageData@ Image[Graphics[{White, Table[Translate[ Rotate[flake, RandomReal[{0, \[Pi]/6}]], {RandomReal[{0, x}], RandomReal[{0, 5 x}]}], {num}]}, Background -> Black, PlotRange -> {{0, x}, {0, 5 x}}], ImageSize -> {size, 5 size}]]; size = 300; r = snowfield @@@ {{1, size, 500}, {1.5, size, 250}, {2, size, 50}}; Dynamic[Image[(r[[#]] = RotateRight[r[[#]], #]) & /@ {1, 2, 3}; Total[r[[All, ;; size]]]]]
{ "source": [ "https://mathematica.stackexchange.com/questions/16881", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/219/" ] }
16,925
Is there a way to obtain the coordinate of a point of interest in a ListPlot ? As an example, I have a list containing many sets of 2D coordinates and the plot drawn is discontinuous at one point (the first derivative is not continuous and the gradient increases suddenly). Can I extract the location of that point interactively? Otherwise, I have to search through the list of data myself to determine the change of gradient, which defeats the whole purpose of drawing a plot. Also, using the Get Coordinates function from the right click menu does not give very accurate results.
ListPlot accepts data wrappers besides Tooltip (although I could not find any mention of this feature in the docs). So, @Jens' method can be achieved without post-processing: data = Table[{Sin[n], Sin[2 n]}, {n, 50}]; ListPlot[PopupWindow[Tooltip[#], #] & /@ data] On mouseover: Click on a point: Note: Thought this was a new feature added in Version-9, but as @Alexey Popkov noted it also works in version 8.0.4, so it has been around for some time. Update: A simpler version of @Mr.Wizard's printTip can also be used as a wrapper directly inside ListPlot : ListPlot[Button[Tooltip@#, Print[#]] & /@ N@data] Update 2: Collecting point coordinates: clicks = {}; Column[{ListPlot[Button[Tooltip@#, AppendTo[clicks, #]] & /@ N@data, ImageSize -> 300], "\n\t", Row[{"clicks = " , Dynamic[clicks // TableForm]}]}]
{ "source": [ "https://mathematica.stackexchange.com/questions/16925", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5047/" ] }
16,931
Can't regain the data after Export. Create an array of sampled amplitude values: 2. Visualize as sound 3. Save it 4. Get it back 5. ??? sound = RandomReal[1, {500}]; ListPlay[sound] Export["test.txt", sound]; in=Import["test.txt"] ListPlay[in] A second example. Take data from a WAV sound, Export it, reImport it, play it. tubadat = ExampleData[{"Sound", "Tuba"}, "Data"]; Export["TubaDat.dat", tubadat]; in = Import["TubaDat.dat"]; ListPlay[in] It is not the original sound.
ListPlot accepts data wrappers besides Tooltip (although I could not find any mention of this feature in the docs). So, @Jens' method can be achieved without post-processing: data = Table[{Sin[n], Sin[2 n]}, {n, 50}]; ListPlot[PopupWindow[Tooltip[#], #] & /@ data] On mouseover: Click on a point: Note: Thought this was a new feature added in Version-9, but as @Alexey Popkov noted it also works in version 8.0.4, so it has been around for some time. Update: A simpler version of @Mr.Wizard's printTip can also be used as a wrapper directly inside ListPlot : ListPlot[Button[Tooltip@#, Print[#]] & /@ N@data] Update 2: Collecting point coordinates: clicks = {}; Column[{ListPlot[Button[Tooltip@#, AppendTo[clicks, #]] & /@ N@data, ImageSize -> 300], "\n\t", Row[{"clicks = " , Dynamic[clicks // TableForm]}]}]
{ "source": [ "https://mathematica.stackexchange.com/questions/16931", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/4881/" ] }
17,046
I have a data set of x,y,z values and I fit a function of x,y to the data. This works, but I can't come up with a nice way to visualize the data. 3D plots are not very clear on paper and a contour plot of two data sets doesn't work either. What would be a clear and simple way to show the data and the fit? data = Import["https://pastebin.com/raw/mTUJAZrM"]; fit = NonlinearModelFit[ data, A*Exp[-(y - y0 - y1 Cos[2 (x/180*Pi)])^2/(w0 + w1 Cos[2 x/180*Pi])^2], {A, {y0, 0.04}, {y1, 0.00}, {w0, 0.03}, {w1, 0.01}}, {x, y} ]; Show[ ListPointPlot3D[data], Plot3D[fit["BestFit"], {x, 0, 180}, {y, 0, 0.1}] ] EDIT: What I decided to do for now is using a DensityPlot of the data with the ContourPlot of the fit (similar to Rahul Narain's answer). This does not really show the quality of the model, so I will add other plots, candidates are residuals vs. predicted values (similar to chris's answer) distribution of residuals (chris's answer) Q-Q plot using QuantilePlot[fit["FitResiduals"]] the plot Rahul Narain suggested
If what you want to visualize is how good the fit is, then you should do as @whuber suggests and plot the residuals, that is, the difference between the data and the fitted function. Below, each data point is drawn as a point with area proportional to the magnitude of the residual. Red means that the data value is higher than the fit; blue means the data is lower. For context, the contours of the fit are plotted in the background. residual[{x_, y_, z_}] := Evaluate[z - fit["BestFit"]] rmax = Max[(Abs@residual@#) & /@ data]; residualPoint[p : {px_, py_, pz_}] := Module[{r}, r = residual[p]/rmax; {AbsolutePointSize[10 Sqrt@Abs@r], ColorData["ThermometerColors"][(r + 1)/2], Point[{px, py}]}] Show[ContourPlot[fit["BestFit"], {x, 0, 180}, {y, 0, 0.1}, AspectRatio -> 1, ContourShading -> None], Graphics[Flatten[residualPoint /@ data]]] There does seem to be a little bit of systematic bias in the residuals. If I had to guess, I'd say the fitted function tends to overestimate the data at the left and right ends of the "ridge", and underestimates the data at the lower corners. And perhaps the ridge ought to form a narrower "V". However, I am not a statistician. Anyway, if you want to both visualize the shape of the fit and also indicate how far it is from the data simultaneously, you could lay these residual markers right on top of your 3D plot. residualPoint3D[p : {x_, y_, z_}] := Evaluate@Module[{r}, r = residual[p]/rmax; {AbsolutePointSize[2 + 8 Sqrt@Abs@r], ColorData["ThermometerColors"][(r + 1)/2], Point[{x, y, fit["BestFit"] + 1*^-5}]}] Show[Plot3D[Evaluate@fit["BestFit"], {x, 0, 180}, {y, 0, 0.1}, Mesh -> 5, MeshFunctions -> {#3 &}, MeshStyle -> Gray, Lighting -> {{"Ambient", White}}], Graphics3D[Flatten[residualPoint3D /@ data]]]
{ "source": [ "https://mathematica.stackexchange.com/questions/17046", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1967/" ] }
17,112
I am now struggling to understand code that contains the following (simplified) Manipulate structure. Manipulate[ complexparts[E^(I Pi t)], {{t, 1/4.}, 0., 2}, {{complexparts, {Re[#], Im[#]} &}, None}] I am having difficulty with the last line: {{complexparts, {Re[#], Im[#]}&}, None} . Somehow, this creates a "pure function" with a name "complexparts," which is then used above in the line complexparts[E^(I Pi t)] I tried to execute these independently outside the body of code so I could watch them do what they do, but without success. I evaluated: {{complexparts, {Re[#], Im[#]} &}, None} and then: complexparts[x+Iy] But my output was just: complexparts(x+I y) Can I get some help in understanding how {{complexparts, {Re[#], Im[#]} &}, None} works? And what does the word None do?
What the first part of the variable declaration does Manipulate initializes complexparts to {Re[#], Im[#]} & when it executes. (In general, a declaration of the form {{var, expr},...} in a Manipulate results in the local variable var being initialized to expr .) To use complexparts outside of the Manipulate , do this: complexparts = {Re[#], Im[#]} &; With[{θ = 0.25, b = 0.5 + 0.2 I}, complexparts /@ {E^(I π θ), b E^(-I π θ), E^(I π θ) + b E^(-I π θ), 0}] (* {{0.707107, 0.707107}, {0.494975, -0.212132}, {1.20208, 0.494975}, {0, 0}} *) Addendum 1 -- What "None" does To illustrate @Mr.Wizard's remark about Initialization , one could modify @David's code above as follows: Manipulate[ complexparts[E^(I Pi t)], {{t, 1/4.}, 0., 2}, {complexparts, None}, Initialization :> (complexparts = {Re[#], Im[#]} &) ] The declaration {complexparts, None} declares complexparts to be a local variable of the DynamicModule that is created by the Manipulate command. Whether complexparts needs to be declared local or not doesn't seem important in such an example. Generally I try to localize variables whenever possible, especially in Manipulate , as it saves headaches if you're doing scratch work in the same kernel that the Manipulate uses. Since the intended scope of complexparts is entire body of the Manipulate (and furthermore, it never changes), declaring it as a variable in a Manipulate seems appropriate. It hardly matters here, but in some cases it can make a big difference. Update -- Reference to the manual I have found a passage in the manual which I believe documents the usage of None . There are two alternatives for specifying a control type {u, ..., ControlType -> type} or more briefly (u, ..., type} This last one is not described but is used frequently in the examples. Technically it has the form {u, ..., func} where func is a function that constructs the control; however, since None is not a function, one can object that None must be treated as a special case. On the other hand, the reference page state Possible control types include: Animator .... None can also be used. The effect of a variable declaration is described thus: Manipulate generates a DynamicModule object, with the variables u, v, etc. specified as local. While the manual does not clearly state that {u,..., None} is accepted usage, it does state that what is practically equivalent, {u,..., ControlType -> None} is: Use ControlType to specify the type of control to use, including None : Manipulate[u, {u, 0, 1}, ControlType -> None] Addendum 2 -- "None" and other alternatives In response to the updated title for @David's question, as well as to some of the comments, the following might be worth studying to see the differences. Problem. We need the variable var to be local. It takes a long time to compute its value. It won't change its value, but we need to dynamically access the value (or parts of the value). As an example, var is to be a list of squares and the "long time" is simulated by Pause[0.2] . We wish to display part n of var with the slider for n . The solutions below all do the "same" thing. But there are differences in how each works. Depending on what one is trying to do, the differences can be significant. In my opinion, #1 is the best; the others can be fine in appropriate situations. I'll explain below. (* 1 *) Manipulate[ var[[n]], {n, 1, 10, 1}, {{var, Table[Pause[0.2]; n^2, {n, 10}]}, None} ] (* 2 *) Manipulate[ var[[n]], {n, 1, 10, 1}, {var, None}, Initialization :> (var = Table[Pause[0.2]; n^2, {n, 10}]) ] (* 3 *) Module[{var = Table[Pause[0.2]; n^2, {n, 10}]}, Manipulate[ var[[n]], {n, 1, 10, 1} ] ] (* 4 *) Manipulate[ Module[{var = Table[Pause[0.2]; n^2, {n, 10}]}, var[[n]]], {n, 1, 10, 1} ] The most important thing to ask is when is var calculated in each solution above: Once when the input cell is first evaluated. Every time the Manipulate output is (re)activated. For instance, every time the notebook is opened. Once when the input cell is first evaluated. (Same as #1.) Every time n changes value. This is terrible. The second question is where is var stored: In the output cell (in the notebook) and loaded into the kernel. Can make a very big notebook file, but the data is persistent. In the output cell l (in the notebook) as in 1 (and overwritten by the Initialization code). Correction due to @unlikely. Just in the kernel, when the input cell is evaluated. (Note the difference in #1.) In the kernel, after recalculation. Next, does the output work when the notebook is reopened? Will it work as a CDF? As a Wolfram Demonstration? (Each has the same answer for a given solution): 1, 2, 4: Yes. 3: No. (Even if var were made global, a Demonstration must have Manipulate as the outside function.) So in summary, Fast, fast on re-open of notebook, quick start-up in a CDF. Fast, slow on re-open, slow start-up in a CDF. (Change pause to 5 seconds, and you'll see a problem.) Fast, won't work on reopen, won't work in a CDF. Super slow all the time. Now what's going on? In #1, the data is computed first and fed to Manipulate , which stores in the output. That's what happens in {{var, initial_value},..} . In #2, the Initialization code is stored unevaluated in the output. Every time the output cell is activated (by opening the notebook and scrolling to the cell), the Initialization code is evaluated. In #3, a local variable is first created in the kernel and initialized; the local id for var is stored in the Manipulate output. When the notebook is reopened, this id is invalid. You have to reevaluate the input again to get it to work. In #4, a new local variable is created every time the Manipulate is updated (on start-up and every time a control is moved or a tracked variable changes); the variable is then initialized, so this can cost a lot a time. When the initialization time is short, you won't really notice the difference between #1, #2, and #4.
{ "source": [ "https://mathematica.stackexchange.com/questions/17112", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5183/" ] }
17,127
Solve and Reduce both can be used for solving equations. Just by working with them, I know there are some differences between them. but that is about all I know, and I want to know what the differences are. Could someone teach me about this?
In Some Notes on Internal Implementation especially in Algebra and Calculus one finds interesting subtleties and differences between these two functions, e.g. The code for Solve and related functions is about 500 pages long. Reduce and related functions use about 350 pages of Mathematica code and 1400 pages of C code. There is much more than a little difference between them. The most important is : Reduce returns results of computation as boolean formulae and gives complete description of solution sets. Solve returns lists of replacement rules yielding generic solutions. An important step toward more complete description of solution sets was a new option of Solve in Mathematica 8 , namely MaxExtraConditions (default value 0 ). Using MaxExtraConditions -> All in Solve provides complete solutions for algebraic equations, nevertheless we have to emphasize that sometimes we might better work with Reduce rather than Solve (regardless of any options added) because replacement rules may appear not a good fit in description of solutions in the real or complex domain to algebraic equations as well as to trancendental equations˛ Distinction between genericity and completness does not make sense in the Integers , an example provided below. Solve[expr,vars] assumes by default that quantities appearing algebraically in inequalities are real, while all other quantities are complex. We have the same issue with Reduce[expr,vars]. Example : Solve cannot find solutions in the real domain Consider a simple symbolic case in the real domain where Solve does not work even with MaxExtraConditions -> All : Solve[ x^2 + y^2 <= r^2, {x, y}, MaxExtraConditions -> All] Solve::fdimc: When parameter values satisfy the condition r ∈ Reals, the solution set contains a full-dimensional component; use Reduce for complete solution information. >> {} Reduce[ x^2 + y^2 <= r^2, {x, y}] r ∈ Reals && ((x == -Sqrt[r^2] && y == 0) || (-Sqrt[r^2] < x < Sqrt[r^2] && -Sqrt[r^2 - x^2] <= y <= Sqrt[r^2 - x^2]) || (x == Sqrt[r^2] && y == 0)) We have found none solutions with Solve . We should remember that we can find instances in the real domain with : fi = FindInstance[ x^2 + y^2 <= 9, {x, y}, 5] {{x -> 83/84, y -> 31/18}, {x -> 3, y -> 0}, {x -> 83/84, y -> (13 Sqrt[335])/84}, {x -> 5/28, y -> -(Sqrt[7031]/28)}, {x -> 37/21, y -> (10 Sqrt[26])/21}} However for the same inequality we can find all solutions with Solve in the integers. Example : Solve provides solutions in the integer domain s = {x, y} /. Solve[ x^2 + y^2 <= 9, {x, y}, Integers]; r = (List @@@ List @@ Reduce[ x^2 + y^2 <= 9, {x, y}, Integers])[[All, All, 2]] r == s True Here the blue region represents solutions described by Reduce while the red points on the left plot are instances found with FindInstance in the real domain, whereas on the right plot there are all solutions found by Solve in the Integers : GraphicsRow[{ RegionPlot[ x^2 + y^2 <= 9, {x, -5, 5}, {y, -5, 5}, Epilog -> {Red, PointSize[0.015], Point[fi[[All, All, 2]]]}], RegionPlot[ x^2 + y^2 <= 9, {x, -5, 5}, {y, -5, 5}, Epilog -> {Red, PointSize[0.015], Point[s]}]}] Example : Genericity can be advantageous for symbolic transcendental equations Genericity of Solve output sometimes can be advantageous, e.g. compare Solve[ x^c == 5, x] Solve::ifun: Inverse functions are being used by Solve, so some solutions may not be found; use Reduce for complete solution information. >> {{x -> 5^(1/c)}} Solve yields this solution immediately, while Reduce after ~ 10 seconds yields a huge boolean formula, here is a little part of it : Reduce[ x^c == 5, x][[3, 2]] C[1] <= -1 && (2 π C[1] - Sqrt[4 π ^2 C[1]^2 + Log[5]^2])/( 2 π ) < Re[c] < 2 C[1] && Im[c] <= (-Log[5] - Sqrt[ Log[5]^2 + 8 π ^2 C[1] Re[c] - 4 π ^2 Re[c]^2])/(2 π ) && x == E^((2 I π C[1] + Log[5])/c) There are another examples where we would rather use Reduce rather than Solve with specification MaxExtraConditions -> All because a list of replacement rules cannot express the full solution unlike a boolean form. Example : Solve cannot find the complete solution set Even with MaxExtraConditions -> All option Solve sometimes fails which may be seen when we work e.g. with real variables, e.g. : Normal @ Solve[ a x^2 == c && b x^3 == d, x, Reals, MaxExtraConditions -> All] Solve::fdimc: When parameter values satisfy the condition d == 0 && b== 0 && c == 0 && a == 0, the solution set contains a full-dimensional component; use Reduce for complete solution information. >> {{x -> 0}, {x -> -Sqrt[(c/a)]}, {x -> Sqrt[c/a]}, {x -> Root[-d + b #1^3 &, 1]}} We have used here Normal to get rid of ConditionalExpressions . Reduce[ a x^2 == c && b x^3 == d, x, Reals] For a nice discussion of these topics see this presentation Getting the Most from Algebraic Solvers in Mathematica by Adam Strzeboński during Wolfram Technology Conference 2011 . Example : Further issues Solve yields exlicit formulae for the solutions (in terms of radicals) to equations whenever it is possible (it is always possible for univariate algebraic (polynomial) equations up to the order four). For more detailed discussion see e.g. : How do I work with Root objects? . You can find more specific differences examining carefully this : Options /@ {Reduce, Solve} // Column { Backsubstitution -> False, Cubics -> False, GeneratedParameters -> C, Method -> Automatic, Modulus -> 0, Quartics -> False, WorkingPrecision -> Infinity} { Cubics -> True, GeneratedParameters -> C, InverseFunctions -> Automatic, MaxExtraConditions -> 0, Method -> Automatic, Modulus -> 0, Quartics -> True, VerifySolutions -> Automatic, WorkingPrecision -> Infinity } And even more systematic discussion of the differences might include SystemOptions["ReduceOptions"] . For some sketches of their usage take a look at this reference Real Polynomial Systems . SystemOptions["ReduceOptions"] // Short[#, 5] & { "ReduceOptions" -> {"ADDSolveBound" -> 8, "AlgebraicNumberOutput" -> True, "BDDEliminate" -> Automatic, "BooleanInstanceMethod" -> Automatic, <<21>>, "UseNestedRoots" -> Automatic, "UseOldReduce" -> False, "UseTranscendentalRoots" -> Automatic, "UseTranscendentalSolve" -> True}} These issues could be systematically discussed only with concrete examples, so that the main question has to be investigated on a case-by-case basis. See e.g. Solving/Reducing equations in $\mathbb{Z}/p\mathbb{Z}$ for a discussion of ExhaustiveSearchMaxPoints . Edit Another answer by Itai Seggev says that by specifying Method -> Reduce in Solve , Solve will use Reduce behind the scenes to produce an answer. That is not quite true. Here is an example : Solve with Method -> Reduce gives a different result than Reduce . Another statement therein not precise or incorrect is : " Reduce can deal with the following logical conjunction of inequalities, while Solve cannot." Solve works well with logical conjunction of inequalities (see e.g. Solve an equation in $\mathbb{R}^+$ ), let's slightly modify the system : Solve[ x^2 < 1 && Sin[x] == Cos[x], x] Reduce[ x^2 < 1 && Sin[x] == Cos[x], x] Reduce[x^2 < 1 && Sin[x] < Cos[x], x] {{x -> -2 ArcTan[1 - Sqrt[2]]}} x == -2 ArcTan[1 - Sqrt[2]] -1 < x < -2 ArcTan[1 - Sqrt[2]] whereas the issue here is just mentioned above that the solution set contains a full-dimensional component (in the real domain). For comparison let's see how it works in the integer domain : Solve[ x^2 < 2 && Sin[x] < Cos[x], x, Integers] Reduce[ x^2 < 2 && Sin[x] < Cos[x], x, Integers] {{x -> -1}, {x -> 0}} x == -1 || x == 0
{ "source": [ "https://mathematica.stackexchange.com/questions/17127", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/2371/" ] }
17,242
Let's say I have a list: {a, b, c} I would like to, for say $n=2$ get every distinct pair from that list. That is, the expected result should be, for some function choose : choose[{a, b, c}, 2] (* {{a, b}, {a, c}, {b, c}} *) My attempt at this was like so: choose[list_, n_] := DeleteDuplicates[Permutations[list, {n}], Union[#1, #2] == #1 &] And it does give the expected result for this example. There are, however, some problems in which I would like some help addressing: Permutations creates more combinations that I need, which forces me to use DeleteDuplicates . Is there away to directly arrive at all combinations? The DeleteDuplicates operation is very costly. Is there a way I could use the structure of the Permutations result to my advantage to get rid of the unwanted repeats? My function DOES make an error when there are supposed to be intended repeats. For instance, choose[{b, b, c}, 2] should give {{b,b}, {b, c}, {c, b}} - as every element in the list is considered "distinct" even though the values could be equal - but instead, the duplicate deletion removes the {c, b} . EDIT I have figured out a way to address #3. If I create a symbolic list tempList in which every element is unique, then replace that with the list, I am able to preserve "distinct" combinations even though they have the same value: choose[list_, n_] := With[{tempList = Array[Unique[] &, Length@list]}, DeleteDuplicates[ Permutations[tempList, {n}], Union[#1, #2] == #1 &] /. Thread[tempList -> list]] However, there's still room for improvement as having to use the replacement is not great for larger list lengths and values of $n$.
I think there is a built-in function for what you need: Subsets[{a, b, c, d}, {2}]
{ "source": [ "https://mathematica.stackexchange.com/questions/17242", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1611/" ] }
17,249
I would like to create a CDF document that uses dynamic content. The example code is: fun=x^2-1; InputField[Dynamic[fun]] And what I get is $Aborted instead of interactive document. How to make a useful document? EDIT: What I am really trying to do is to make a CDF document in which the given function is plotted. Initially the function is x^2-1, but the user should be able do input any function.
I think there is a built-in function for what you need: Subsets[{a, b, c, d}, {2}]
{ "source": [ "https://mathematica.stackexchange.com/questions/17249", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/742/" ] }
17,250
For example: p = Plot[Sin[x], {x, 0, 1}] Is it possible to write options in Show to change the curve's color for example into red? Show[p, (* Option?? *)]
I already answered this question on StackOverflow but since old questions can no longer be migrated without undue trouble I shall reproduce my answer here. There are two different categories of graphical objects in a Plot output. The plotted lines of the functions ( Sin[x] , Cos[x] ) and their styles are "hard coded" into Line objects, which Graphics can understand. Auxiliary settings such as Axes -> True , PlotLabel -> "Sine Cosecant Plot" and AxesStyle -> Orange are understood by Graphics directly, without conversion, and therefore remain within the myplot object. The second kind of settings can be easily changed after the fact because they are soft settings. (e.g. Show[p, (* options *)] The first kind much be processed in some way. This is complicated by the fact that different *Plot functions output different patterns of Graphics and Plot itself may give different patterns of output depending on the input it is given. I am not aware of any global way to restyle all plot types, and if you do such restyling often, it probably makes more sense to retain the data that is required and simply regenerate the graphic with Plot. Nevertheless, for basic uses, your method can be improved. Each function plotted creates a Line object, in the given order. Therefore, you can use something like this to completely restyle a plot: myplot = Plot[{Cos[x], Sin[x]}, {x, 0, 2 Pi}, PlotStyle -> {{Red, Dashing[None]}, {Green, Dashing[None]}}] newstyles = Directive @@@ { {Green, Thickness[.02], Dashing[Tiny]}, {Thickness[Large], Red} }; i = 1; MapAt[# /. {__, ln__Line} :> {newstyles[[i++]], ln} &, myplot, {1, 1}] Please note the part {1, 1} in the last line of code above. This is the part specification for the location of the Line objects within myplot . It is specified so as not to accidentally style Lines that might appear in other parts of the Graphics object. This part may need to be changed; for example when using Filling the Lines end up in {1, 2} . For this reason in the function below I simply used 1 which will be more flexible but could conceivably conflict with something. Restyle function The method above can be made into a self-contained function. I will use this method to cycle the styles given. restylePlot[plot_Graphics, styles_List, op : OptionsPattern[Graphics]] := Module[{x = styles}, Show[ MapAt[# /. {__, ln__Line} :> {Directive @ Last[x = RotateLeft@x], ln} &, plot, 1], op ]] Example: myplot2 = Plot[Evaluate[Table[BesselJ[n, x], {n, 4}]], {x, 0, 10}, Filling -> Axis] restylePlot[myplot2, { {Green, Thickness[.02], Dashing[Tiny]}, {Thickness[Large], Red}, Blue }, Axes -> False, Frame -> True, FrameStyle -> Directive[20, FontColor -> Orange] ] You will notice that the filling styles have not changed. While it is possible to change these by using GraphicsGroup in place of Line in the replacement rule the structure is considerably more complex to the point of being inconvenient. (It would probably be better to use the Graphics Inspector, or preferably to regenerate the graphic.) Graphics Inspector While I personally tend to avoid extensive after-Plot restyling because I like to keep everything in one place (the Plot command), and I prefer to make what changes I do with code so that there is a record of my settings without having to dig into the Graphics object, the Graphics Inspector is directly applicable. Double click the plot. The border should change from orange to thick gray. Single click one of the plot lines. (the pointed should change when you hover over an element) Press Ctrl + g to open the Graphics Inspector. Make the changes you desire, and close the Graphics Inspector. You can now copy and paste the entire graphic, or directly assign it to a symbol: p = <graphic> Also see: https://reference.wolfram.com/language/howto/EditWolframLanguageGraphics.html Tangentially related: How to change the default ColorData used in Mathematica's Plot? Filling Styles using a single Plot in Mathematica
{ "source": [ "https://mathematica.stackexchange.com/questions/17250", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/4742/" ] }
17,260
I have a set of data that looks like {{x1, y1, z1}, {x2, y2, z2}, ...} so it describes points in 3D space. I want to make a heatmap out of this data. So that points with a high density are shown as a cloud and marked with different colors dependend of the density. In fact, I want the result of this script just for 3D: data = RandomReal[1, {100, 2}]; SmoothDensityHistogram[data, 0.02, "PDF", ColorFunction -> "Rainbow", Mesh -> 0]
If you want to plot a distribution that is three dimensional then first you need to form it! SmoothDensityHistogram plots a smooth kernel histogram of the values $\{x_i,y_i\}$ but as we have three dimensional data here we need the function called SmoothKernelDistribution ! data = RandomReal[1, {1000, 3}]; dist = SmoothKernelDistribution[data]; Now you have got the probability distribution with three variables. So we can simply plot the PDF as a 3d contour plot using ContourPlot3D . Keep in mind that this function is reputed to be little slow. ContourPlot3D[Evaluate@PDF[dist, {x, y, z}], {x, -2, 2}, {y, -2, 2}, {z, -2, 2}, PlotRange -> All, Mesh -> None, MaxRecursion -> 0, PlotPoints -> 160, ContourStyle -> Opacity[0.45], Mesh -> None, ColorFunction -> Function[{x, y, z, f}, ColorData["Rainbow"][z]], AxesLabel -> {x, y, z}] To cut through the contours I used the option! RegionFunction -> Function[{x, y, z}, x < z || z > y] In order to check that the data points density is responsible for the shape of the contours we can use Graphics3D pic = Graphics3D[{ColorData["DarkRainbow"][#[[3]]], PointSize -> Large, Point[#]} & /@ data, Boxed -> False]; Show[con, pic] BR EDIT To follow up on the 2D example and get warm colours for higher densities data = RandomReal[1, {500, 3}]; dist = SmoothKernelDistribution[data]; ContourPlot3D[Evaluate@PDF[dist, {x, y, z}], {x, -2, 2}, {y, -2, 2}, {z, -2, 2},PlotRange -> All, Mesh -> None, MaxRecursion -> 0, PlotPoints -> 150,  ContourStyle -> Opacity[0.45], Contours -> 5, Mesh -> None, ColorFunction -> Function[{x, y, z, f}, ColorData["Rainbow"][f/Max[data]]],  AxesLabel -> {x, y, z}, RegionFunction -> Function[{x, y, z}, x < z || z > y]]
{ "source": [ "https://mathematica.stackexchange.com/questions/17260", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5281/" ] }
17,272
I am experiencing some rather large performance decreases in Mathematica version 9.0 using the xkcd-styled plotting routines. I had used the xkcdConvert code from Simon Woods as seen here (also described/annotated by Vitaliy Kaurov, as seen here ) a few months back under version 8.0.4. This code worked great under version 8.0.4 and ran the following sample code in about 1.68 seconds : f1[x_] := 5 + 50 (1 + Erf[x - 5]); f2[x_] := 20 + 30 (1 - Erf[x - 5]); xkcdConvert[ Plot[{f1[x], f2[x]}, {x, 0, 10}, Epilog -> xkcdLabel /@ {{"Label 1", {1, f1[1]}, {1, 30}}, {"Label 2", {8, f2[8]}, {0, 30}}}, Ticks -> {{{3.5, "1st Event"}, {7, "2nd Event"}}, Automatic}]] // AbsoluteTiming This code will produce a simple xkcd-styled plot as given by Simon Woods example. When I run the same code under version 9.0, the output takes ~17.0 seconds to produce!? I'm not sure why the performance degradation is happening in version 9.0. I was hoping to produce a number of comic styled plots for a meeting. I have produced the desired plots, but all the plot-rendering took a really long time (one plot took ~8 minutes to render). I welcome insight on how to improve the rendering performance under version 9.0 for future rendering efforts!
By the power of CUDALink and a CUDA-enabled GPU, this code drastically increases the speed of xkcdDistort by almost 120x. It takes circa 60s to transform a 400 × 400 image using xkcdDistort on my laptop (i5-2410M + NVIDIA GT540M + 4GB memory), and CUDAxkcdDistort can do the same in just 0.5s. Distortion of a 1000 × 1000 image takes just 2.5s. Needs["CUDALink`"] CUDAxkcdDistort[p_, s_List, blockDim_Integer] := Module[{ code = "#include<math.h> __global__ void CUDATransform( float * in, float * out , float * \ aux , int width, int height, int channels, int distort ) { int Index = threadIdx.x + blockIdx.x * blockDim.x ; int xIndex = Index % width ; int yIndex = Index / width ; if ( xIndex >= width || yIndex >= height ) return ; int xfrom , yfrom ; int xfetch , yfetch ; int from , to , ii; xfrom = xIndex + yIndex * width ; yfrom = ( width - 1 - xIndex ) + ( height - 1 - yIndex ) * width ; xfetch = (int) ceil( xIndex + aux[xfrom] * distort ) ; yfetch = (int) ceil( yIndex + aux[yfrom] * distort ) ; if ( xfetch > 0 && xfetch < width && yfetch > 0 && yfetch < height ) { from = xfrom * channels; to = ( xfetch + yfetch * width ) * channels; for ( ii = 0 ; ii < channels ; ii++) out[ from + ii ] = in [ to + ii ]; } }", func, InMem, OutMem, AuxMem, width, height, pad = 15, channels, distort = 20, result}, func = CUDAFunctionLoad[code, "CUDATransform", { {"Float"}, {"Float"}, {"Float"}, "Integer32", "Integer32", "Integer32", "Integer32" }, {blockDim, 1, 1}, TargetPrecision -> "Single"]; If[ImageQ[p], InMem = ImagePad[p, pad, Padding -> White], InMem = ImagePad[Rasterize[p, ImageSize -> s], pad, Padding -> White]]; {width, height} = ImageDimensions[InMem]; channels = ImageChannels[InMem]; InMem = CUDAMemoryLoad[Flatten[ImageData[InMem]], "Float"]; OutMem = CUDAMemoryLoad[Flatten[ParallelTable[1, {i, height}, {j, width},{k,channels}]], "Float"]; AuxMem = CUDAMemoryLoad[Flatten[ImageData[CUDAImageConvolve[RandomImage[{-1, 1},{width, height}], GaussianMatrix[10]]]], "Float"]; CUDAMemoryCopyToDevice[InMem]; CUDAMemoryCopyToDevice[OutMem]; CUDAMemoryCopyToDevice[AuxMem]; func[InMem, OutMem, AuxMem, width, height, channels, distort];result = ImagePad[Image[Partition[Partition[CUDAMemoryGet[OutMem], channels], width]], -3]; CUDAMemoryUnload[InMem]; CUDAMemoryUnload[OutMem]; CUDAMemoryUnload[AuxMem]; Return[ImageAdjust@GaussianFilter[result, 1]];]; CUDAxkcdConvert[x_, s_List, blockDim_Integer] :=CUDAxkcdDistort[xkcdShow[x], s, blockDim];
{ "source": [ "https://mathematica.stackexchange.com/questions/17272", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/4636/" ] }
17,357
When I have entered some bad code and hit shift+enter before thinking about the perils of finite RAM my computer obviously starts suffering. I have found two options that usually lets me recover without rebooting or in other ways lose the entire notebook. The first is to switch to a shell and kill -9 the PID of MathKernel process. The other is to go to the menu Evaluation->Quit Kernel->Local (note that Alt+. and Alt+, are completely ignored by now), by the time I have reached that menu my computer is on its last breath and seconds are of utmost importance. It usually takes seconds just to render the "Do you really want to quit the kernel?" dialog box. I think I would have better success rate if it just quit the kernel as fast as possible. Can I disable this dialog box?
You can add this to your init file, (or just try it out for the current session). It will add a Quit to your key events. This Quit doesn't open a confirm dialog. FrontEndExecute[ FrontEnd`AddMenuCommands["MenuListQuitEvaluators", {MenuItem["AddMenu &Quit", FrontEnd`KernelExecute[ToExpression["Quit[]"]], MenuKey["q", Modifiers -> {"Control"}], System`MenuEvaluator -> Automatic]}]] ref. https://mathematica.stackexchange.com/a/6227/363 Alternatively, it can be added to MenuSetup.tr like so: Menu["Quit Local", { MenuItem["Quit Kernel", FrontEnd`KernelExecute[ToExpression["Quit[]"]], MenuKey["q", Modifiers -> {"Control"}], MenuEvaluator -> Automatic] }]
{ "source": [ "https://mathematica.stackexchange.com/questions/17357", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1517/" ] }
17,530
The legending functionality in versions 9 and higher is much easier to use than the PlotLegends package and other bespoke ways of creating legends in earlier versions. However, the vertical spacing between items is larger than I would like. How can I reduce this spacing? Changing the LegendMarkerSize option to a smaller number without changing the size specified in the LegendMarkers option just ends up cutting off the graphic. LegendMargins doesn't affect the inter-item spacing, only the space between the whole legend and other items. PointLegend[{RGBColor[1, 0, 0], RGBColor[0, 0, 1]}, {"Series 1", "Series 2"}, LegendMarkers -> {{"\[FilledCircle]", 20}, {"\[FilledCircle]", 20}}, LegendMarkerSize -> 19, LabelStyle -> {FontFamily -> "Arial", FontSize -> 20}]
It turns out that the Spacings option does exactly what is needed, even though its use in legend constructs such as PointLegend is not documented, and it shows as red text when you use it in those constructs. PointLegend[{Red, Blue}, {"Series 1", "Series 2"}, LegendMarkers -> {{"\[FilledCircle]", 20}, {"\[FilledCircle]", 20}}, Spacings -> {0.2, 0.2}, LegendMarkerSize -> 19, LabelStyle -> {FontFamily -> "Arial", FontSize -> 20}] This continues the tradition of undocumented options and functions in Mathematica. UPDATE (2) : the Spacings option is still marked with red text in version 10.0.1, 10.1 and 10.3 and 11.0 .
{ "source": [ "https://mathematica.stackexchange.com/questions/17530", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/8/" ] }
17,621
This is a system of equations of the Vietnamese Mathematical Olympiad 2013, the first day. Solve the system of equations $$\begin{cases} \sqrt{\sin^2 x + \dfrac{1}{\sin^2 x}} + \sqrt{\cos^2 y + \dfrac{1}{\cos^2 y}} = \sqrt{\dfrac{20y}{x+y}},\\ \sqrt{\sin^2 y + \dfrac{1}{\sin^2 y}} + \sqrt{\cos^2 x + \dfrac{1}{\cos^2 x}} = \sqrt{\dfrac{20x}{x+y}}. \end{cases}$$ I tried Reduce[{Sqrt[ Sin[x]^2 + 1/Sin[x]^2] + Sqrt[ Cos[y]^2 + 1/Cos[y]^2] == Sqrt[ 20 y/(x + y)], Sqrt[ Sin[y]^2 + 1/Sin[y]^2] + Sqrt[ Cos[x]^2 + 1/Cos[x]^2] == Sqrt[ 20 x/(x + y)]}, {x, y}, Reals] My computer runs more than ten minutes, but I have not received results.
For contest problems (and real mathematical work), brute-force application of Mathematica often does not suffice. The software is better used as a tool for discovery and understanding. This answer is intended to illustrate that process. Like Mathematica itself, people make progress by identifying and trandforming patterns. In this problem several strongly patterned features are evident. There are several ways we could characterize and exploit them, but I think the core ideas common to any successful attack will include some aspect of these two: On the left side of the equations we see four terms of the form $f(u) = \sqrt{u^2 + 1/u^2}$ where $u$ is variously equal to $\cos(x)$, $\cos(y)$, $\sin(x)$, and $\sin(y)$. On the right side of the equation we see two terms which are square roots of the form $20\frac{x}{x+y}$. Notice that these are homogeneous : simultaneously rescaling $x$ and $y$ will not change either fraction. We ought therefore to think of these terms as function of the ratio $r = x/y$. Let's write $g(r) = \sqrt{20 \frac{1}{1+r}}$, so that the two right sides are $g(r)$ and $g(1/r)$. Let's begin the Mathematica exploration, then, by implementing $f$ and $g$ and plotting their values so that we can understand how these functions behave. f[u_] := Sqrt[u^2 + 1/u^2]; g[r_] := Sqrt[20 / (1 + r)]; Plot[f[u], {u, 0, 1}, AxesOrigin -> {0, 0}] Plot[g[r], {r, -1, 3}, AxesOrigin -> {-1, 0}] Because this is a system of equations, we should expect to have to recombine them somehow. One's first thoughts would range among adding, subtracting, squaring, multiplying, and dividing them. Addition, subtraction, and division promise to be simplest and to exhibit the most symmetry. Taking addition to be the easiest, let's try it first. The sum of the two equations is $$\left(f(\sin x) + f(\cos y)\right) + \left(f(\sin y)+ f(\cos x)\right) = g(x/y) + g(y/x).$$ The left hand side clearly can be arranged to equal the sum of a function of $x$ and the same function of $y$: $$\left(f(\sin x) + f(\cos x)\right) + \left(f(\sin y) + f(\cos y)\right) = g(x/y) + g(y/x).$$ This is progress, because it indicates we should be studying two univariate functions, $f_0(t) = f(\sin t) + f(\cos t)$ and $g_0(r) = g(r) + g(1/r)$. Let us again ask Mathematica for visual help in understanding them: f0[t_] := f[Sin[t]] + f[Cos[t]]; g0[r_] := g[r] + g[1/r]; Plot[f0[t], {t, -\[Pi], \[Pi]}, AxesOrigin -> {-\[Pi], 0}, Ticks -> {Range[-\[Pi], \[Pi], \[Pi]/2]}] Plot[g0[r], {r, -1, 3}, AxesOrigin -> {-1, 0}] The really interesting and striking things that emerge from inspecting these plots are $f_0$ is periodic with period $\pi/2$. In retrospect, that's obvious and easy to prove. $f_0$ has a lower bound which, by virtue of the periodicity and symmetry of $f_0$, occurs at $\pi/4$ plus all integral multiples of $\pi/2$. It's easy to calculate, but let's confirm: f0[\[Pi]/4] $\sqrt{10}$ $g_0$ is defined only for non-negative values (which is trivial to show, now that we have seen it) and has an upper bound . We can find this using methods of calculus, but for now let's just consult Mathematica : Maximize[g0[r], r] $\left\{2 \sqrt{10},\{r\to 1\}\right\}$ It is now immediate that the left hand side of the sum of the equations cannot be any less than the minimum of $f_0(x)$ plus the minimum of $f_0(y)$; namely, $\sqrt{10} + \sqrt{10}$, and that the right hand side cannot be any greater than the maximum of $g_0(r)$; namely, $2 \sqrt{10}$. These values are equal! This, the key insight, is the climax of the analysis. It establishes that the sum of the two equations can be true if and only if $f_0(x)$ and $f_0(y)$ are simultaneously at a minimum and $g_0(x/y)$ is at a maximum (which Mathematica has indicated occurs uniquely when $x/y=r=1$). Thus, remembering the periodicity of $f_0$, $$x = y\ \text{ and }\ x = \pi/4 + n \pi/2 \quad (n \in \mathbb{Z})$$ are necessary conditions for any solution. Plugging these values into the original equations shows that they both hold: we have found all the solutions. Backtracking through this exploration will establish a program for proving the answer is correct. The only missing piece is finding the unique global minimum of $g_0$. This can be done in an elementary way (that is, without Calculus) by writing $t = \frac{1}{1+r}$, so that $g(r) = \sqrt{20}\sqrt{t}$ and $g_0(r) = \sqrt{20}\left(\sqrt{t} + \sqrt{1-t}\right)$. The common factor of $\sqrt{20}$ does not affect the position of the maximum. Concerning what's left, let $u = \sqrt{t}$ and $v = \sqrt{1-t}$. Then $u^2 + v^2 = 1$, showing that we need to maximize the linear form $u+v = (1,1)\cdot(u,v)$ along the unit circle. It is geometrically obvious (and easy to prove using a little vector arithmetic ) that the maximum occurs when $(u,v)$ is parallel to $(1,1)$, whence $u=v$, implying $t=1/2$ and then $r=1$, QED.
{ "source": [ "https://mathematica.stackexchange.com/questions/17621", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/2241/" ] }
17,671
Assuming I have two function: example 1: add[{x_, y_, z_}] := x + y - z add[{1, 3, 5}] If use pure function,I know I can write it as : Function[{x}, x[[1]] + x[[2]] - x[[3]]][{1, 3, 5}] example 2: fun[{a_, b_}, y_] := If[y~Mod~2 == 0, {a~Join~{y}, b}, {a, b~Join~{y}}] Fold[fun, {{}, {}}, Range@10] Fold[Function[{x, y}, If[y < 5, {Join[x[[1]], {y}], x[[2]]}, {x[[1]], Join[x[[2]], {y}]}]], {{}, {}}, Range[10]] I think this a little prolix with many "[[]]", can you tell me another simpler way? Updated Do[ If[i[[1]] < i[[4]] < i[[7]] && i[[1]]/(10 i[[2]] + i[[3]]) + i[[4]]/(10*i[[5]] + i[[6]]) + i[[7]]/(10 i[[8]] + i[[9]]) == 1, Print@i ], {i, Permutations[Range[9]]} ] // Timing {2.153, Null} ============ Do[If[(x /. {a_, b_, c_, d_, e_, f_, g_, h_, i_} :> a < d < g && a/(10 b + c) + d/(10 e + f) + g/(10 h + i) == 1), Print@x], {x, Permutations[Range[9]]}] // Timing {10.374, Null} (*can't compiled*) ============= Block[{a, b, c, d, e, f, g, h, i}, Do[ If[{a, b, c, d, e, f, g, h, i} = x; a < d < g && a/(10 b + c) + d/(10 e + f) + g/(10 h + i) == 1, Print@x], {x, Permutations[Range[9]]}] ] // Timing {2.543, Null} (*easy compiled*) (*If Module or Blcok within Do loop, Module will slower than Block *)
Preamble This is IMO a very good question. I will try to describe an approach based on code-generation, which in my view would allow one to get the most benefits of declarative rule-based-like definitions without essentially imposing eny limitations or introducing any inconsistencies. The resulting functions can also be Compiled . General solution via code generation and overloading Code As an alternative, one can overload Function , in the following way: Unprotect[Function]; Function[{left___, {syms__Symbol}, right___}, body_,atts_:{}] := Module[{var}, With[{ rules = Thread[# :> Evaluate[ Range[Length[#]]]] &@ Thread[HoldPattern[{syms}]] /. ind_Integer :> var[[ind]] }, Function @@ (Hold[{left, var, right}, body,atts] /. rules) ] ]; Protect[Function]; Since by itself, Function does not have such extended syntax, this should be reasonably safe. Usage You can then call: Function[{{x,y,z}},x+y-z] and what you get will look like (* Function[{var$28109},var$28109[[1]]+var$28109[[2]]-var$28109[[3]]] *) so that the above code does some code-generation for you. Your second example also works verbatim, without any modiication: Fold[ Function[{{a, b}, y},If[y~Mod~2 == 0, {a~Join~{y}, b}, {a, b~Join~{y}}]], {{}, {}}, Range@10] (* {{2, 4, 6, 8, 10}, {1, 3, 5, 7, 9}} *) Function's attributes can also be handled. The following, in particular, will do in-place modifications of a list passed as a first argument: lst = {0, 0, 0}; Function[{{a, b, c}, d, e, f}, a = d; b = e; c = f, HoldAll][lst, 1, 2, 3]; lst (* {1, 2, 3} *) again, with a transparent and easy to read syntax. Such behavior does not seem to be easy to reproduce in other approaches, at least without some loss of clarity / readability. Advantages of this scheme In my opinion, this scheme has a number of advantages w.r.t. other solutions, in particular those based on replacement rules. Some of them: Generality - it can handle all cases without any modifications to the body of the function, w.r.t. how you'd write it in a rule-based style. Support of function's attributes. No impedance mismatch with Function : since the result is good old pure function, it does not have any limitations or inconsistencies in terms of how it can be used (e.g. in Compile , see next item, but perhaps not only) Such functions can be Compile -d rather straightforwardly, which is described in the last section of the answer. Making it safer with a dynamic environment Since overloading built-in functions globally is generally a bad idea, you can make it safer by creating a local dynamic environment . Code This is done with Internal`InheritedBlock : ClearAll[withAddedFunctionSyntax]; SetAttributes[withAddedFunctionSyntax, HoldAll]; withAddedFunctionSyntax[code_] := Internal`InheritedBlock[{Function}, Unprotect[Function]; Function[{left___, {syms__Symbol}, right___}, body_, atts_:{}] := Module[{var}, With[{ rules = Thread[# :> Evaluate[ Range[Length[#]]]] &@ Thread[HoldPattern[{syms}]] /. ind_Integer :> var[[ind]] }, Function @@ (Hold[{left, var, right}, body,atts] /. rules) ] ]; Protect[Function]; code ]; Usage you can now execute the code in this environment: withAddedFunctionSyntax[Function[{{x,y,z}},x+y-z][{1,3,5}]] (* -1 *) Note that it is enough to execute only the part with your function definition in that environment, you can export it to a global one: fun= withAddedFunctionSyntax[Function[{{x,y,z}},x+y-z]] (* Function[{var$357},var$357[[1]]+var$357[[2]]-var$357[[3]]] *) fun[{1,3,5}] (* -1 *) Certain special cases, speed-ups and compilation As the OP rightly noted, using replacement rules presents also problems for speeding up and / or compiling the functions obtained that way. Here, I will use the OP's added example to show how one can speed up and also compile functions obtained via the procedure I proposed above. I will be using the global (less secure) version of the Function overloading for simplicity, but it is trivial to use also a dynamic environment. Problems with naive usage in loops etc First, let us try to run the naive version of the code: Do[ Function[{{a, b, c, d, e, f, g, h, i}}, If[a < d < g && a/(10 b + c) + d/(10 e + f) + g/(10 h + i) == 1, Print[{a, b, c, d, e, f, g, h, i}] ]][i], {i,Permutations[Range[9]]} ] // Timing I had to Abort[] this code, since it was taking way too long. And it is easy to understand why: since Do holds its arguments, the function expansion defined above was used at every function's invocation. Simple work-around: store a pure function in a variable The simplest way to deal with this problem is to define a function separately, and store in a variable, like so: fn = Function[{{a,b,c,d,e,f,g,h,i}}, If[a<d<g&&a/(10 b+c)+d/(10 e+f)+g/(10 h+i)==1,Print[{a,b,c,d,e,f,g,h,i}]]]; Do[fn[i],{i,Permutations[Range[9]]}]//Timing During evaluation of In[42]:= {5,3,4,7,6,8,9,1,2} (* {4.593750,Null} *) This however is not the most general way. General way out: adding function-expanding macro Another way would be to write a function-expanding macro. Here it is: ClearAll[functionExpand]; SetAttributes[functionExpand, HoldAll]; functionExpand[code_] := Unevaluated[code] /. f_Function :> With[{eval = f}, eval /; True] It uses Trott-Strzebonski in-place evaluation technique, described also here (see also the answer of WReach there), and here , to expand Function inside the code. With it, one can do: functionExpand[ Do[ Function[{{a,b,c,d,e,f,g,h,i}}, If[a<d<g&&a/(10 b+c)+d/(10 e+f)+g/(10 h+i)==1,Print[{a,b,c,d,e,f,g,h,i}]] ][i],{i,Permutations[Range[9]]} ] ]//Timing During evaluation of In[43]:= {5,3,4,7,6,8,9,1,2} (* {4.546875,Null} *) Compilation Let me now show how one would compile the code obtain in this way. The recipe is very simple - use functionExpand again. So, for example: compiled = functionExpand[ Compile[{{p, _Integer, 1}}, Function[{{a, b, c, d, e, f, g, h, i}}, If[a < d < g && a/(10 b + c) + d/(10 e + f) + g/(10 h + i) == 1, {a, b, c, d, e, f, g, h, i}, {} ]][p] ]] where I slightly changed the output so that we return rather than Print , and there are no calls to the main evaluator then. You can check that compiled contains only the byte-code instructions, so it all works. Now, this speeds things up quite a bit: Do[If[compiled[p]!={},Print[p]],{p,Permutations[Range[9]]}]//Timing During evaluation of In[36]:= {5,3,4,7,6,8,9,1,2} (* {0.890625,Null} *) This is not the end of the story, however. One improvement would be to compile to C. Another improvement is to compile entire loop as well: fullCompiled = Compile[{}, Do[If[compiled[p] != {}, Print[p]], {p, Permutations[Range[9]]}], CompilationOptions -> {"InlineCompiledFunctions" -> True} ]; One can also test that,apart from Print , we get byte-code instructions again (note that the option "InlineCompiledFunctions" was used). So, fullCompiled[]//Timing During evaluation of In[49]:= {5,3,4,7,6,8,9,1,2} (* {0.312500,Null} *) Finally, we can also inline external definitions: fullCompiledInlined = Compile[{}, Do[If[compiled[p] != {}, Print[p]], {p, Permutations[Range[9]]}], CompilationOptions -> { "InlineCompiledFunctions" -> True, "InlineExternalDefinitions" -> True }]; which gives another 2x speedup in this case: fullCompiledInlined[]//Timing During evaluation of In[50]:= {5,3,4,7,6,8,9,1,2} (* {0.187500,Null} *) So, we got a 20x speedup due to compilation. Compilation to C target would likely bring further speed enhancements. What I've shown here is the workflow involving the overloaded Function , and ways to speed up and / or compile code using it.
{ "source": [ "https://mathematica.stackexchange.com/questions/17671", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5379/" ] }
17,704
Wolfram|Alpha has a whole collection¹ of parametric curves that create images of famous people. To see them, enter WolframAlpha["person curve"] into a Mathematica notebook, or person curve into Wolfram|Alpha . You get a mix of scientist, politicians and media personalities, such as Albert Einstein, Abraham Lincoln and PSY: The W|A parametric people curves are constructed from a combination of trigonometric and step functions. This suggests that the images might have been created by parametrising a sequence of contours... which is backed up by some curves being based of famous photos, e.g., the W|A curve for PAM Dirac : is clearly based on the Dirac portrait used in Wikipedia : Here's a animation showing each closed contour of Abraham Lincoln's portrait as the plot parameter $t$ increases by $2\pi$ units: Since the functions are so complicated, I can't believe that they were manually constructed. For example, the function to make Abe's bow tie is (for $8\pi < t < 10\pi$) The full parametric curve for Abe has 56 such curves tied together with step functions and takes many pages to display. So my question is: How can I use Mathematica to take an image and produce a good looking "people curve"? Answers can start from line art and just automatically parametrise the lines or they can start from a picture/portrait and identify a set of contours that are then parametrised. Or any other (semi)automated approach that you can think of. ¹ At the time of posting this question, it has 37 such curves.
This now has been discussed in Wolfram blog posts by Michael Trott: Part 1: Making Formulas… for Everything — From Pi to the Pink Panther to Sir Isaac Newton Part 2: Using Formulas... for Everything — From Complex Analysis Class to Political Cartoons to Music Album Covers Part 3: Even More Formulas… for Everything—From Filled Algebraic Curves to the Twitter Bird, the American Flag, Chocolate Easter Bunnies, and the Superman Solid Here is one of the example apps from blog - go read it in full - fun! Don't miss the link to download the notebook with complete code and apps at the end of the blog.
{ "source": [ "https://mathematica.stackexchange.com/questions/17704", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/34/" ] }
17,707
Possible Duplicate: How to Combine Pattern Constraints and Default Values for Function Arguments First a simple example: define a function "add" with two arguments, and its second argument should be Positive and have a default value 1. addv1[x_, (y_:1)?Positive] := x + y; addv2[x_,y?Positive:1] := x + y; these two just don't work as expected. So is it impossible to use PatternTest and Optional value on one Pattern simultaneously, considering the probability of its default value conflicting with its pattern test?
The syntax The answer is yes. I use this construct all the time. Here is the form: add[x_, y : (_?Positive) : 1] := x + y; You can test that it passes all the test cases. Sutble behavior to watch out for There is one additional subtlety associated with this construct: the default value must match the pattern specified for the explicit argument. So, for example, this definition: Clear[addAuto]; addAuto[x_, y : (_?Positive) : Automatic] := x + y; won't work as expected: addAuto[1] (* addAuto[1] *) because Automatic does not match _?Positive . But this will: Clear[addAuto]; addAuto[x_, y : (_?Positive | Automatic) : Automatic] := x + y; addAuto[1] (* 1+Automatic *) So, make sure that your defualt value matches the explicit arg. pattern. Many, many hours did I waste debugging such cases, more than once. It is not something that first comes to mind. See some more discussion here .
{ "source": [ "https://mathematica.stackexchange.com/questions/17707", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1931/" ] }
17,736
I am new to Mathematica and I am trying to get to it to produce some expressions in Fortran code. However, it seems that Mathematica will output duplicated expressions, that is, expressions the need not be calculated more than once. Is there any good method to define a rule so that Mathematica will recognize duplicated expressions, assign them to a new variable, and then optimize the Fortran code? P.S: The following is some code I wrote to test Mathematica 's Fortran capabilities. The solution of x, y and z contains many duplicated expressions, for example, (-36*a + 20*a**3 - 216*b)**2. sol = Solve[{x^2 + y^2 + z^2 == 1, x + y + z == a , x*y*z == b}, {x, y, z}]; xx = x /. sol yy = y /. sol zz = z /. sol Print["Writing Fortran Code . . . : / "]; SetDirectory["F:\\tang\\mathtest"]; strm = OpenWrite["test.f90", FormatType -> FotranForm, PageWidth -> 70]; (* write subroutine of invisopar*) WriteString[strm, "subroutine test(x,y,z,a,b)\n"]; WriteString[strm, "implicit none\n"]; WriteString[strm, "real*8::x,y,z,a,b\n"]; nroot = Length[xx]; For[ii = 1, ii <= nroot, WriteString[strm, "x = " <> ToString[FortranForm[xx[[ii]]]] <> "\n"]; ii++]; For[ii = 1, ii <= nroot, WriteString[strm, "y = " <> ToString[FortranForm[yy[[ii]]]] <> "\n"]; ii++]; For[ii = 1, ii <= nroot, WriteString[strm, "z = " <> ToString[FortranForm[zz[[ii]]]] <> "\n"]; ii++]; WriteString[strm, "end subroutine\n"]; Close[strm]; Print["Finished Writing Fortran Code . . . : / "]; When the test.f90 is outputted, the first solution of x is: x = a/3. + (-6 + 2*a**2)/(3. 2 *0.6666666666666666*(-36*a + 20*a* 3 + Sqrt(4 (-6 + 2*a* 2) *3 + (-36*a + 20*a**3 - 216*b)**2) - 216*b)**0.3333333333333333) - (-36*a + 20*a* 3 + Sqrt(4 (-6 + 2*a* 2) *3 + (-36*a + 20*a**3 - 216*b)**2) - 216*b)**0.3333333333333333/(6. 2 *0.3333333333333333) I would like that the code is as follows: tmp0 = 216*b tmp1 = -36*a + 20*a**3 tmp2 = (tmp1 - tmp0 )**2 tmp3 = -6 + 2*a**2 tmp4 = 4*tmp3**3 tmp5 = Sqrt(tmp4 + tmp2 ) tmp6 = tmp1 + tmp5 - tmp0 tmp7 = tmp6**0.3333333333333333 tmp8 = 2**0.6666666666666666 x = a/3. + tmp3 /(3.*tmp8 *tmp7 ) - tmp7/(6.*tmp8) I noticed that maple has the capability for optimizing Fortran; for example, the following maple code can output optimized Fortran code: with(codegen, fortran) A := array(1 .. 2, 1 .. 2, symmetric); A[1, 1] := log(x); A[1, 2] := 1-log(x); A[2, 2] := 2-log(x); print(A); fortran(A, optimized, mode = double) So I want to know whether Mathematica also can do similar optimization.
OK, here's a quick go using Experimental`OptimizeExpression , which is used internally by Compile . I'm not claiming that this is a polished solution to your problem, but hopefully it can be used as a place to start. (Also, forgive any Fortran mistakes, I haven't looked at Fortran for a long time...) xx = x /. Solve[{x^2 + y^2 + z^2 == 1, x + y + z == a, x*y*z == b}, {x, y, z}] // First; Quiet[Remove["tmp*"]] (* otherwise the numbers after 'tmp' keep going up *) Module[{out}, out = Experimental`OptimizeExpression[xx, "OptimizationSymbol" -> tmp] /. HoldPattern[Experimental`OptimizedExpression[Block[{tempVars__}, CompoundExpression[defs : Set[_, _] ..., expr_]]]] :> Block[{ Set = ToString[#1] <> " = " <> ToString[FortranForm[#2]] &}, List[defs, expr]]; {"subroutine test(x,a,b)", "implicit none", "real*8::x,a,b", Most@out, "x = " <> ToString@FortranForm@N@Last@out, "end subroutine"} ] // Flatten // ExportString[#, "Table"] & subroutine test(x,a,b) implicit none real*8::x,a,b tmp4 = a**2 tmp5 = 2*tmp4 tmp6 = -6 + tmp5 tmp7 = -36*a tmp8 = a**3 tmp9 = 20*tmp8 tmp12 = -216*b tmp10 = tmp6**3 tmp11 = 4*tmp10 tmp13 = tmp12 + tmp7 + tmp9 tmp14 = tmp13**2 tmp15 = tmp11 + tmp14 tmp16 = Sqrt(tmp15) tmp17 = tmp12 + tmp16 + tmp7 + tmp9 x = 0.3333333333333333*a - 0.13228342099734997*tmp17**0.3333333333333333 + \ (0.20998684164914552*tmp6)/tmp17**0.3333333333333333 end subroutine This can easily be modified to process and output more than just the first solution for x and can also be made to export to a file instead of a string. It's not as compact as hand code would make it, some of the tmp definitions, I would join together, but it's not bad. Also, note that the other solutions for x contain complex numbers and might have to be treated a little more carefully.
{ "source": [ "https://mathematica.stackexchange.com/questions/17736", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5396/" ] }
17,767
Usually in programming languages, function arguments are normal local variables, which can be modified. Is this not true in Mathematica? In[94]:= TTT[x_] := Block[{}, x += 2 ]; In[95]:= TTT[3] During evaluation of In[95]:= AddTo::rvalue: 3 is not a variable with a value, so its value cannot be changed. >> Out[95]= 3 += 2 Is it possible to simulate normal argument behavior somehow?
Intro I will treat your question in a somewhat broader context of parameter-passing semantics in Mathematica in general. Many points of confusion here come from analogies and comparisons with more traditional languages, and it is important to realize that Mathematica uses entirely different (from most other languages) mechanisms for parameter-passing. Realizing this is not helped by the fact that there are significant syntactic similarities with other languages, however. Parameter - passing semantics in Mathematica : pass-by-value via code injection Parameter-passing semantics in Mathematica is different from many other languages. Parameters are passed by value, but if you dig deeper, functions are really rules, and parameters are simply injected into the body of a function, right before the body is evaluated. Depending on whether or not the function in question holds a particular argument, what is injected into its body is either the argument verbatim, or its value (meaning that the argument is first evaluated and only then injected, and then the body evaluates). Whether or not the expressions passed as arguments can be modified inside a function depends on whether or not they represent an L-value (meaning they can be assigned a value, e.g. via Set operator). I have a rather long section in my book which has a detailed discussion on that, but, to put the story short, for the following function: f[x_]:=x=1 this will assign to a : Clear[a]; f[a] while this will result in an error: a=2; f[a] because in the first case, the symbol a is injected into the r.h.s. (it is of course first evaluated, but since it does not have any value, it evaluates trivially, to itself), while in the second, it already has a value, so it's immutable value 2 is injected. Note however, that this "injection" parameter-passing mechanism is highly unusual, from the point of view of traditional languages. In essence, parameter-passing acts as a code-generation device, assembling full function's code in a macro-like fashion from code pieces passed as parameters and the body which has "placeholders" and acts like a macro. One can say that in Mathematica , run-time code generation happens at each function invocation. Emulating pass-by-reference via Hold -attributes When functions are given Hold -attributes, they can emulate pass-by-reference semantics since they inject their passed arguments into their bodies verbatim, without first evaluating them. Therefore, giving f the attribute HoldFirst (for example), will lead to assignments in both cases. ClearAll[f]; SetAttributes[f,HoldFirst]; f[x_]:= x = x + 5; a = 5; f[a]; a (* 10 *) f[a]; a (* 15 *) This is however only an emulation, since there are no pointers in Mathematica. One representative aspect of this emulation is that you can not "dereferece" a symbol holding a value. Nevertheless, for many tasks, such an emulation is sufficient. Getting the behavior similar to other languages (such as C) Finally, you can easily simulate the effect of local variables by assigning your passed parameters to Module or Block -local variables: TTT[x_] := Block[{xl=x}, xl += 2 ]; But in this case, the changes in those local variables will not affect the values of the parameters (just like this would be for function's parameters in C, for example). This behavior is probably the closest analog of how passed parameters belong in say C, where they are copied on the stack and become function's local variables. The topic of name conflicts for passed parameters and local variables in actually more complex, and some of the associated behavior may be not very easy to understand at first. Mathematica documentation has an extensive coverage of these topics. I also discussed this topic in some more (compared to this answer) details here . Summary Parameter-passing in Mathematica is very different from that of many more traditional languages, in terms of core mechanisms involved (rules, run-time code generation). However, the syntax and partly behavior may look pretty close to what we have in other languages. It is important to understand the core mechanisms behind Mathematica 's parameter-passing scheme, to better understand the differences and avoid unwanted surprises.
{ "source": [ "https://mathematica.stackexchange.com/questions/17767", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/430/" ] }
17,783
Suppose that I want to write a function fun that takes an Integer num as input, and returns Red if num == 1 , Orange if num == 2 , and Yellow if num == 3 . One way, I think, to do this is to use Which : fun[num_Integer] := Which[num == 1, Red, num == 2, Orange, num == 3, Yellow] Is there a more concise way to write fun ? In other words, is there any built-in function (analogous to Which ) that I can use that would allow me to avoid typing " num " all the time instead of always having to specify it to Which . Writing fun as a series of nested If statements would be even lengthier. Do you have any suggestions? Thanks for your time.
Not really a concise syntax, but you can also do this using Switch, which removes the need for writting the checking, and also allows patterns: fun[num_Integer] := Switch[num, 1, "Red", 2, "Orange", 3, "Yellow", _?PrimeQ, "Purple", _, "LightGray"] I used strings just to make the output nicer to verify the behavior. Naturally you would switch these to the actual colors. Style[#, fun@#] & /@ Range@20
{ "source": [ "https://mathematica.stackexchange.com/questions/17783", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1185/" ] }
17,841
A simple file reading issue is baffling me here. I am reading a around 200 MB textual file in .dat format. Now the file contains many lines but to phrase my problem I am taking here first two lines from the example file. str = "Tue 1 Jan 2013 23 : 00 : 01; 17; {}; 32.5; 0.\nTue 2 Jan 2013 2 : 20 : 01; 47; {3,4}; 3.5; 110."; Now I want to use ; and newline \n as my RecordSeparators and it works as expected. ReadList[StringToStream[str],{Record, Record, Record, Record, Record}, RecordSeparators -> {"\n", ";"}] {{Tue 1 Jan 2013 23 : 00 : 01, 17, {}, 32.5, 0.},{Tue 2 Jan 2013 2 : 20 : 01, 47, {3,4}, 3.5, 110.}} But if I want to specify the Type of each separate Record using for example {String, Number, Expression, Number, number} above code fails to work. The error is the following. Read::readn: Invalid real number found when reading from StringToStream[Tue 1 Jan 2013 23 : 00 : 01; 17; {}; 32.5; 0. Tue 2 Jan 2013 2 : 20 : 01; 47; {3,4}; 3.5; 110.]. >> Is this problem solvable or I need to change the formatting of my input .dat file in a way so that it works with ReadList ? PS: If I need to change the file format what will be best separator to use in this context?
Your problem is that you've got a slight misunderstanding of the different types of items that ReadList can read. That's OK, it can be a little confusing. To begin with: String , Number , Expression , etc. are not sub-types of Record . They are all separate types with their own rules for how they are read. The RecordSeparators option is only applied to Records and Words. Probably if you have some complicated input format whose parsing is best controlled by RecordSeparators/WordSeparators, you should just use Record/Word types, which will give you strings; afterwards, convert the ones you know to be numeric by using ToExpression . On the other hand, if you want to gain power over this area of Mathematica, read on. BASIC CONCEPTS OF READ Let's make up some terms to help explain things. At their base, the Mathematica functions Read , ReadList , and Skip read in ITEMS from an input stream. An Item is a number like 3.14159e-26 , or a string like "peg and awl" . There are different TYPES of Items: Record , Word , String , Number , Real , Character , and Byte . These Types correspond to either a string or a number, with different rules for how the input is parsed. There is also an Expression Type which corresponds to an Item which is a general Mathematica expression of any form. WHAT ARE THE ITEMS AND HOW DO THEY WORK? The simplest cases: a Character is a single character from the stream, represented as a one-letter string. a Byte is a single character from the stream, represented as an integer that is the Character Code of the character. Both Character and Byte have the same rule -- read one character -- but different representations, string vs. number. To describe the other Item Types, you need to understand that they are all assembled from sequences of characters read from the stream, with some particular character that marks their end. That character is not part of the Item being read! It is a TERMINATOR, or TERMINATING CHARACTER. We say that the Item was TERMINATED by a particular character in the stream. a Record is a string, a sequence of characters terminated by a RecordSeparator . a Word is a string, a sequence of characters terminated by a WordSeparator , RecordSeparator , or TokenWord . a String is a sequence of characters terminated by a newline ( \n character). Basically it's a LINE of text input, starting at the current stream position. a Number is any sequence of characters that can be interpreted as a number (in Fortran syntax), terminated by any character that can't be part of the number. Any whitespace (spaces, newlines, tabs) preceding the number is quietly skipped over first. a Real is the same as a Number but it's always a floating-point value, never an integer. an Expression is a sequence of one or more newline-terminated lines that form a parseable Mathematica expression. It's terminated by whatever newline ends the last line of the expression. If you've ever typed in a multi-line input to the raw text kernel, you know how this works. Records, Words, Strings, and Characters become Mathematica strings. Numbers, Reals, and Bytes become Mathematica numbers. Expressions become Mathematica expressions. Numbers, Reals, Strings, and Expressions pay no attention to RecordSeparators and WordSeparators. They have their own rules for when they stop taking characters from the stream. (The end of the stream, represented in Mathematica by the symbol EndOfFile , is nearly always a terminator. It's not a character, though.) OBJECTS: GROUPS OF ITEMS I have just told you the only Types of Items that can be read. However, there's another term that has to be introduced. The second argument of Read , ReadList , and Skip -- the input specification -- can be a complex expression which contains one or more of these Types. Let's call that an OBJECT. For instance, Read[stream, {String, Number, Plus[Number, Real], Hold[Expression]}] reads an Object: a sequence of five Items. Several of the Items are placed inside larger expressions, and the whole thing is placed inside a List head. The degenerate case of an Object is a single naked Item: ReadList[stream, Byte] If you don't specify a second argument to Read, ReadList, or Skip, it defaults to Expression. ReadList[stream] == ReadList[stream, Expression] Read, ReadList, and Skip proceed left to right through the Object; each Item Type they encounter causes an Item to be read from the stream. As I listed above, each Type has its own rules for how many characters it will snatch up, what it will do with them, and when it will stop. If you are constructing complex Objects consisting of several Item Types, you need to know especially when will each one stop . This requires understanding the TERMINATORS for each type. Just as importantly, you need to know what is done with those terminating characters. WHAT HAPPENS TO THE CHARACTERS THAT TERMINATE AN ITEM Terminating characters are not part of the Item that is read. They simply mark that Item's end in the stream. Different Types apply different rules to how they treat the terminator -- that is, where they leave the position of the stream pointer after they are done. Bytes and Characters don't have terminators, of course. Expressions have terminators that are newlines. The stream pointer is left sitting at the newline. An Expression like 1+2* 3/4- 5 has three newlines in it, at the end of each line. The newline after 5 is the terminator for this Expression, and after Read[stream, Expression] that character's position is the stream's position. StreamPosition[stream] == 11 . If you followed Read[Expression] with Read[Character] you'd get a \n . Strings also have newline terminators. But they CONSUME the newline, skipping over it, leaving the stream pointer after it. The newline character is not part of the String, but if you read a Character after reading a String you wouldn't get a \n , you'd get whatever is at the beginning of the next line. Numbers, like Expressions, do not consume their terminating characters. They leave the stream pointer at that character, whatever it is. For instance, if you read a Number and then a Character from "64+32*3" , the Number would be 64 , and the Character would be "+" . I think you can see why this is what you want. Records and Words leave the stream pointer pointing at whatever character terminated them. This character is a RecordSeparator or WordSeparator; only Records or Words care about those options. However, if you then read another Record or Word subsequently, the stream will first SKIP OVER the RecordSeparator or WordSeparator that the stream is pointing to, the terminator for the previous Record or Word. Then it will proceed to read the next Record or Word. (Exception: this skipping does not happen if you're about to Read another Word and the separator was a TokenWord .) If the input stream were an,a,tev,ka 0123456789 and RecordSeparators->"," , then reading one Record would give you "an" , and the stream position would be 2. If it reads another Record then it will skip the comma, move to position 3, and then read "a" . The stream position would be left at 4, the second comma. In general this is what you want. You want to be able to read multiple Records without having the terminating characters interfere, but you also want to be able to grab those characters if desired. You might have RecordSeparators->{"+", "-", "*", "/"} , and you need to inspect the Character after the Record to find out which particular separator stopped it. I hope this is an adequate explanation. I am not going to talk about Record and Word behavior when you have left-and-right matched delimiters as RecordSeparators or WordSeparators (like parentheses); nor NullRecords and NullWords ; nor RecordLists ; and there's one very useful special case where Numbers can consume RecordSeparator terminators. Please let me know if there's anything unclear and I'll hack on this response to make it unclearer.
{ "source": [ "https://mathematica.stackexchange.com/questions/17841", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/240/" ] }
17,926
Here is the example: Simplify[x + y, x + y == a] Simplify[x + y, x + y == 5] Mathematica 9 output: x+y 5 I expect the complexity of a to be lower than complexity of Plus[x,y] , and the result of the first line should be a . Even if I specify ComplexityFunction explicitly: Simplify[x + y, x + y == a, ComplexityFunction -> LeafCount] I still get x+y as a result. It's however obvious that LeafCount[x+y] is greater than LeafCount[a] . Why does Simplify ignore x+y==a but uses x+y==5 ? How can I define the former assumption in a right way?
We can see from the examples in the comments to the question that Simplify (and FullSimplify which builds on it) doesn't try all permutations of substitutions. That's probably justified in general to keep the computational effort from exploding, but in your example it leads to the quirky behavior that the variable names affect the result of the simplification. For example, you get Clear[a, z]; Simplify[x + y, x + y == a] (* ==> x + y *) Simplify[x + y, x + y == z] (* ==> z *) The only difference is that the last assumption uses a variable name that comes lexically after the names which you would like to replace. I think the reason for this is that Mathematica tries substitutions in sums only in a specific sequence dictated by the alphabetical order of the variables it encounters. My heuristic conclusion from this would be that assumptions in which you would like variables to be substituted by new names should have the new names chosen such that they come lexically after the "old" names. If this doesn't work for you, the best alternative would be to do the elimination explicitly using Eliminate .
{ "source": [ "https://mathematica.stackexchange.com/questions/17926", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5433/" ] }
18,034
Bug fixed in 13.0.0 The problem in general involves the unreliable behaviour of AbsoluteOptions when option values are implicitly specified (e.g. Automatic , All , Full , etc.), for example the graphics below clearly has a different plot range than the one reported by AbsoluteOptions : {g = Graphics[{}, Frame -> True], AbsoluteOptions[g, PlotRange]} Original example For demonstrating the problem, have a look at the following example, and try adjusting the rotation angle a and/or the Locator position, comparing the real PlotRange of pic indicated by the frame-ticks with the one under the graph obtained by AbsoluteOptions[pic, PlotRange] : Manipulate[ DynamicModule[{pic}, Column[{ pic = Graphics[{FaceForm[], EdgeForm[Black], GeometricTransformation[Rectangle[], RotationTransform[a]], Red, Point[p]}, Frame -> True], p, AbsoluteOptions[pic, PlotRange] }] ], {{a, 0}, 0, 2 Pi}, {{p, {.1, .2}}, {-2, -2}, {2, 2}, Locator}] As shown in the screen capture above, in my Mathematica 9.0 on Windows 7 64-bit system, the PlotRange from AbsoluteOptions is not consistent with the real range. And the angle a seems to do nothing with it. Additional tests in my system suggest this problem is not restricted to the presence of RotationTransform , but comes with the GeometricTransformation . And it happens not only on Graphics but also on Graphics3D . So my questions are: What is going on here? How can I obtain the real PlotRange of the Graphics / Graphics3D when there are GeometricTransformation s in it?
UPDATE In version 13.0.0 the described long-standing bug in determining PlotRange via AbsoluteOptions is fixed. Original answer AbsoluteOptions is known as very buggy function and the bug in determining the true PlotRange has very long history... You could try my Ticks -based workaround for getting the complete PlotRange (with PlotRangePadding added): completePlotRange[plot:(_Graphics|_Graphics3D|_Graph)] := Last@ Last@Reap[ Rasterize[ Show[plot, Axes -> True, Frame -> False, Ticks -> ((Sow[{##}]; Automatic) &), DisplayFunction -> Identity, ImageSize -> 0], ImageResolution -> 1]] Manipulate[ DynamicModule[{pic}, Column[{pic = Graphics[{FaceForm[], EdgeForm[Black], GeometricTransformation[Rectangle[], RotationTransform[a]], Red, Point[p]}, Frame -> True, PlotRangePadding -> 0], p, AbsoluteOptions[pic, PlotRange], completePlotRange[pic]}]], {{a, 4}, 0, 2 Pi}, {{p, {.1, -.6}}, {-2, -2}, {2, 2}, Locator}, ContinuousAction -> False, SynchronousUpdating -> False] EDIT One can get the exact PlotRange (without the PlotRangePadding added) with the following function: plotRange[plot : (_Graphics | _Graphics3D | _Graph)] := Last@ Last@Reap[ Rasterize[ Show[plot, PlotRangePadding -> None, Axes -> True, Frame -> False, Ticks -> ((Sow[{##}]; Automatic) &), DisplayFunction -> Identity, ImageSize -> 0], ImageResolution -> 1]] Manipulate[ DynamicModule[{pic}, Column[{pic = Graphics[{FaceForm[], EdgeForm[Black], GeometricTransformation[Rectangle[], RotationTransform[a]], Red, Point[p]}, Frame -> True], p, AbsoluteOptions[pic, PlotRange], plotRange[pic]}]], {{a, 4}, 0, 2 Pi}, {{p, {.1, -.6}}, {-2, -2}, {2, 2}, Locator}, SynchronousUpdating -> False] EDIT 2 Here is timing comparison of various ways to get real PlotRange : completePlotRange[plot : (_Graphics | _Graphics3D | _Graph)] := Last@ Last@Reap[ Rasterize[ Show[plot, Axes -> True, Frame -> False, Ticks -> ((Sow[{##}]; Automatic) &), DisplayFunction -> Identity, ImageSize -> 0], ImageResolution -> 1]] completePlotRange[plot : (_Graphics | _Graphics3D | _Graph), format_] := Last@ Last@Reap[ ExportString[ Show[plot, Axes -> True, Frame -> False, Ticks -> ((Sow[{##}]; Automatic) &), DisplayFunction -> Identity, ImageSize -> 0], format]] pic = Graphics[{FaceForm[], EdgeForm[Black], GeometricTransformation[Rectangle[], RotationTransform[.3]]}, Frame -> True]; Print[{#, AbsoluteTiming[ First@Table[ completePlotRange[pic, #], {100}]]}] & /@ {"RawBitmap", "BMP", "WMF", "EMF", "SVG", "PDF", "EPS"}; {RawBitmap,{2.8931655,{{-0.32158,0.981396},{-0.0250171,1.27587}}}} {BMP,{3.0201728,{{-0.32158,0.981396},{-0.0250171,1.27587}}}} {WMF,{4.3242473,{{-0.32158,0.981396},{-0.0250171,1.27587}}}} {EMF,{4.0182298,{{-0.32158,0.981396},{-0.0250171,1.27587}}}} {SVG,{3.1461800,{{-0.32158,0.981396},{-0.0250171,1.27587}}}} {PDF,{16.9799712,{{-0.32158,0.981396},{-0.0250171,1.27587}}}} {EPS,{7.3074179,{{-0.32158,0.981396},{-0.0250171,1.27587}}}} AbsoluteTiming[First@Table[completePlotRange[pic], {100}]] {2.3991372, {{-0.32158, 0.981396}, {-0.0250171, 1.27587}}} One can see that Rasterize with ImageSize -> 0 is the fastest. UPDATE 3 Here is purely Dynamic implementation of the same idea: plotRange[plot : (_Graphics | _Graphics3D | _Graph)] := Reap[NotebookDelete[ First@{PrintTemporary[ Show[plot, Axes -> True, Frame -> False, Ticks -> ((Sow[{##}]; Automatic) &), DisplayFunction -> Identity, PlotRangePadding -> None, ImageSize -> 0]], FinishDynamic[]}]][[2, 1]] completePlotRange[plot : (_Graphics | _Graphics3D | _Graph)] := Reap[NotebookDelete[ First@{PrintTemporary[ Show[plot, Axes -> True, Frame -> False, Ticks -> ((Sow[{##}]; Automatic) &), DisplayFunction -> Identity, ImageSize -> 0]], FinishDynamic[]}]][[2, 1]]
{ "source": [ "https://mathematica.stackexchange.com/questions/18034", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/17/" ] }
18,078
I wish to create an efficient circular buffer. That is, I wish to keep a fixed length list while appending a new value and dropping the oldest, repeatedly. As we know lists in Mathematica are implemented as arrays and Append etc. are slow on long lists. For example: big = Range@1*^7; Do[big = Append[Rest@big, RandomInteger@99], {100}] // AbsoluteTiming {2.2100031, Null} Internal`Bag and related functions are appropriate for a continually accumulating list but do not appear to be applicable to this situation. Is there an efficient means to have a large circular buffer in Mathematica ?
You can implement an imperative-style circular buffer. big = Range@1*^7; size = Length@big; pointer = size; updateElement[new_Integer] := (pointer = 1 + Mod[pointer, size]; big[[pointer]] = new) Do[updateElement[RandomInteger@99], {100}] // AbsoluteTiming {0.000374, Null} To bring the buffer back to the normal form use big = RotateLeft[big, Mod[pointer, size]]; // AbsoluteTiming pointer = size; {0.034542, Null} If you don't need a list to be in the normal form on each step this could be 10^4 times faster than Append[Rest[...]] Do[big = Append[Rest@big, RandomInteger@99], {100}] // AbsoluteTiming {5.884157, Null}
{ "source": [ "https://mathematica.stackexchange.com/questions/18078", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/121/" ] }
18,257
I have a simple interactive plot in Mathematica , with controls for various parameters. The point of the plot is simply that users can explore how the plot changes as the parameters change by manipulating controls. IOW, this is Dynamic -101 stuff (which is my level at the moment). I would like to convert this to (non-proprietary) HTML + SVG (+ CSS, JavaScript, etc., as needed). Is there a straightforward path for doing this? I know that one can export Mathematica graphics to SVG, but I'm not sure how one would export the dynamic behavior described above. (BTW, I've looked for ways to do this starting from JavaScript to begin with, but I have found that JavaScript support for plotting is rather primitive. JavaScript graphics seem to be mostly about Illustrator-type stuff, and more recently, "data visualization". In comparison, there's almost nothing in the JavaScript graphics universe for plotting functions, the way Plot et al. do.)
Animations as interactive visualizations The simplest form of interactive graphics is an animation in which the play head can be moved by the user. That doesn't sound very interactive, but in terms of functionality the play head is nothing but a type of Slider . With this simple interpretation of interactivity, any movie format supported by Export would be a way to create a standalone "interactive" visualization. The starting point for this approach would be to generate a list of graphics that will form the frames of the animation: frames = Table[ Plot[Sin[φ x]/(φ x), {x, -1, 1}, Background -> White, Frame -> True, PlotRange -> {{-1, 1}, {-.5, 1}}], {φ, Pi,10 Pi, Pi/2}]; I've added a Background to the plot because it will be needed to make the SVG version of the movie come out properly below. Frame based animations with SVG But the other part of your question is specifically asking about SVG and HTML format. In SVG , you can create animations by moving elements around using JavaScript . But that's not something you can easily automate in exporting a Mathematica dynamic object - it would require case-by-case fine tuning. So instead, I pursued a totally different way to combine the first point (the movie paradigm) with SVG : export an animation in which each frame is a static SVG vector graphic. Then the interactive element is again realized by the mere presence of the play head as a slider. To make this a little more interesting than a typical movie player, I also added the ability to export a sequence of N graphics but create a larger number M > N of frames from them in the animation. This is achieved by allowing an indexed list to specify the movie frames, so the M frames can walk through the N graphics in any order with arbitrary repetitions during playback. The Javascript movie player The whole thing is based on a JavaScript movie player I had written earlier, so you also get the ability to encode your frames as standard PNG bitmaps instead of SVG . The special thing about the player is that it's a single standalone HTML file . All movie frames are embedded in the HTML using base64 encoding, so the animation remains just as portable as a normal movie, GIF etc. But the SVG playback ability is what makes this most relevant to your question. Since SVG takes more resources to store and interpret during the display, one can notice that the player is somewhat slower to start up when you choose SVG format instead of the default PNG format. However, the nice thing is that SVG animations can be enlarged without loss of quality, even while the movie is running . I'm putting this out there for experimentation, and SVG may not turn out to be the best choice for your application. But then you can still go with PNG and get a smooth frame animation with full slider control. The JavaScript player has some additional features in addition to a draggable play head. Since it's frame-based, you can interactively change the frame delay, press a to display all frames side-by-side, and change the looping behavior. htmlTemplate = Import["http://pages.uoregon.edu/noeckel/jensPlayer/jensPlayerTemplate.js", "Text"]; jensPlayer[name_?StringQ, a_?ListQ, opts : OptionsPattern[]] := Module[ {delay = 50, dataType = "img", htmlString, htmlBody, scaledFrames, n, i, movieFrames, dimensions, frameStartTag, frameEndTag, exportFormat, imgSizeRule, loopOptions = {"Loop" -> "rightLoopButton", "None" -> "noLoopButton", "Palindrome" -> "palindromeButton"}, toolHeight = 25}, n = Range[Length[a]]; imgSizeRule = FilterRules[{opts}, ImageSize]; If[imgSizeRule == {}, imgSizeRule = (ImageSize -> Automatic)]; scaledFrames = Map[Show[#, imgSizeRule] &, a]; dimensions = ImageDimensions[Rasterize[scaledFrames[[1]]]]; With[{del = ("Delay" /. {opts})}, If[NumericQ[del], delay = del]]; With[{ind = ("Indices" /. {opts})}, If[ListQ[ind], i = ind - 1, i = n - 1]]; Which[("SVG" /. {opts}) === True, dataType = "object", ("SVGZ" /. {opts}) === True, dataType = "embed"]; If[dataType == "embed", frameStartTag = "<embed src=\""; frameEndTag = "\" width=\"" <> ToString[dimensions[[1]]] <> "\"height=\"" <> ToString[dimensions[[2]]] <> "\">"; htmlString = ""; movieFrames = Table[ With[{svgName = name <> ToString[ PaddedForm[i, Total@DigitCount[Length[scaledFrames]], NumberPadding -> {"0", " "}]] <> ".svgz"}, Export[svgName, scaledFrames[[i]], "SVGZ"]; frameStartTag <> svgName <> frameEndTag], {i, Length[scaledFrames]}]; htmlString = StringJoin[movieFrames], If[dataType == "img", frameStartTag = "<img src=\"data:image/png;base64,"; frameEndTag = "\">"; movieFrames = Apply[If[("Parallel" /. {opts}) === False, Map, ParallelMap], {ExportString[#, "PNG"] &, scaledFrames}], frameStartTag = "<object data=\"data:image/svg+xml;base64,"; frameEndTag = "\" type=\"image/svg+xml\"></object>"; movieFrames = Apply[If[("Parallel" /. {opts}) === False, Map, ParallelMap], {ExportString[#, "SVG"] &, scaledFrames}] ]; htmlString = StringJoin@ If[("Parallel" /. {opts}) === False, Map[(StringJoin[frameStartTag, StringReplace[ExportString[#, "Base64"], "\n" -> ""], frameEndTag]) &, movieFrames], DistributeDefinitions[frameStartTag]; DistributeDefinitions[frameEndTag]; ParallelMap[(StringJoin[frameStartTag, StringReplace[ExportString[#, "Base64"], "\n" -> ""], frameEndTag]) &, movieFrames] ] ]; htmlBody = StringReplace[ htmlTemplate, {"**DATE**" -> DateString[], "**DATATYPE**" -> dataType, "**WIDTH**" -> ToString[dimensions[[1]]], "**HEIGHT**" -> ToString[dimensions[[2]]], "**TOOLHEIGHT**" -> ToString[toolHeight], "**DELAY**" -> ToString[delay], "**COMBINEDWIDTH**" -> ToString[Length[a]*dimensions[[1]]], "**USERNAME**" -> $UserName, "**LOOPCONTROL**" -> With[{loopOption = ("Looping" /. {opts}) /. loopOptions}, If[MemberQ[loopOptions[[All, 2]], loopOption], loopOption, "None" /. loopOptions]], "**INDICES**" -> StringJoin@Riffle[Map[ToString, i], ","], "**AUTOPLAY**" -> If[("AutoPlay" /. {opts}) === True, "true", "false"], "**TITLE**" -> name}] <> htmlString <> "</div></body></html>"; Export[name, htmlBody, "TEXT"]; ] Examples With this function you can now export the frames created earlier: jensPlayer["sombrero.html", frames] SystemOpen["sombrero.html"] jensPlayer["sombreroIndexed.html", frames, "Delay" -> 60, "AutoPlay" -> True, "Looping" -> "Palindrome", "Parallel" -> True, "Indices" -> {19, 18, 17, 16, 15, 15, 17, 18, 19, 19, 18, 17, 16, 15, 14, 13, 11, 9, 7, 5, 4, 3, 2, 2, 1, 1, 1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 11, 13, 15, 16, 17, 18, 19, 19, 19, 19}] SystemOpen["sombreroIndexed.html"] jensPlayer["sombreroSVG.html", frames, "SVG" -> True] SystemOpen["sombreroSVG.html"] Each of the export commands illustrates a different export format. Options By default, the images in list images are displayed sequentially with a constant time delay, in a single playback run. If the option "Indices" is specified, frames are played back in the order determined by that option, see below. Options (except for ImageSize, all options are strings requiring quotation marks): ImageSize number of pixels in the horizontal direction. If unspecified, will be determined by size of the graphics in images. "Looping" "None" (default), "Loop" "Palindrome" "Delay" number of milliseconds between frames (default 50 ) "Indices" {i1, i2,... iN} , a list of (not necessarily different) integers between 1 and Length[images] . The number of frames in the movie is N . in ( n = 1,...N ) is the index in list a of the image to be displayed as frame n . "AutoPlay" True False (default) sets whether the movie should start playing as soon as loaded. "Parallel" True (default) False switches between parallel/sequential image conversion. Parallel speeds up the export if more than one Mathematica Kernel is available. "SVG" True False (default) switches between SVG or PNG format for the frame export. SVG format is provided on an experimental basis because browser support is evolving slowly. It is a resolution-independent graphics format that can be resized seamlessly in Firefox. SVG requires larger startup time, so it should not be used for large movies. With SVG you should also specify an explicit background for the frames, e.g. by doing images=Map[Show[#,Background->White]&,originalImages] . Although SVG movies yield much larger HTML files, gzip compression can make file sizes comparable to those of PNG movies (or even smaller). Since web servers increasingly are configured to transmit HTML files using on-the-fly compression, SVG does not necessarily increase download times. Additional notes Because the JavaScript file is too unwieldy for this post, I put it on my web site and use Import in the jensPlayer function to load it. I would suggest that you download the file http://pages.uoregon.edu/noeckel/jensPlayer/jensPlayerTemplate.js and copy and paste it as a string into the htmlTemplate = assignment. Then you can use the function offline. Also, I had tried SVGZ instead of SVG , and the function allows that as an option. However, this compressed SVG format doesn't play back so well apparently. Maybe the decompression is causing problems - I haven't had time to debug that yet. So I'd recommend you not use SVGZ at the moment, even though you may have seen it in the code above. Illustrated example To show what the movie should look like, here is a sequence of images that represent an electric field distribution for a range of separations d between two charged objects. The parameter d is then controlled with the movie slider: field[a_, d_, x_, y_] = D[Log[((x - d)^2 + y^2)/((x - a)^2 + y^2)], {{x, y}}]; images = With[{r = 1.}, Table[ Show[ StreamPlot[field[1/d, d, x, y], {x, -2, 4}, {y, -3, 3}, FrameLabel -> {"x", "y"}, StreamColorFunctionScaling -> False, StreamColorFunction -> "Rainbow", PlotLabel -> Row[{"d = ", PaddedForm[N@d, {4, 2}]}]], Graphics[{Thickness[.009], White, Circle[{0, 0}, r], PointSize[.03], Point[{d, 0}]}], Background -> GrayLevel[.2], LabelStyle -> White, FrameStyle -> Directive[Lighter@Gray, Thickness[.005]], ImageMargins -> 5], {d, 1.5 r, 4 r, r/4}]]; jensPlayer["imageChargesSVG.html", images, "SVG" -> True, "Parallel" -> False] The movie is a screen recording of the JavaScript movie player in Google Chrome. The controls at the bottom fade in and out. The left-most control switches between single run, back-and-forth (palindromic) playback and looping. I show how to stop the movie by pressing the red button, and then drag the slider to get to a particular frame. After restarting and stopping agin, I click on the frame counter to get a dialog that allows interactive adjustment of the frame delay. After changing the delay to 250 milliseconds, the playback is slower. There are several other keyboard shortcuts that are explained if you click the question mark at the bottom right. In particular, you can use arrow keys to move from frame to frame while the movie is stopped.
{ "source": [ "https://mathematica.stackexchange.com/questions/18257", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/2464/" ] }
18,258
Possible Duplicate: Plotting multivariable integration I am trying to plot an inverse function. If I do something like this: g[x_] := Sin[x] F[x_] := NIntegrate[g[y], {y, 0, x}] ParametricPlot[{F[x], x}, {x, 0, 2 Pi}] I get the following error message "NIntegrate::nlim: y = x is not a valid limit of integration. >>" However, I also get a plot which is correct. Am I doing something wrong or should I just ignore the error message?
Animations as interactive visualizations The simplest form of interactive graphics is an animation in which the play head can be moved by the user. That doesn't sound very interactive, but in terms of functionality the play head is nothing but a type of Slider . With this simple interpretation of interactivity, any movie format supported by Export would be a way to create a standalone "interactive" visualization. The starting point for this approach would be to generate a list of graphics that will form the frames of the animation: frames = Table[ Plot[Sin[φ x]/(φ x), {x, -1, 1}, Background -> White, Frame -> True, PlotRange -> {{-1, 1}, {-.5, 1}}], {φ, Pi,10 Pi, Pi/2}]; I've added a Background to the plot because it will be needed to make the SVG version of the movie come out properly below. Frame based animations with SVG But the other part of your question is specifically asking about SVG and HTML format. In SVG , you can create animations by moving elements around using JavaScript . But that's not something you can easily automate in exporting a Mathematica dynamic object - it would require case-by-case fine tuning. So instead, I pursued a totally different way to combine the first point (the movie paradigm) with SVG : export an animation in which each frame is a static SVG vector graphic. Then the interactive element is again realized by the mere presence of the play head as a slider. To make this a little more interesting than a typical movie player, I also added the ability to export a sequence of N graphics but create a larger number M > N of frames from them in the animation. This is achieved by allowing an indexed list to specify the movie frames, so the M frames can walk through the N graphics in any order with arbitrary repetitions during playback. The Javascript movie player The whole thing is based on a JavaScript movie player I had written earlier, so you also get the ability to encode your frames as standard PNG bitmaps instead of SVG . The special thing about the player is that it's a single standalone HTML file . All movie frames are embedded in the HTML using base64 encoding, so the animation remains just as portable as a normal movie, GIF etc. But the SVG playback ability is what makes this most relevant to your question. Since SVG takes more resources to store and interpret during the display, one can notice that the player is somewhat slower to start up when you choose SVG format instead of the default PNG format. However, the nice thing is that SVG animations can be enlarged without loss of quality, even while the movie is running . I'm putting this out there for experimentation, and SVG may not turn out to be the best choice for your application. But then you can still go with PNG and get a smooth frame animation with full slider control. The JavaScript player has some additional features in addition to a draggable play head. Since it's frame-based, you can interactively change the frame delay, press a to display all frames side-by-side, and change the looping behavior. htmlTemplate = Import["http://pages.uoregon.edu/noeckel/jensPlayer/jensPlayerTemplate.js", "Text"]; jensPlayer[name_?StringQ, a_?ListQ, opts : OptionsPattern[]] := Module[ {delay = 50, dataType = "img", htmlString, htmlBody, scaledFrames, n, i, movieFrames, dimensions, frameStartTag, frameEndTag, exportFormat, imgSizeRule, loopOptions = {"Loop" -> "rightLoopButton", "None" -> "noLoopButton", "Palindrome" -> "palindromeButton"}, toolHeight = 25}, n = Range[Length[a]]; imgSizeRule = FilterRules[{opts}, ImageSize]; If[imgSizeRule == {}, imgSizeRule = (ImageSize -> Automatic)]; scaledFrames = Map[Show[#, imgSizeRule] &, a]; dimensions = ImageDimensions[Rasterize[scaledFrames[[1]]]]; With[{del = ("Delay" /. {opts})}, If[NumericQ[del], delay = del]]; With[{ind = ("Indices" /. {opts})}, If[ListQ[ind], i = ind - 1, i = n - 1]]; Which[("SVG" /. {opts}) === True, dataType = "object", ("SVGZ" /. {opts}) === True, dataType = "embed"]; If[dataType == "embed", frameStartTag = "<embed src=\""; frameEndTag = "\" width=\"" <> ToString[dimensions[[1]]] <> "\"height=\"" <> ToString[dimensions[[2]]] <> "\">"; htmlString = ""; movieFrames = Table[ With[{svgName = name <> ToString[ PaddedForm[i, Total@DigitCount[Length[scaledFrames]], NumberPadding -> {"0", " "}]] <> ".svgz"}, Export[svgName, scaledFrames[[i]], "SVGZ"]; frameStartTag <> svgName <> frameEndTag], {i, Length[scaledFrames]}]; htmlString = StringJoin[movieFrames], If[dataType == "img", frameStartTag = "<img src=\"data:image/png;base64,"; frameEndTag = "\">"; movieFrames = Apply[If[("Parallel" /. {opts}) === False, Map, ParallelMap], {ExportString[#, "PNG"] &, scaledFrames}], frameStartTag = "<object data=\"data:image/svg+xml;base64,"; frameEndTag = "\" type=\"image/svg+xml\"></object>"; movieFrames = Apply[If[("Parallel" /. {opts}) === False, Map, ParallelMap], {ExportString[#, "SVG"] &, scaledFrames}] ]; htmlString = StringJoin@ If[("Parallel" /. {opts}) === False, Map[(StringJoin[frameStartTag, StringReplace[ExportString[#, "Base64"], "\n" -> ""], frameEndTag]) &, movieFrames], DistributeDefinitions[frameStartTag]; DistributeDefinitions[frameEndTag]; ParallelMap[(StringJoin[frameStartTag, StringReplace[ExportString[#, "Base64"], "\n" -> ""], frameEndTag]) &, movieFrames] ] ]; htmlBody = StringReplace[ htmlTemplate, {"**DATE**" -> DateString[], "**DATATYPE**" -> dataType, "**WIDTH**" -> ToString[dimensions[[1]]], "**HEIGHT**" -> ToString[dimensions[[2]]], "**TOOLHEIGHT**" -> ToString[toolHeight], "**DELAY**" -> ToString[delay], "**COMBINEDWIDTH**" -> ToString[Length[a]*dimensions[[1]]], "**USERNAME**" -> $UserName, "**LOOPCONTROL**" -> With[{loopOption = ("Looping" /. {opts}) /. loopOptions}, If[MemberQ[loopOptions[[All, 2]], loopOption], loopOption, "None" /. loopOptions]], "**INDICES**" -> StringJoin@Riffle[Map[ToString, i], ","], "**AUTOPLAY**" -> If[("AutoPlay" /. {opts}) === True, "true", "false"], "**TITLE**" -> name}] <> htmlString <> "</div></body></html>"; Export[name, htmlBody, "TEXT"]; ] Examples With this function you can now export the frames created earlier: jensPlayer["sombrero.html", frames] SystemOpen["sombrero.html"] jensPlayer["sombreroIndexed.html", frames, "Delay" -> 60, "AutoPlay" -> True, "Looping" -> "Palindrome", "Parallel" -> True, "Indices" -> {19, 18, 17, 16, 15, 15, 17, 18, 19, 19, 18, 17, 16, 15, 14, 13, 11, 9, 7, 5, 4, 3, 2, 2, 1, 1, 1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 11, 13, 15, 16, 17, 18, 19, 19, 19, 19}] SystemOpen["sombreroIndexed.html"] jensPlayer["sombreroSVG.html", frames, "SVG" -> True] SystemOpen["sombreroSVG.html"] Each of the export commands illustrates a different export format. Options By default, the images in list images are displayed sequentially with a constant time delay, in a single playback run. If the option "Indices" is specified, frames are played back in the order determined by that option, see below. Options (except for ImageSize, all options are strings requiring quotation marks): ImageSize number of pixels in the horizontal direction. If unspecified, will be determined by size of the graphics in images. "Looping" "None" (default), "Loop" "Palindrome" "Delay" number of milliseconds between frames (default 50 ) "Indices" {i1, i2,... iN} , a list of (not necessarily different) integers between 1 and Length[images] . The number of frames in the movie is N . in ( n = 1,...N ) is the index in list a of the image to be displayed as frame n . "AutoPlay" True False (default) sets whether the movie should start playing as soon as loaded. "Parallel" True (default) False switches between parallel/sequential image conversion. Parallel speeds up the export if more than one Mathematica Kernel is available. "SVG" True False (default) switches between SVG or PNG format for the frame export. SVG format is provided on an experimental basis because browser support is evolving slowly. It is a resolution-independent graphics format that can be resized seamlessly in Firefox. SVG requires larger startup time, so it should not be used for large movies. With SVG you should also specify an explicit background for the frames, e.g. by doing images=Map[Show[#,Background->White]&,originalImages] . Although SVG movies yield much larger HTML files, gzip compression can make file sizes comparable to those of PNG movies (or even smaller). Since web servers increasingly are configured to transmit HTML files using on-the-fly compression, SVG does not necessarily increase download times. Additional notes Because the JavaScript file is too unwieldy for this post, I put it on my web site and use Import in the jensPlayer function to load it. I would suggest that you download the file http://pages.uoregon.edu/noeckel/jensPlayer/jensPlayerTemplate.js and copy and paste it as a string into the htmlTemplate = assignment. Then you can use the function offline. Also, I had tried SVGZ instead of SVG , and the function allows that as an option. However, this compressed SVG format doesn't play back so well apparently. Maybe the decompression is causing problems - I haven't had time to debug that yet. So I'd recommend you not use SVGZ at the moment, even though you may have seen it in the code above. Illustrated example To show what the movie should look like, here is a sequence of images that represent an electric field distribution for a range of separations d between two charged objects. The parameter d is then controlled with the movie slider: field[a_, d_, x_, y_] = D[Log[((x - d)^2 + y^2)/((x - a)^2 + y^2)], {{x, y}}]; images = With[{r = 1.}, Table[ Show[ StreamPlot[field[1/d, d, x, y], {x, -2, 4}, {y, -3, 3}, FrameLabel -> {"x", "y"}, StreamColorFunctionScaling -> False, StreamColorFunction -> "Rainbow", PlotLabel -> Row[{"d = ", PaddedForm[N@d, {4, 2}]}]], Graphics[{Thickness[.009], White, Circle[{0, 0}, r], PointSize[.03], Point[{d, 0}]}], Background -> GrayLevel[.2], LabelStyle -> White, FrameStyle -> Directive[Lighter@Gray, Thickness[.005]], ImageMargins -> 5], {d, 1.5 r, 4 r, r/4}]]; jensPlayer["imageChargesSVG.html", images, "SVG" -> True, "Parallel" -> False] The movie is a screen recording of the JavaScript movie player in Google Chrome. The controls at the bottom fade in and out. The left-most control switches between single run, back-and-forth (palindromic) playback and looping. I show how to stop the movie by pressing the red button, and then drag the slider to get to a particular frame. After restarting and stopping agin, I click on the frame counter to get a dialog that allows interactive adjustment of the frame delay. After changing the delay to 250 milliseconds, the playback is slower. There are several other keyboard shortcuts that are explained if you click the question mark at the bottom right. In particular, you can use arrow keys to move from frame to frame while the movie is stopped.
{ "source": [ "https://mathematica.stackexchange.com/questions/18258", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5454/" ] }
18,393
As you may already know, Mathematica is a wonderful piece of software. However, it has a few characteristics that tend to confuse new (and sometimes not-so-new) users. That can be clearly seen from the the fact that the same questions keep being posted at this site over and over again. Please help me to identify and explain those pitfalls, so that fewer new users make the mistake of walking into these unexpected traps. Suggestions for posting answers: One topic per answer Focus on non-advanced uses (it's intended to be useful for beginners/newbies/novices and as a question closing reference) Include a self explanatory title in h2 style Explain the symptoms of problems, the mechanism behind the scenes and all possible causes and solutions you can think of. Be sure to include a beginner's level explanation (and a more advanced one too, if you're in the mood) Include a link to your answer by editing the Index below (for quick reference) Stability and usability Learn how to use the Documentation Center effectively Undo is not available before version 10 Don't leave the Suggestions Bar enabled The default $HistoryLength causes Mathematica to crash! Syntax and semantics Association value access [] vs [[]] Basic syntax issues What the @#%^&*?! do all those funny signs mean? Understand that semicolon (;) is not a delimiter Omitting ; can cause unexpected results in functions Understand the difference between Set (or = ) and Equal (or == ) The displayed form may substantially differ from the internal form Mathematica's own programming model: functions and expressions Assignment and definition Lingering Definitions: when calculations go bad Understand the difference between Set (or = ) and SetDelayed (or := ) Understand what Set (=) really does Attempting to make an assignment to the argument of a function Assuming commands will have side effects which they don't: How to use both initialized and uninitialized variables General guidelines Avoiding procedural loops Understand the difference between exact and approximate (Real) numbers Using the result of functions that return replacement rules Use Consistent Naming Conventions User-defined functions, numerical approximation, and NumericQ Mathematica can be much more than a scratchpad Understanding $Context , $ContextPath the parsing stage and runtime scoping constructs How to work always in WYSIWYG mode? Graphics and images Why do I get an empty plot? Why is my picture upside-down? Plot functions do not print output (Where are my plots?) Use Rasterize[..., "Image"] to avoid double rasterization Tricky functions Using Sort incorrectly Misunderstanding Dynamic Fourier transforms do not return the expected result Association/<||> objects are Atomic and thus unmatchable before 10.4 Association has HoldAll(Complete)
What the @#%^&*?! do all those funny signs mean? Questions frequently arise about the meaning of the basic operators, and I hope it will prove useful to have a sort of index for them. It would be nice to have them organized by sign instead of topic, but they do not have a natural order. One can use the find/search feature of a browser to locate an operator in the list. Below are links to documentation explanations for most of those shorthand signs together with a short example. Read the documentation for an explanation and more examples. See also the guide to Wolfram Language Syntax , which has links to most of these. In a couple of cases, I give different links that seem more helpful to me. All those operators come with a specific precedence. Assuming an incorrect precedence of your operators can wreak havoc with your programs. For instance, the & operator, which is part of a pure function specification, has a rather unexpectedly low precedence, and constructions using it quite often need to be protected with parentheses in order to make things work as intended (for instance, as option values). So, please have a look at this gigantic precedence table . Most (but not all) of these can be looked up using the ? -syntax, for example evaluating ? /@ will show help for Map . They can also be found by searching for them in the Documentation Center (Help menu). In older versions of Mathematica certain operators must be quoted before searching for them, e.g. search for "?" to find PatternTest . Version information may be found at the bottom of the documentation pages of each command. Consult the online page if you do not have the latest version of Mathematica to see when a function was introduced. Beginners may have difficulty in identifying shorthand signs correctly. For example, is _? a whole shorthand sign or the combination of _ and ? ? In this case, Hold and FullForm can be revealing: Cases[Range[500], _?PrimeQ] // Hold // FullForm (* Hold[Cases[Range[500], PatternTest[Blank[], PrimeQ]]] *) By further searching PatternTest and Blank in document, we'll know _? is actually combination of Blank[] ( _ ) and PatternTest ( ? ). Function application @ , [...] , // [ ref ] -- f @ x = f[x] = x // f ( Prefix , circumfix and Postfix operators for function application) ~ [ ref ] -- x ~f~ y = f[x, y] ( Infix ; see Join [ ref ] for a Basic Example .) /@ [ ref ] -- f /@ list = Map[f, list] (not to be confused with f @ list , when f is Listable ) @@ [ ref ] -- f @@ list = Apply[f, list] @@@ [ ref ] -- f @@@ list = Apply[f, list, {1}] //@ [ ref ] -- f //@ expr = MapAll[f, expr] @* [ ref ] -- f @* g @* h = Composition[f, g, h] /* [ ref ] -- f /* g /* h = RightComposition[f, g, h] Infix ~ should not be confused with: ~~ [ ref ] -- s1 ~~ s2 ~~ ... = StringExpression[s1, s2, ...] <> [ ref ] -- s1 <> s2 <> ... = StringJoin[s1, s2, ...] Pure function notation # , #1 , #2 , ... [ ref ] -- # = #1 = Slot[1] , #2 = Slot[2] , ... ## , ##2 , ... [ ref ] -- ## = ##1 = SlotSequence[1] , ##2 = SlotSequence[2] , ... #0 [ ref ] gives the head of the function, i.e., the pure function itself. & [ ref ] -- # & = Function[Slot[1]] , #1 + #2 & = Function[#1 + #2] , etc. |-> or \[Function] [ ref ] -- x \[Function] x^2 ( ) = Function[x, x^2] Bracketing [ , ] -- f[x, y, ...] ; function application and the underlying form of all expressions { , } [ ref ] -- {x, y, ...} = List[x, y, ...] [[ , ]] [ ref ] -- expr[[n]] = Part[expr, n] ; also expr[[n1, n2,...]] = Part[expr, n1, n2,...] . ( , ) -- parentheses, used for grouping only (not function application) <| , |> [ref] -- <| a -> b, c -> d, ... |> = Association[a -> b, c -> d, ...] (* , *) -- (*some text*) ; an inline comment \[ , ] [ ref ] -- \[charactername] ; special characters, e.g. \[CapitalOmega] for Ω \( , \) [ ref ] -- RowBox , a low-level head used in constructing notebook expressions (rare) Assignments = [ ref ] -- = = Set (not to be confused with == -- Equal !) := [ ref ] -- := = SetDelayed =. [ ref ] -- =. = Unset ^= [ ref ] -- ^= = UpSet ^:= [ ref ] -- ^:= = UpSetDelayed /: = [ ref ] -- /: = = TagSet /: := [ ref ] -- /: := = TagSetDelayed /: =. [ ref ] -- /: =. = TagUnset Special assignments //= [ ref ] -- x //= f = ApplyTo[x, f] ; equivalent to x = f[x] += [ ref ] -- x += n = AddTo[x, n] ; equivalent to x = x + n -= [ ref ] -- x -= n = SubtractFrom[x, n] ; equivalent to x = x - n *= [ ref ] -- x *= n = TimesBy[x, n] ; equivalent to x = x * n /= [ ref ] -- x /= n = DivideBy[x, n] ; equivalent to x = x / n ++ [ ref ] x++ = Increment[x] ; sets x = x + 1 , then evaluates to the old value of x [ ref ] ++x = PreIncrement[x] ; sets x = x + 1 , then evaluates to the new value of x -- [ ref ] x-- = Decrement[x] ; sets x = x - 1 , then evaluates to the old value of x [ ref ] --x = PreDecrement[x] ; sets x = x - 1 , then evaluates to the new value of x Relations == [ ref ] -- == = Equal (not to be confused with = -- Set , or with Equivalent !) === [ ref ] -- === = SameQ != [ ref ] -- != = Unequal =!= [ ref ] -- =!= = UnsameQ < , > , <= , >= -- Less , Greater , LessEqual , GreaterEqual ∈ , \[Element] [ ref ] -- Element Rules and patterns -> [ ref ] -- -> = Rule (also can specify DirectedEdge ) <-> [ ref ] -- <-> = TwoWayRule (also can specify UndirectedEdge ) :> [ ref ] -- :> = RuleDelayed /; [ ref ] -- patt /; test = Condition[patt, test] ? [ ref ] -- p ? test = PatternTest[p, test] (not to be confused with Information ) _ , _h [ ref ] -- Single underscore: _ = Blank[] , _h = Blank[h] __ , __h [ ref ] -- Double underscore: __ = BlankSequence[] , __h = BlankSequence[h] ___ , ___h [ ref ] -- Triple underscore: ___ = BlankNullSequence[] , ___h = BlankNullSequence[h] .. [ ref ] -- p.. = Repeated[p] ... [ ref ] -- p... = RepeatedNull[p] : [ ref ] or [ ref ] -- x : p = pattern p named x ; or, as a function argument, p : v = pattern p to be replaced by v if p is omitted. _. [ ref ] , [ ref ] -- Represents an optional argument to a function, with a default value specified by Default . | [ ref ] -- | = Alternatives (not to be confused with || -- Or !) /. [ ref ] -- expr /. rules = ReplaceAll[expr, rules] //. [ ref ] -- expr //. rules = ReplaceRepeated[expr, rules] Logical operators && , ∧ [ ref ] -- && = And (not to be confused with & -- Function !) || , ∨ [ ref ] -- || = Or ! , ¬ [ ref ] -- ! = Not \[Implies] [ ref ] -- \[Implies] = Implies ( ) \[Equivalent] [ ref ] -- \[Equivalent] = Equivalent ( ) ⊼ [ ref ] -- ⊼ = Nand ⊽ [ ref ] -- ⊽ = Nor ⊻ [ ref ] -- ⊻ = Xor [ ref ] -- = Xnor List ;; [ ref ] -- expr[[i ;; j]] = Part[expr, Span[i, j]] ; also expr[[i ;; j ;; k]] = Part[expr, Span[i, j, k]] . . [ ref ] -- a.b , a.m.b ; the dot product of vectors or matrices ( List s) Numeric + , - , * , ^ -- Plus , Subtract (or Minus as a prefix), Times , Power *^ is equivalent to *10^ (e.g. 3*^2=300 ). ^^ gives a way to enter a number in a different base (e.g. 2^^100101 represents the binary number $100101_2 = 37$ ). See more info in the documentation of BaseForm . ` , `` [ ref ] / [ ref ] , [ ref ] -- Indicates Precision , and Accuracy , respectively, when following a number. There is a table of typical examples in the tutorial Numerical Precision . When ` follows a symbol, it denotes a context. More information about contexts can be found in some of the tutorials in this overview . Graph construction \[DirectedEdge] [ ref ] -- \[DirectedEdge] = DirectedEdge ( or -> / Rule may be used) \[UndirectedEdge] [ ref ] -- \[UndirectedEdge] = UndirectedEdge ( or <-> / TwoWayRule may be used) Probability \[Distributed] [ ref ] -- \[Distributed] = Distributed ( ) \[Conditioned] [ ref ] -- \[Conditioned] = Conditioned ( ) Evaluation history and control % [ ref ] gives the last result generated. %% gives the result before last. %n (= Out[n] ) gives the result on the n th output line. Not to be confused with Percent [ ref ] . ; [ ref ] -- a;b;c = CompoundExpression[a,b,c] . ; is an expression separator, used to evaluate some number of expressions in sequence, for example in the body of Module[] . When evaluated with no trailing ; , the value returned is the value of the last expression. Note that x; returns Null . Files and Packages << [ ref ] -- << = Get >> [ ref ] -- >> = Put >>> [ ref ] -- >>> = PutAppend Symbol information :: [ ref ] -- f::usage = MessageName[f, "usage"] . (Note that since v13.1 :: is also experimentally used for TypeSpecifier when the first argument is a string.) ? , ?? [ ref ] -- ? f = Information[f, LongForm -> False] , ?? f = Information[Sin] . See also Definition and its undocumented relatives discussed here . Not to be confused with ? when following a pattern ( PatternTest ). Other $ is not an operator; it can be used in variable names (e.g. my$variable ). It is commonly used for System` constants and parameters (e.g. $Version ) and for local variables generated by scoping constructs (e.g. Module[{x}, x] $\rightarrow$ x$9302 ). a ** b ** c [ ref ] = NonCommutativeMultiply[a, b, c] (not given a built-in value) Similar to ** there are numerous operator forms which can be used with their special symbols in unary or infix form and which carry no predefined meaning. A list can be found here .
{ "source": [ "https://mathematica.stackexchange.com/questions/18393", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/193/" ] }
18,495
For example: "#FF8000" . How could I convert it to RGBColor or Hue ?
Using IntegerDigits to convert directly to base 256: hexToRGB = RGBColor @@ (IntegerDigits[ ToExpression@StringReplace[#, "#" -> "16^^"], 256, 3]/255.) & hexToRGB["#FF8000"] (* RGBColor[1., 0.501961, 0.] *) Edit Shorter version, since somebody mentioned golfing... hexToRGB = RGBColor @@ (IntegerDigits[# ~StringDrop~ 1 ~FromDigits~ 16, 256, 3]/255.) &
{ "source": [ "https://mathematica.stackexchange.com/questions/18495", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5379/" ] }
18,508
Inspired by this (please use Chrome or Firefox), I tried to simulate it, but I couldn't do it. I'm not familiar with Dynamic . Here is my simple code: Dynamic[ Graphics[{Hue[Random[]], PointSize@Large, Point[{0, Dynamic[Clock[{0, 5, 0.5}]]}]}, Axes -> 1, PlotRange -> 5] ]
Here you have a toy to start playing with: Edit preventing the animation running at different speeds in different machines by using Clock[] and DynamicWrapper[] (due credit to @jVincent) n = 500; (*number of managed particles*) x[i_][t_] := (vx0[i] (t - delay[i])) UnitStep[t - delay[i]]; y[i_][t_] := Module[{k}, If[(k = (-#^2 + vy0@i #) UnitStep@#) < 0 &[t - delay@i], delay[i] = t + RandomReal[{0, 5}], k]]; vcols = RandomReal[{0, 1}, n]; Table[vx0@i = RandomReal[{-1, 1}]; vy0@i = RandomReal[{10, 12}]; delay@i = RandomReal[{0, 12}], {i, n}]; points[s_] := Table[{x[i][s], y[i][s]}, {i, n}]; DynamicModule[{t}, DynamicWrapper[ Framed@Graphics[Dynamic@Point[points[t], VertexColors -> Hue /@ vcols], PlotRange -> {{-10, 10}, {0, 40}}, ImageSize -> 200], t = Clock[10^6]]]
{ "source": [ "https://mathematica.stackexchange.com/questions/18508", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5379/" ] }
18,526
It’s great that Quantity can utilize Wolfram Alpha to interpret unit strings that it doesn’t recognize, but I need my code to work on machines that do not have Internet access. Is there a complete list of built-in (i.e. canonical) unit strings recognized by Quantity ? Better yet, is there a programmatic way to produce such a list?
This is certainly the optimal way of obtaining the list you are looking for Quantity;QuantityUnits`Private`$UnitReplacementRules[[1, All, 1]] EDIT for v10 (thanks @DavidCreech) In v10 this undocumented variable format has been changed into an association, whose keys are the units. Quantity; Keys[QuantityUnits`Private`$UnitReplacementRules]
{ "source": [ "https://mathematica.stackexchange.com/questions/18526", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/155/" ] }
18,598
For my Calc III class, I need to find $T(t), N(t)$, and $B(t)$ for $t=1, 2$, and $-1$, given $r(t)=\{t,t^2,t^3\}$. I've got Mathematica , but I've never used it before and I'm not sure how to coerce it into solving this. (My professor told us to use a computer, as it starts getting pretty nasty around $T'(t)$. By hand, $$T(t)=\frac{1}{ \sqrt{(1+4t^2+9t^4})}\{1,2t,3t^2\}$$ I've tried defining r as stated above and using D , Norm , and CrossProduct . However, I get a bunch of Abs in my outputs (am I missing an assumption?). Additionally, I can't seem to google up how to ask Mathematica to sub in a specific value for $t$, once I get the equations worked out properly.
Mathematica wouldn't be much helpful if one applied only formulae calculated by hand. Here we demonstrate how to calculate the desired geometric objects with the system having a definition of the curve r[t] : r[t_] := {t, t^2, t^3} now we call uT the unit tangent vector to r[t] . Since we'd like it only for real parameters we add an assumption to Simplify that t is a real number. Similarly we can do it for the normal vector vN[t] and the binormal vB[t] : uT[t_] = Simplify[ r'[t] / Norm[ r'[t] ], t ∈ Reals]; vN[t_] = Simplify[ uT'[t]/ Norm[ uT'[t]], t ∈ Reals]; vB[t_] = Simplify[ Cross[r'[t], r''[t]] / Norm[ Cross[r'[t], r''[t]] ], t ∈ Reals]; let's write down the formulae : {uT[t], vN[t], vB[t]} // Column // TraditionalForm Edit Definitions provided above are clearly more useful than only to write them down. They are powerful enough to animate a moving reper along a curve r[t] . Indeed the vectors uT[t] , vN[t] and vB[t] are orthogonal and normalized, e.g. Simplify[ Norm /@ {uT[t], vN[t], vB[t]}, t ∈ Reals] {1, 1, 1} To demonstrate a moving reper we can use ParametricPlot3D and Arrow enclosed in Animate : Animate[ Show[ ParametricPlot3D[ {r[t]}, {t, -1.3, 1.3}, PlotStyle -> {Blue, Thick}], Graphics3D[{ {Thick, Darker @ Red, Arrow[{r[s], r[s] + uT[s]}]}, {Thick, Darker @ Green, Arrow[{r[s], r[s] + vB[s]}]}, {Thick, Darker @ Cyan, Arrow[{r[s], r[s] + vN[s]}]}}], PlotRange -> {{-2, 2}, {-2, 2}, {-2, 2}}, ViewPoint -> {4, 6, 0}, ImageSize -> 600], {s, -1, 1}]
{ "source": [ "https://mathematica.stackexchange.com/questions/18598", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5605/" ] }
18,599
Possible Duplicate: Best way to extract values from a list of rules? If I have a vector v = {x->1.03, x-> 2.01, .... }, and I want to use an element in the list, I can get an element as v[[1]] = x-> 1.03 but suppose I want to get rid of the arrow? Thanks for any suggestions.
Mathematica wouldn't be much helpful if one applied only formulae calculated by hand. Here we demonstrate how to calculate the desired geometric objects with the system having a definition of the curve r[t] : r[t_] := {t, t^2, t^3} now we call uT the unit tangent vector to r[t] . Since we'd like it only for real parameters we add an assumption to Simplify that t is a real number. Similarly we can do it for the normal vector vN[t] and the binormal vB[t] : uT[t_] = Simplify[ r'[t] / Norm[ r'[t] ], t ∈ Reals]; vN[t_] = Simplify[ uT'[t]/ Norm[ uT'[t]], t ∈ Reals]; vB[t_] = Simplify[ Cross[r'[t], r''[t]] / Norm[ Cross[r'[t], r''[t]] ], t ∈ Reals]; let's write down the formulae : {uT[t], vN[t], vB[t]} // Column // TraditionalForm Edit Definitions provided above are clearly more useful than only to write them down. They are powerful enough to animate a moving reper along a curve r[t] . Indeed the vectors uT[t] , vN[t] and vB[t] are orthogonal and normalized, e.g. Simplify[ Norm /@ {uT[t], vN[t], vB[t]}, t ∈ Reals] {1, 1, 1} To demonstrate a moving reper we can use ParametricPlot3D and Arrow enclosed in Animate : Animate[ Show[ ParametricPlot3D[ {r[t]}, {t, -1.3, 1.3}, PlotStyle -> {Blue, Thick}], Graphics3D[{ {Thick, Darker @ Red, Arrow[{r[s], r[s] + uT[s]}]}, {Thick, Darker @ Green, Arrow[{r[s], r[s] + vB[s]}]}, {Thick, Darker @ Cyan, Arrow[{r[s], r[s] + vN[s]}]}}], PlotRange -> {{-2, 2}, {-2, 2}, {-2, 2}}, ViewPoint -> {4, 6, 0}, ImageSize -> 600], {s, -1, 1}]
{ "source": [ "https://mathematica.stackexchange.com/questions/18599", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/4856/" ] }
18,647
What is a simple, fast way to test whether an expression is a real-valued number? I ask since there is no RealQ function. If we call this test realQ , it should satisfy these constraints: realQ["text"] is False (non numerics are all false) realQ[0] is True (integers are true) realQ[3.0] is True (reals are true) realQ[1/2] is True (rationals are true) realQ[I] is False (anything with an imaginary component is false)
Update: Internal`RealValuedNumericQ /@ {1, N[Pi], 1/2, Sin[1.], Pi, 3/4, aa, I} (* {True, True, True, True, True, True, False, False} *) or Internal`RealValuedNumberQ /@ {1, N[Pi], 1/2, Sin[1.], Pi, 3/4, aa, I} (* {True, True, True, True, False, True, False, False} *) Using @RM's test list listRM = With[{n = 10^5}, RandomSample[Flatten[{RandomChoice[CharacterRange["A", "z"], n], RandomInteger[100, n], RandomReal[1, n], RandomComplex[1, n], RandomInteger[100, n]/RandomInteger[{1, 100}, n], Unevaluated@Pause@5}], 5 n + 1]]; and his realQ ClearAll@realQrm SetAttributes[realQrm, Listable] realQrm[_Real | _Integer | _Rational] := True realQrm[_] := False timings realQrm@listRM; // AbsoluteTiming (* {0.458046, Null} *) Internal`RealValuedNumericQ /@ listRM; // AbsoluteTiming (* {0.247025, Null} *) Internal`RealValuedNumberQ /@ listRM; // AbsoluteTiming (* {0.231023, Null} *) realQ = NumberQ[#] && ! MatchQ[#, _Complex] & realQ /@ {1, N[Pi], 1/2, Sin[1.], 3/4, aa, I} (* {True, True, True, True, True, False, False} *) or realQ2 = NumericQ[#] && ! MatchQ[#, _Complex] & realQ3 = NumericQ[#] && FreeQ[#, _Complex] &
{ "source": [ "https://mathematica.stackexchange.com/questions/18647", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/594/" ] }
18,655
This question has appeared in various forms online, but I have not yet seen a complete answer, so I am posting it here. More specifically, suppose I have a function F: X->Y that is not one-to-one. Mathematica can easily plot this function as follows: Plot[F[x], {x, 0, 30}, PlotRange -> {{0, 30}, {0, 1}}] This produces a graph that passes the vertical line test, but does not pass the horizontal line test, because F is not one-to-one. My question is, how do I get a plot of the inverse relation (which is not a function) for all Y? Edit: I am adding the function F for clarity. I originally omitted it because I figured a generic solution would solve it. F[x_] := (1000 * x) / 24279 * Sqrt[-1 + x^(2/7)] Edit 2: I am adding the graph (that I am trying to graph the inverse relation of) I produced using Plot for further clarity. To be clear, this image is produced by the following three commands: F[x_] := (1000 * x) / (24279 * Sqrt[-1 + x^(2/7)]) myplot = Plot[F[x], {x,0,30}, PlotRange -> {{0,30}, {0,1}}] Export["foo.png", myplot]
Update: Using the example function provided in op's update: ff[x_] := (1000*x)/(24279*Sqrt[-1 + x^(2/7)]); prmtrcplt1 = ParametricPlot[{x, ff[x]}, {x, 0, 30}, PlotRange -> {{0, 30}, {0, 1}}, ImageSize -> 300, AspectRatio -> 1]; prmtrcplt2 = ParametricPlot[{ff[x], x}, {x, 0, 30}, PlotRange -> Reverse[PlotRange[prmtrcplt1]], ImageSize -> 300, AspectRatio -> 1]; Row[{prmtrcplt1, prmtrcplt2}, Spacer[5]] plt = Plot[ff[x], {x, 0, 30}, PlotRange -> {{0, 30}, {0, 1}},ImageSize -> 300, AspectRatio -> 1]; ref1 = MapAt[GeometricTransformation[#, ReflectionTransform[{-1, 1}]] &, plt, {1}]; ref2 = plt /. line_Line :> GeometricTransformation[line, ReflectionTransform[{-1, 1}]]; Row[{plt, Graphics[ref1[[1]], PlotRange -> Reverse@PlotRange[ref1], ref1[[2]]], Graphics[ref2[[1]], PlotRange -> Reverse@PlotRange[ref2], ref2[[2]]]}, Spacer[5]] original post ParametricPlot (as suggested by whuber) prmtrcplt1 = ParametricPlot[{x, x Sin[2 x]}, {x, -Pi, Pi}, PlotRange -> {{-Pi, Pi}, {-3, 3}}, ImageSize -> 300]; prmtrcplt2 = ParametricPlot[{x Sin[2 x], x}, {x, -Pi, Pi}, PlotRange -> {{-Pi, Pi}, {-3, 3}}, ImageSize -> 300]; Row[{prmtrcplt1, prmtrcplt2}, Spacer[5]] Post-process using ReflectionTransform reflected = plt /. line_Line :> {Red, GeometricTransformation[line, ReflectionTransform[{-1, 1}]]}; Row[{plt, reflected, Show[plt, Plot[x, {x, -Pi, Pi}, PlotStyle -> Black], reflected, PlotRange -> All, ImageSize -> 300]}, Spacer[5]] Variations: reflected2 = MapAt[GeometricTransformation[#, ReflectionMatrix[{-1, 1}]] &, plt, {1}]; reflected3 = MapAt[GeometricTransformation[#, ReflectionTransform[{-1, 1}]] &,plt, {1}]
{ "source": [ "https://mathematica.stackexchange.com/questions/18655", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5619/" ] }
18,674
I have a function that takes an OptionsPattern and I want to access several options, say a , and b . This works great: f1[OptionsPattern[]] := Block[{}, {OptionValue[a],OptionValue[b]} ]; Options[f1] = {a -> 1, b -> 2}; Calling f1[] returns {1,2} as expected. The problem is that I don't know in advance which options I'll want to access. So I thought about trying this: f2[OptionsPattern[]] := Block[{list}, list={a,b}; OptionValue /@ list ]; Options[f2] = {a -> 1, b -> 2}; f2 doesn't work, and neither do f3 : f3[OptionsPattern[]] := Block[{}, OptionValue /@ {a,b} ]; They both return {OptionValue[a], OptionValue[b]} . However, this does work: f4[OptionsPattern[]] := Block[{}, OptionValue[#]& /@ {a,b} ]; Question : Why on earth do f2,f3 not work, while f4 does, and what is the difference between f4 and f3 anyhow? PS These also these don't work: f5[OptionsPattern[]] := Block[{}, Evaluate[OptionValue /@ {a, b}] ]; f6[OptionsPattern[]] := Block[{}, OptionValue /@ Evaluate[{a, b}] ];
A guess My guess is that you have just run into the details of OptionValue implementation, which are also responsible for its "magical" behavior. OptionValue has to somehow know which function it is in, and tracing the execution of f4[] shows that apparently the following expansion is happening before any evaluation is attempted for the r.h.s.: OptionValue[#]& -> OptionValue[f4,{},#]& Now, it seems like this (lexical) substitution is triggered when OptionValue[something] is found somewhere on the r.h.s., but not when OptionValue appears as a symbol without arguments. Note that such replacement can not be a part of normal evaluation, but rather looks like a macro-like expansion, based on the lexical analysis of the code on the r.h.s. Consider this example d[a -> 8] /. d[OptionsPattern[]] :> HoldComplete@OptionValue[a] (* HoldComplete[OptionValue[d, {a -> 8}, a]] *) Now, HoldComplete holds all kinds of dynamic evaluation of the right hand side. However, OptionValue was expanded. When you are using the magic couple in a way that OptionsPattern has no head, the expansion results in an empty list {} as OptionValue 's first argument. d[a -> 8] /. OptionsPattern[] :> HoldComplete@OptionValue[a] (* d[HoldComplete[OptionValue[{}, {a -> 8}, a]]] *) It seems like the OptionsPattern search is done Heads->False and at levels 0 and 1 only. The expansion doesn't happen for lhs such as OptionsPattern[][] or f[g[OptionsPattern[]] . This might be to ensure there is either no or a single head enclosing all the OptionsPattern . An illustration Here is some code to mimic this behavior: Module[{tried}, Unprotect[SetDelayed]; SetDelayed[ f_[args___, optpt : OptionsPattern[]], rhs_ ] /;!FreeQ[Unevaluated[rhs], optionValue[_]]:= Block[{tried = True}, f[args, optpt] := Unevaluated[rhs] /. optionValue[s_] :> optionValue[f, {optpt}, s] ] /; ! TrueQ[tried]; Protect[SetDelayed]; ] NOTE!! - this redefines SetDelayed (the idea taken from this answer ). So now: f8[OptionsPattern[]]:=Block[{},optionValue[#]&/@{a,b}]; f8[] (* {optionValue[f8,{},a],optionValue[f8,{},b]} *) f9[OptionsPattern[]]:=Block[{},optionValue/@{a,b}]; f9[] (* {optionValue[a],optionValue[b]} *) It remains now to define optionValue[f_,opts_List,name_] to make this emulation to work. Unprotect[SetDelayed]; Clear[SetDelayed]; Protect[SetDelayed] Remarks I wouldn't call this behavior consistent, but this is almost certainly a consequence of the internal mechanism (implementation) for the OptionsPattern - OptionValue construct. Whether it is at all possible to make this "magic" fully work in all cases, is IMO a good question. As to the reason why this does not work for other cases, it looks like OptionValue is dynamically - scoped, in some sense. Only its long (non-magical) form has enough information about the calling function and passed options, to work. At run-time, the short form is evaluated(since the expansion into a long form did not happen), and this short form simply evaluates to itself.
{ "source": [ "https://mathematica.stackexchange.com/questions/18674", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/367/" ] }
18,761
Here is Fizz buzz Write a program that prints the integers from 1 to 100. But for multiples of 3 print "Fizz" instead of the number and for the multiples of 5 print "Buzz". For numbers which are multiples of both 3 and 5 print "FizzBuzz". I found the python version is much shorter, so I decided to write a short one, I have wrote several version Table[If[# != {}, Row@#, n] &@({Fizz}[[Sign[n~Mod~3] + 1 ;;]]~Join~{Buzz}[[Sign[n~Mod~5] + 1 ;;]]), {n, 100}] StringJoin@{If[#~Mod~3 == 0, "Fizz", ""], If[#~Mod~5 == 0, "Buzz", ""]} /. "" -> # & /@ Range@100 d = Divisible; Range@100 /. {_?(#~d~15 &) -> FizzBuzz, _?(#~d~3 &) -> Fizz, _?(#~d~5 &) -> Buzz} Can you show a more shorter one?
67 63 56 55 (47?) characters Better: Row@Pick[{Fizz,Buzz},#~Mod~{3,5},0]/._@{}->#&~Array~100 In the rule-bending spirit of Code Golf, 47 characters : Pick[Fizz^Buzz,#~Mod~{3,5},0]/. 1->#&~Array~100
{ "source": [ "https://mathematica.stackexchange.com/questions/18761", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/2090/" ] }
18,960
I've been struggling with a number of hangs, dynamic timeouts, and outright crashes when using the search/documentation center in version 9. I've tried uninstalling/reinstalling and clearing preferences/cache on start-up, praying for a paclet update---but nothing seems to help. One easily reproducible crash involves searching via the F1 key. On my machine (Windows 7, 64-bit), following the steps below, fails 100% of the time. (This is the simplest example I've taken the time to document; there seem to be many others.) With a fresh session (not always reproducible with just a fresh kernel), type something in the front-end. This could be text (in a text cell) or input (in an input cell) such as: something (and leave it unevaluated---if in an input cell) Now highlight that input and hit "F1" to perform a search. This will either return a dynamic timeout warning, or momentarily freeze the front-end and do nothing. Now use your cursor to select something again and try "F1" a second time. This will perform the search as desired. Can anyone reproduce this issue? UPDATE 1: Upgrading to 9.0.1 only partially addresses the issue. To illustrate, start a fresh session/kernel, type something and then hit F1 ( without manually highlighting something ). A similar hangup will occur. As Albert points out in his answer, this hangup does not seem to occur with F1 searches on built-in symbols, highlighted or not. Finally, FWIW, I suspect Albert's observation relates to another way I've encountered errors. Quite often when I come across some unfamiliar mathematical terminology on stackexchange, I reflexively copy and paste the term---from my browser, to the search field of the documentation center (which is almost always open when I'm working). Frequently this will generate the same type of error or worse. I suspect it has to do with whether or not the search term is either a built-in symbol or already indexed somehow. UPDATE 2: I recently decided to wipe my machine and reinstall everything from the OS up. Eventually I got around to installing Mathematica (from the exact same installer used previously). Much to my surprise, even without applying either of the two fixes, the hangups seem to be gone (or at least below what I can perceive). Just wanted to document this. Will report back if anything changes.
While trying to debug this issue myself, I stumbled across Todd Gayley's name in the source of one of the documentation .m files and contacted him directly. Todd was super great to work with---and at the end of an hour of screensharing he provided an easy workaround. The workaround essentially short-circuits one tiny feature of a normal documentation search. Specifically, this fix prevents the documentation code from looking up the number of times the search term appears on WRI's website. As such, you will also no longer see a count of these search hits showing up in the 'Search Results' window in your Mathematica session. Instructions: (* execute this to locate your user init.m file*) SystemOpen[FileNameJoin[{$UserBaseDirectory,"Kernel"}]] (* open the file init.m file, append the following two lines, save and close it *) Needs["DocumentationSearch`"]; Clear[DocumentationSearch`Private`urlImport]; Now close Mathematica and restart it. No more documentation search stutters. Comments from WRI: This bug is caused by a delay that can occur when Mathematica's internet connectivity code looks up a proxy. The delay generally occurs only once per session, which explains why users will generally find that subsequent documentation searches proceed quickly. The delay can be longer than the default Dynamic timeout, and thus you either get a quiet failure or see the Dynamic timeout warning dialog displayed. If you can get by with not using a proxy at all, as suggested by @Robinaut, then that is ideal. If you do need to use a proxy, then this answer is the best way to handle the problem. Turning off all internet access in Mathematica is a sledgehammer fix that should be avoided. We are working on a fix that will eliminate the delay, but if this is not forthcoming we will simply take out the call to urlImport. Therefore, no future versions of Mathematica will suffer from this problem. Thanks to @telefunkenvf14 for helping us discover the precise cause of this problem.
{ "source": [ "https://mathematica.stackexchange.com/questions/18960", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/197/" ] }
19,004
Show[Plot[Sin[x], {x, 0, π}, PlotStyle -> Red, PlotRange -> {{0, 2 π}, {-1, 1}}], Plot[Sin[x], {x, π, 2 π}, PlotStyle -> Green, PlotRange -> {{0, 2 π}, {-1, 1}}]] Is there a simpler way of doing this? Especially, one that does not require repeating the Plot command 2 times ;)
Plot[Sin[x], {x, 0, 2 π}, PlotStyle -> Thick, ColorFunction -> Function[{x, y}, If[x < Pi, Red, Blue]], ColorFunctionScaling -> False, PlotRange -> {{0, 2 π}, {-1, 1}}] or Plot[Sin[x], {x, 0, 2 π}, PlotStyle -> Thick, Mesh -> {{Pi}}, MeshShading -> {Red, Blue}, PlotRange -> {{0, 2 π}, {-1, 1}}] or Plot[{ConditionalExpression[Sin[x], 0 <= x <= Pi], ConditionalExpression[Sin[x], Pi <= x <= 2 Pi]}, {x, 0, 2 Pi}, PlotStyle -> {Directive[Thick, Red], Directive[Thick, Blue]}]
{ "source": [ "https://mathematica.stackexchange.com/questions/19004", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5323/" ] }
19,014
I was playing around with Manipulate to demonstrate simple geometric idea of conic sections and put this little sample together. When i move the slider it moves my plane, which is what I expect. However, when I let go of the slider, the graphics are rescaled. So how I stop that? I have set the PlotRange and AspectRatio , so I don't understand why the scale is changing. Manipulate[ plot = Plot3D[n, {x, -1, 1}, {y, -1, 1}, AspectRatio->1, PlotRange->{{-1, 1}, {-1, 1}}, Mesh->False]; cone = Graphics3D[{Opacity[0.3], Cone[{{0, 0, -1}, {0, 0, 1}}, 1]}, PlotRange->{{-1, 1}, {-1, 1}}, AspectRatio->1]; Show[{plot, cone}, AspectRatio->1], {{n, 0}, -1, 1}]
Plot[Sin[x], {x, 0, 2 π}, PlotStyle -> Thick, ColorFunction -> Function[{x, y}, If[x < Pi, Red, Blue]], ColorFunctionScaling -> False, PlotRange -> {{0, 2 π}, {-1, 1}}] or Plot[Sin[x], {x, 0, 2 π}, PlotStyle -> Thick, Mesh -> {{Pi}}, MeshShading -> {Red, Blue}, PlotRange -> {{0, 2 π}, {-1, 1}}] or Plot[{ConditionalExpression[Sin[x], 0 <= x <= Pi], ConditionalExpression[Sin[x], Pi <= x <= 2 Pi]}, {x, 0, 2 Pi}, PlotStyle -> {Directive[Thick, Red], Directive[Thick, Blue]}]
{ "source": [ "https://mathematica.stackexchange.com/questions/19014", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5570/" ] }
19,035
I asked Mathematica to compute the following Solve[c (1-x)^2-x^(1/4) == 0, x] and it returned this: x = Root[#1^8 c^4 - 8 #1^7 c^4 + 28 #1^6 c^4 - 56 #1^5 c^4 + 70 #1^4 c^4 - 56 #1^3 c^4 + 28 #1^2 c^4 + #1 (-8 c^4-1) + c^4&, 1] What does this mean? In particular, what's with all the # s?
# is a placeholder for an expression. If you want to define a function, $y(x)=x^2$, you just could do: f = #^2 & The & "pumps in" the expression into the # sign. That is important for pairing & and # when you have nested functions. f[2] (* 4 *) If you have a function operating on two variables, you could do: f = #1 + #2 & So f[3,4] (* 7 *) Or you may have a function operating on a list, like: f = #[[1]] + #[[2]] & So: f[{3,4}] (* 7 *) About Root[] According to Mathematica help: Root[f,k] represents the exact kth root of the polynomial equation f[x]==0 . So, if your polynomial is $x^2 - 1$, using what we saw above: f = #^2 - 1 & Root[f, 1] (* - 1 (* as we expected ! *) *) And Root[f, 2] (* 1 (* Thanks God ! *) *) But if we try with a higher order polynomial: f = -1 - 2 #1 - #1^2 + 2 #1^3 + #1^4 & Root[f, 1] (* Root[-1 - 2 #1 - #1^2 + 2 #1^3 + #1^4 &, 1] *) That means Mathematica doesn't know how to calculate a symbolic result for the root. It's just the first root of the polynomial. But it does know its numerical value: N@Root[-1 - 2 #1 - #1^2 + 2 #1^3 + #1^4 &, 1] (* -2.13224 *) So, Root[f,k] is a kind of stenographic writing for roots of polynomials with order > 3. I'll save you from an explanation about radicals and finding polynomial roots... for the better, I think
{ "source": [ "https://mathematica.stackexchange.com/questions/19035", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5730/" ] }
19,042
I have a set of InterpolatingFunction returned by NDSolve which are valid over different (but overall continuous) domains. How do I splice them together into one single InterpolatingFunction over all the domains? Piecewise seems to promising, but I can't manage to return the piecewise function from another function then use it later the same way as InterpolatingFunction . I guess there is also the brute force way of generating a grid of points using the original set of InterpolatingFunction then interpolating points again, but that's very elaborate and CPU-consuming, not to mention potentially inaccurate if the interpolation grid is not chosen properly. Thoughts? Thanks to the answer from Mr. Wizard, this is the solution I ended up using: JoinInterpolatingFunction[intervals_List, flist_List] := Module[{getGrid}, getGrid[f_InterpolatingFunction, min_?NumericQ, max_?NumericQ] := {{min, f[min]}}~ Join~(Transpose@{f["Grid"] // Flatten, f["ValuesOnGrid"]} // Select[#, (min < #[[1]] < max) &] & )~Join~{{max, f[max]}} // N; Interpolation[ Table[getGrid[flist[[i]], intervals[[i]], intervals[[i + 1]]], {i, Length@flist}] // Flatten[#, 1] & // DeleteDuplicates[#, (#1[[1]] == #2[[1]]) &] &, InterpolationOrder -> 2]] JoinInterpolatingFunction[{I1,I2,..,In},{func1,func2,...func(n-1)}] gives an InterpolatingFunction that takes values of func1 between [I1,I2], func2 between (I2,I3], ... func(n-1) between (I(n-1),In].
Update: information below updated with values from version 10.0.0 I expect that if the InterpolationOrder is the same between functions it should be possible to merge them into one. If not Piecewise may be the best you can do. This is an incomplete answer but hopefully a useful signpost that may lead you to a solution. You can get the constituent parts (or at least their related forms) using the little-known "Methods" syntax, which is akin to the "Properties" of SparseArray if you have seen that before. Here is a list of the "Methods": f1 = Interpolation @ Table[{i, Sin[i]}, {i, 0, Pi, 0.1}]; f1["Methods"] {"Coordinates", "DerivativeOrder", "Domain", "ElementMesh", "Evaluate", "Grid", "InterpolationMethod", "InterpolationOrder", "MethodInformation", "Methods", "OutputDimensions", "Periodicity", "PlottableQ", "Properties", "QuantityUnits", "ValuesOnGrid"} Here are the internal usage messages: f1["MethodInformation"@#] & ~Scan~ f1["Methods"] InterpolatingFunction[domain, data]@Coordinates[] returns the grid coordinates in each dimension. InterpolatingFunction[domain, data]@DerivativeOrder[] returns what derivative of the interpolated function will be computed upon evaluation. InterpolatingFunction[domain, data]@Domain[] returns the domain of the InterpolatingFunction. InterpolatingFunction[domain, data]@ElementMesh[] returns the element mesh if one is present. InterpolatingFunction[domain, data]@Evaluate[arg] evaluates the InterpolatingFunction at the argument arg. InterpolatingFunction[domain, data]@Grid[] gives the grid of points where the interpolated data is defined. InterpolatingFunction[domain, data]@InterpolationMethod[] returns the method used for interpolation. InterpolatingFunction[domain, data]@InterpolationOrder[] returns the degree of polynomials used for computing interpolated values. InterpolatingFunction[domain, data]@MethodInformation[method] gives information about a particular method. InterpolatingFunction[domain, data]@Methods[pat] gives the list of methods matching the string pattern pat. InterpolatingFunction[domain, data]@OutputDimensions[] returns the output dimensions of the interpolating function. InterpolatingFunction[domain, data]@Periodicity[] returns whether the interpolating function is periodic in the respective dimensions. InterpolatingFunction[domain, data]@PlottableQ[] returns whether the interpolating function is plottable or not. InterpolatingFunction[domain, data]@Properties gives the list of possible properties. InterpolatingFunction[domain, data]@QuantityUnits[] returns the quantity units associated with abscissa and ordinates. InterpolatingFunction[domain, data]@ValuesOnGrid[] gives the function values at each grid point. In some cases, this may be faster than evaluating at each of the grid points. Here is the actual output when applying these "Methods" to the example InterpolatingFunction above: Print /@ f1 /@ {"Coordinates", "DerivativeOrder", "Domain", "ElementMesh", Evaluate[], "Grid", "InterpolationMethod", "InterpolationOrder", "Methods", "OutputDimensions", "Periodicity", "PlottableQ", "Properties", "QuantityUnits", "ValuesOnGrid"}; {{0.,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9,3.,3.1}} 0 {{0.,3.1}} None {{0.},{0.1},{0.2},{0.3},{0.4},{0.5},{0.6},{0.7},{0.8},{0.9},{1.},{1.1},{1.2},{1.3},{1.4},{1.5},{1.6},{1.7},{1.8},{1.9},{2.},{2.1},{2.2},{2.3},{2.4},{2.5},{2.6},{2.7},{2.8},{2.9},{3.},{3.1}} Hermite {3} {Coordinates,DerivativeOrder,Domain,ElementMesh,Evaluate,Grid,InterpolationMethod,InterpolationOrder,MethodInformation,Methods,OutputDimensions,Periodicity,PlottableQ,Properties,QuantityUnits,ValuesOnGrid} {} {False} True {Properties} {None,None} {0.,0.0998334,0.198669,0.29552,0.389418,0.479426,0.564642,0.644218,0.717356,0.783327,0.841471,0.891207,0.932039,0.963558,0.98545,0.997495,0.999574,0.991665,0.973848,0.9463,0.909297,0.863209,0.808496,0.745705,0.675463,0.598472,0.515501,0.42738,0.334988,0.239249,0.14112,0.0415807}
{ "source": [ "https://mathematica.stackexchange.com/questions/19042", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1944/" ] }
19,076
I'm trying to plot a function of the form $z(r,\theta)$ where $r \in [0, R]$ for a finite R, $\theta \in [0,2\pi[$, and z is the third coordinate, a function of the first two. I couldn't find anything to do it natively, so I went back to Cartesian coordinates. But the result does not satisfy me, because the range of x is a function of y, a consequence of the constraint $ x^2+y^2 < R^2$. Is there already something in Mathematica to handle this kind of plot?
Do it parametrically. Here's a generic implementation: cylinderPlot3D[f_, {rMin_, rMax_}, {tMin_, tMax_}, opts___] := ParametricPlot3D[{r Cos[t], r Sin[t], f[r, t]}, {r, rMin, rMax}, {t, tMin, tMax}, opts] For example, f[r_, t_] := r^2 Cos[3 t]]; cylinderPlot3D[f, {0, 1}, {0, 2 Pi}, Mesh->None, Boxed->False]
{ "source": [ "https://mathematica.stackexchange.com/questions/19076", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5643/" ] }
19,108
I noticed that Mathematica has a set of special 'Formal' characters such as \[FormalA] , \[FormalB] , etc.. In the front end, it looks like a character with a dot above and below: It is not clear from the built-in documentation how these characters are to be used. Would someone demonstrate?
Very often, especially new Mathematica users stumble over the following error: They gave, maybe hours ago, a symbol a value like x=3 , and later they try to use it where a function really expects a symbol: This leads of course to an error, because the Minimize call does not see the x , but only its value. The same happens when you try to derive this with D or Dt or Integrate expressions. Although the error message is very clear, most people get very confused and try to change their whole calculation. Exactly for those situations, the formal parameter characters are made. They all share the attribute Protected which states that you cannot simply assign a value to them. Therefore, you can use them in situations where you maybe derive expressions or proof formulas or where you minimize an expression
{ "source": [ "https://mathematica.stackexchange.com/questions/19108", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/2048/" ] }
19,121
PlotPoints lets you determine how many sample points you want in each direction, but sometimes I want specific ones. For Plot you can give an argument like PlotPoints->{None, pts} to use pts as the initial points: Show[ Plot[Sin[x], {x, -3 Pi, 3 Pi}, PlotStyle -> Red, MaxRecursion -> 0, PlotPoints -> {None, {-7.3, -5.2, -Pi, Pi, 3.8, 5}}, PlotRange -> {{-3 Pi, 3 Pi}, {-1, 1}}], Plot[Sin[x], {x, -5 Pi, 5 Pi},PlotStyle -> Dashed] ] Is this also possible for Plot3D ? Whatever I try I end up with completely broken plots, anyone know the syntax of what I have stumbled into? EDIT PlotPoints->{Automatic,pts} seems to work, although about 2x as many points are used. f[x_, y_] := Cos[y]^3 Sin[x]^2 + Cos[x] Sin[y] pts3d = Reap[Plot3D[f[x, y], {x, -5, 5}, {y, -5, 5}, EvaluationMonitor :> Sow[{x, y}]]][[-1, 1]]; opts = {{Automatic, "Automatic"}, {{None, pts3d}, "{None, pts3d}"}, {{Automatic, pts3d}, "{Automatic,pts3d}"}, {{Automatic, RandomReal[{-5, 5}, {5000, 2}]}, "{Automatic,Random}"} }; Row[Plot3D[f[x, y], {x, -5, 5}, {y, -5, 5}, PlotPoints -> First@#, PlotLabel -> Last@#, ImageSize -> 200] & /@ opts] Here are three plots with exactly the same points that look different: {orig, {origpts}} = Reap[DensityPlot[f[x, y], {x, -5, 5}, {y, -5, 5}, EvaluationMonitor :> Sow[{x, y}]]]; {auto, {autopts}} = Reap[DensityPlot[f[x, y], {x, -5, 5}, {y, -5, 5}, PlotPoints -> {Automatic, RandomSample[origpts]}, MaxRecursion -> 0, EvaluationMonitor :> Sow[{x, y}]]]; {none, {nonepts}} = Reap[DensityPlot[f[x, y], {x, -5, 5}, {y, -5, 5}, PlotPoints -> {None, RandomSample[origpts]}, MaxRecursion -> 0, EvaluationMonitor :> Sow[{x, y}]]]; (* All give {} *) DeleteCases[origpts, Alternatives @@ autopts] DeleteCases[autopts, Alternatives @@ origpts] DeleteCases[nonepts, Alternatives @@ origpts] {orig, auto, none}
Just to be clear, the following is based on experimentation and could be wildly misleading... The outline of the algorithm for generating the mesh for Plot3D and DensityPlot appears to be: Create initial mesh based on the number of plot points Inject any user supplied points into the mesh Refine the mesh There are two issues to worry about when supplying an explicit list of points to PlotPoints . The first is that the injection of a point into the initial mesh works by subdividing the containing triangle, which can lead to very long thin triangles in the mesh. The second, critical, issue is that the mesh refinement appears to fail if too many points are inserted into a coarse initial mesh . To demonstrate these issues I will define a function to show the mesh obtained with specified PlotPoints and MaxRecursion settings: showmesh[pp_, mr_, opts___] := DensityPlot[f[x, y], {x, -1, 1}, {y, -1, 1}, Mesh -> All, MeshStyle -> Red, ColorFunction -> (White &), Frame -> None, PlotPoints -> pp, MaxRecursion -> mr, opts] f[x_, y_] := 1 To start with we can look at the mesh obtained with no refinement and a small number of plot points. There are no surprises here: GraphicsRow[showmesh[#, 0] & /@ {2, 3, 4}] When an explicit extra point is supplied, the containing triangle is subdivided: p = {{-0.123, 0.123}}; GraphicsRow[showmesh[{#, p}, 0] & /@ {2, 3, 4}] The thin triangle issue is clear, compare for example the first mesh above with a Delaunay triangulation of the same points: If we allow some mesh refinement with MaxRecursion , we can see that the user specified point is sampled after the initial mesh points but before the refinement. I've highlighted the user specified point in red: Reap[showmesh[{3, p}, 3, EvaluationMonitor :> Sow[{x, y}]]][[2]] /. x : First[p] :> Style[x, Red] I'll now switch to a more interesting plot function to make the refinement more obvious. Here are the meshes with our single user-specified point and adaptive mesh refinement switched on: f[x_, y_] := Sin[20 x y] GraphicsRow[showmesh[{#, p}, 3] & /@ {2, 3, 4}] Something interesting has happened - the meshes with 3 and 4 initial plot points have been refined, but the one with 2 initial plot points hasn't. (Clearly something has been done, as the thin triangle has gone - it looks like the Delaunay triangulation now, but there has been no subdivision.) It gets even more interesting if we increase the number of user-supplied points: p = RandomReal[{-1, 1}, {10, 2}]; GraphicsRow[showmesh[{#, p}, 3] & /@ {2, 3, 4}] With 10 points, the mesh with 3 initial plot points is now unrefined too. (Note that there is not a fixed threshold, if you run the code multiple times you'll see the mesh get refined sometimes and sometimes not.) The trend continues if we increase the number of user-supplied points: p = RandomReal[{-1, 1}, {25, 2}]; GraphicsRow[showmesh[{#, p}, 3] & /@ {2, 3, 4}] This is why the plots in the question are coming out badly - with a large number of user-supplied points and an initial mesh of None (i.e. 2) points, there is no adaptive refinement taking place, and the plot is based on a horrible mesh with lots of thin triangles. p = RandomReal[{-1, 1}, {100, 2}]; showmesh[{None, p}, 3] The only solution I can see is the one identified in the question - use a large enough number of initial plot points (or Automatic) to get the mesh refinement to kick in: showmesh[{10, p}, 3] It's not clear why the mesh refinement fails, I suspect the algorithm that decides whether to subdivide a triangle is getting fooled by the long thin triangles that appear when the user-supplied points are inserted. Ideally there would be a complete re-triangulation of the mesh after insertion of the extra points, using something like a Delaunay triangulation, but I can't find a way to make that happen. Update As MichaelE2 has pointed out, it is not as clear-cut as the recursive mesh refinement either working or not working. Instead, the rule seems to be that having a user point in every square cell of the original mesh will totally prevent refinement. However, when an original mesh cell is free of extra points, subdivision can occur in that cell - and propagate to adjacent cells. The propagation won't continue through the whole region though, rather it appears to spread by a few cells per recursion. To demonstrate, here's a mesh with a single user-defined point (shown in blue) placed inside each square cell. There is no mesh refinement at all: grid = Tuples[Range[-1., 1, 2/9], 2]; p = Select[({0.05, 0.15} + #) & /@ grid, Max[#] <= 1 &]; Show[showmesh[{10, p}, 3], Graphics[{PointSize[Medium], Blue, Point[p]}]] Now I'll remove the extra point from just one cell, in the middle. This time I'll highlight only the extra points added to the mesh by the refinement algorithm: x = p[[41]]; p = DeleteCases[p, x]; m = showmesh[{10, p}, 3]; q = Complement[Round[m[[1, 1]], 0.0001], Round[grid, 0.0001], Round[p, 0.0001]]; Show[m, Graphics[{PointSize[Medium], Point[q], Blue, Opacity[0.5], Disk[x, 0.1]}]] The refinement has started in the empty cell (the blue disk shows where the user point was removed) and spread to nearby cells. Here's an animation showing the result as MaxRecursion is increased from 0 to 6. The upshot seems to be that when specifying extra plot points, care must be taken to ensure that there are some initial mesh cells without extra points in, and also a high enough MaxRecursion to propagate the mesh refinement from those cells across the whole region.
{ "source": [ "https://mathematica.stackexchange.com/questions/19121", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1517/" ] }
19,174
I have a Dynamic -based GUI, and one part of it will kick off a calculation that could take longer than the default 5-second dynamic timeout. I know that Button has a Method -> "Queued" option for performing an evaluation on the main link rather than by doing a pre-emptive evaluation. How can I initiate a main link evaluation without requiring the user to click a button?
If you pass SynchronousUpdating->False to Dynamic , it will perform operations on the main link. Note that this only works where Dynamic is displayed as a typeset result (i.e., typeset as a DynamicBox ). It does not presently work where Dynamic is used to give a value to a control (such as Slider ) or an option. A quick survey of other constructs... ActionMenu has a Method option which works identically to Button . EventHandler , as of version 9, has no way to do main link evaluations. (Edit: As of v10, the EventHandler and the various EventHandler -like options now accept a Method option.) FrontEndDynamicExpression and friends, as of version 9, have no way to do main link evaluations.
{ "source": [ "https://mathematica.stackexchange.com/questions/19174", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/594/" ] }
19,268
As the title says, my objective is to create a simulation of the motion of the planets in our Solar System using Mathematica. All the theoretical background regarding the equations of motion of planets is well know so, the difficult part is to create a functional code. Below I present what I have so far Clear["Global`"]; pSun = {0, 0}; rMercury = a/(1 + e*Cos[θ]) /. {a -> 0.387, e -> 0.2056, i -> 7.005}; rVenus = a/(1 + e*Cos[θ]) /. {a -> 0.723, e -> 0.0068, i -> 3.3947}; rEarth = a/(1 + e*Cos[θ]) /. {a -> 1, e -> 0.0167, i -> 0}; rMars = a/(1 + e*Cos[θ]) /. {a -> 1.524, e -> 0.0934, i -> 1.851}; rJupiter = a/(1 + e*Cos[θ]) /. {a -> 5.203, e -> 0.0484, i -> 1.305}; rSaturn = a/(1 + e*Cos[θ]) /. {a -> 9.537, e -> 0.0542, i -> 2.484}; rUranus = a/(1 + e*Cos[θ]) /. {a -> 19.191, e -> 0.0472, i -> 0.770}; rNeptune = a/(1 + e*Cos[θ]) /. {a -> 30.069, e -> 0.0086, i -> 1.769}; rPluto = a/(1 + e*Cos[θ]) /. {a -> 39.482, e -> 0.2488, i -> 17.142}; p0 = ListPlot[{pSun}, Axes -> False, PlotStyle -> {RGBColor[1, 0.65, 0], PointSize[0.035]}]; p1 = PolarPlot[rMercury, {θ, 0, 2 π}, PlotStyle -> Gray]; p2 = PolarPlot[rVenus, {θ, 0, 2 π}, PlotStyle -> Orange]; p3 = PolarPlot[rEarth, {θ, 0, 2 π}, PlotStyle -> Blue]; p4 = PolarPlot[rMars, {θ, 0, 2 π}, PlotStyle -> Red]; p5 = PolarPlot[rJupiter, {θ, 0, 2 π}, PlotStyle -> Brown]; p6 = PolarPlot[rSaturn, {θ, 0, 2 π}, PlotStyle -> Magenta]; p7 = PolarPlot[rUranus, {θ, 0, 2 π}, PlotStyle -> Cyan]; p8 = PolarPlot[rNeptune, {θ, 0, 2 π}, PlotStyle -> Darker[Green]]; p9 = PolarPlot[rPluto, {θ, 0, 2 π}, PlotStyle -> Black]; S1 = Show[{p1, p2, p3, p4, p0}, Axes -> False, Frame -> True, FrameTicks -> None, PlotRange -> All, AspectRatio -> 1, ImageSize -> 500] S2 = Show[{p5, p6, p7, p8, p9, p0}, Frame -> True, FrameTicks -> None, Axes -> False, PlotRange -> All, AspectRatio -> 1, ImageSize -> 500] -------------------- INNER SOLAR SYSTEM -------------------- -------------------- OUTER SOLAR SYSTEM -------------------- I have divided the Solar System in two different plots. The first one contains the Earth-type planets (Mercury, Venus, Earth and Mars) and the second one the gas giants. The orbits of the planets are ellipses and are given in polar form using Kepler's theory. Obviously, Sun is stationary at one of the focuses. The motion of all the planets is two-dimensional. However, all orbits are not co-planar. Here comes the first issue: (1). Somehow, the ellipses must be rotated according to the inclination of each planet. The inclination (i) in degrees is given. So, we should have a 3D box containing all the 2D inclined ellipses. Earth's inclination is zero thus defying the primary plane (ecliptic) from which we measure inclination. (2). At every orbit, it would be nice if there was a color dot (like the Sun I already have) indicating each planet. Since we speak of a simulation, every dot (planet) should circulate around Sun following the corresponding orbit. Here we have a problem. Every planet has each one rotational velocity according to its mass. However, the polar equation giving the orbit does not include the mass of the planet. Any suggestions here would be greatly appreciated. There are also few additional minor issues. For the time being, the first two issues are important and should be resolved first. From my point of view, this task is indeed not only interesting but also very challenging. Everyone should have a nice model of our Solar System!
Update June 2015 Here is an updated version of the program. I've made it compatible with newer Mathematica versions ( AstronomicalData returns Quantity structures in newer versions, which wrangled calculations). It should now work on versions 8 through 10. Let me know if it doesn't. I added animation and simplified the presentation (no tooltips in the Graphics3D) and also added a star field in the background. I was aiming for reality-mapped stars but StarData coughed and sputtered too much to be usable, and the public star API that I tried gave only partial data. It's possible I misused these tools, but either way it's an improvement to be made. The program loads the planet colors from WolframAlpha into a memoization table, so it takes a few seconds to run the first time. metersToAU[m_] := m/(1.496*10^11);(*orbits are in AU*) objects = Prepend[AstronomicalData["Planet"], "Sun"]; (*ClearAll[dataMemo];*) dataMemo[object_] := ( dataMemo[object] = { (*orbit*)If[object === "Sun", {{0, 0, 0}}, First[AstronomicalData[object, "OrbitPath"]]], (*radius*)metersToAU[AstronomicalData[object, "Radius"]], (*color*)First[Cases[WolframAlpha[object <> " color"], _RGBColor, Infinity]], (*drawing scale*)If[object === "Sun", 1, 2.6]} /. Quantity[a_, _] :> a ); objectData[object_, dateOffset_] := Append[dataMemo[object], (*position*)metersToAU[AstronomicalData[object, {"Position", DatePlus[dateOffset]}]] /. Quantity[a_, _] :> a ]; dataMemo /@ objects; createGraphics[object_, scale_, dateOffset_, showOrbit_: True, showDisk_: False] := Module[{orbit, radius, color, exponent, position}, {orbit, radius, color, exponent, position} = objectData[object, dateOffset]; {color, Glow[color], (*orbit disk*)If[showDisk, {Opacity[.1], EdgeForm[None], Polygon[orbit]}], (*orbit*)If[showOrbit, {Opacity[.1], Line[orbit]}], (*object*)Sphere[position, scale^exponent*radius]}]; setterBar = # -> Tooltip[ImageResize[AstronomicalData[#, "Image"], {30, 30}], #] & /@ objects; (*random star distribution*) ratio = 1.91;(*8Volume[Cuboid[]]/Volume[Ball[]]*) {numstars, starDistance} = {10000, 50}; stars = Normalize /@ Select[RandomReal[{-1, 1}, {Floor[numstars*ratio], 3}], Norm[#] < 1 &]; daysInFuture = 0; Print[DynamicWrapper[Dynamic[DatePlus[daysInFuture]], Refresh[daysInFuture++, UpdateInterval -> .01, TrackedSymbols :> {}]]]; Module[{viewvector = {0, 8, 0}}, Manipulate[ viewvector[[2]] = zoom; Graphics3D[{ {White, Opacity[.4], AbsolutePointSize[2], Point[starDistance*stars]}, {Specularity[.1], Dynamic[ createGraphics[#, scale, daysInFuture, showOrbits, showDisk] & /@ visiblePlanets]}}, Boxed -> False, Background -> Black, SphericalRegion -> True, ImageSize -> Large, PlotRangePadding -> .5, ViewVector -> (*Dynamic[*)viewvector(*]*), Lighting -> {{"Ambient", White}, {"Directional", White, ImageScaled[{0, 0, 1}]}}], {{visiblePlanets, Take[objects, 5], "planets"}, setterBar, ControlType -> TogglerBar}, {{showDisk, False, "show planes"}, {False, True}}, {{showOrbits, True, "show orbits"}, {True, False}}, {{zoom, 8}, 2, 30}, {{scale, 13.5, "scale"}, 10, 20, Appearance -> "Labeled", ControlType -> None}]] Previous version metersToAU[m_] := m/(1.496*10^11); (* these colors aren't available from Astronomical data, but I got them through the free-form input. "=mars color", "=earth color", etc *) colorTable = { "Sun" -> Blend["BlackBodySpectrum", AstronomicalData["Sun", "EffectiveTemperature"]], "Mercury" -> RGBColor[0.598209, 0.577666, 0.576307], "Venus" -> RGBColor[0.753588`, 0.740667`, 0.706174`], "Earth" -> RGBColor[0.598209, 0.577666, 0.576307], "Mars" -> RGBColor[0.591699, 0.37999, 0.19484], "Jupiter" -> RGBColor[0.757233`, 0.697683`, 0.666215`], "Saturn" -> RGBColor[0.767425`, 0.699073`, 0.563738`], "Uranus" -> RGBColor[0.574328`, 0.751126`, 0.827463`], "Neptune" -> RGBColor[0.556615`, 0.747549`, 0.88086`] }; (* returns {orbit, current position, radius, color, scale exponent} *) objectData[object_] := { If[object === "Sun", {{0, 0, 0}}, First[AstronomicalData[object, "OrbitPath"]]], metersToAU[AstronomicalData[object, "Position"]], metersToAU[AstronomicalData[object, "Radius"]], object /. colorTable, If[object === "Sun", 1.1, 2.2] }; (* all astronomical data for an object. memoized *) Clear[tooltipData]; tooltipData[object_] := tooltipData[object] = Column[{ AstronomicalData[object, "Image"], Style[object, Bold], Grid[ Select[{#, AstronomicalData[object, #]} & /@ AstronomicalData["Properties"], Head[#[[2]]] =!= Missing && #[[1]] =!= "OrbitPath" && #[[1]] =!= "Image" &], Alignment -> Left]}]; (* create the Graphics3D primitives for a given object *) graphics[object_, scale_, showDisk_: False] := Module[{orbit, position, radius, color, exponent}, {orbit, position, radius, color, exponent} = objectData[object]; {If[showDisk, {Opacity[.02], Polygon[orbit]}], Tooltip[{Opacity[.1], color, Line[orbit], Opacity[1], Sphere[position, scale^exponent*radius]}, tooltipData[object]]}]; (* type AstronomicalData["Planet"], press Ctrl+. twice, then press Ctrl+Shift+Enter *) planets = {"Sun", "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"}; setterBar = # -> Tooltip[ImageResize[AstronomicalData[#, "Image"], {30, 30}], #, TooltipDelay -> .1] & /@ planets; (* preload tooltipData *) tooltipData /@ planets; Manipulate[ Graphics3D[ graphics[#, scale, showDisk] & /@ visiblePlanets, Boxed -> False, Background -> Black, SphericalRegion -> True, PlotRangePadding -> .5, Lighting -> {{"Ambient", White}, {"Directional", White, ImageScaled[{0, 0, 1}]}}], {{visiblePlanets, Take[planets, 5], "planets"}, setterBar, ControlType -> TogglerBar}, {{showDisk, False, "show planes"}, {False, True}}, {{scale, 10, "scale"}, 1, 20, Appearance -> "Labeled"}]
{ "source": [ "https://mathematica.stackexchange.com/questions/19268", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5052/" ] }
19,277
Not sure if this has been asked, but I have a fairly simple operation that I don't know the syntax for. Say I have an array with some values, and a function f that accepts an arbitrary number of arguments. The following: array = {e,f}; f[a, b, c, d, array]; ...is functionally equivalent to: f[a, b, c, d, {e, f}]; OK, will Sequence help? Nope, this does the same thing: f[a, b, c, d, Sequence@array]; Essentially, I want to include e and f into the list of arguments, i.e. I want to know the syntax for telling Mathematica I want it to evaluate this: f[a, b, c, d, e, f]; How do I go about doing this?
Sequence means more or less "no head". What you want to do is to remove the head List from an inner list. Or, put in another way, you want to replace this head with "no head". The operation that changes one head to another is Apply . Therefore, what you really want is f[a, b, c, d, Sequence @@ array] where @@ stands for Apply .
{ "source": [ "https://mathematica.stackexchange.com/questions/19277", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/805/" ] }
19,285
Is anyone aware of Mathematica use/implementation of Random Forest algorithm?
Here I will attempt to provide a basic implementation of the random forest algorithm for classification. This is by no means fast and doesn't scale very well but otherwise is a nice classifier. I recommend reading Breiman and Cutler's page for information about random forests. The following are some helper functions that allow us to compute entropy and ultimately information gain easily. condEnt = Statistics`Library`NConditionalEntropy; ent = Statistics`Library`NEntropy; maxI[v_] := Ordering[v, -1][[1]] Now for the decision trees that will be used in the forest. This is the biggest bottleneck in the whole process and I would love to see a much faster implementation in Mathematica! The trees I'm working with are called CART trees . The basic idea is to select at random m of the possible k variables to separate the response y into classes. Once the best variable is chosen the value of that variable which bests separates the classes is chosen to create a split in the tree. This process continues until all responses have been classified or we aren't able to split things based on the remaining data. cart[x_, y_ /; ent[y] == 0, m_] := First[y] cart[x_, y_, m_] := Block[{k = Length[x], h, drop, bestVar, ub, best, mask}, h = ent[y]; drop = RandomSample[Range[k], k - m]; bestVar = maxI[Table[If[FreeQ[drop, i], h - condEnt[x[[i]], y], 0], {i, k}]]; ub = Union[x[[bestVar]]]; mask = UnitStep[x[[bestVar]] - #] & /@ ub; best = maxI[(h - condEnt[#, y] & /@ mask)]; If[Min[#] == Max[#], RandomChoice[y], {bestVar, ub[[best]], cart[Pick[x\[Transpose], #, 1]\[Transpose], Pick[y, #, 1], m], cart[Pick[x\[Transpose], #, 0]\[Transpose], Pick[y, #, 0], m] } ] &[mask[[best]]] ] To demo these things as I go lets use the famous iris data built in to Mathematica selecting about 80% for training and 20% for testing. data = ExampleData[{"Statistics", "FisherIris"}]; rs = RandomSample[Range[Length[data]]]; train = rs[[1 ;; 120]]; test = rs[[121 ;;]]; Now lets create a CART tree from this data letting m be 3. We can read the result easily. The first element is the variable that bests splits the data, in this case variable 3. The next value 3.3 is the critical value of variable 3 to use. If a value is below that it branches to the right and if it is above it branches to the left. The leaves are the next two elements. tree = cart[Transpose@data[[train, 1 ;; -2]], data[[train, -1]], 3] (* {3, 3.3, {3, 4.9, {4, 1.8, "virginica", {3, 5.1, {4, 1.6, "versicolor","virginica"}, "versicolor"}}, {4, 1.7, {4, 1.8, "versicolor", "virginica"},"versicolor"}}, "setosa"} *) So far so good. Now we need a classifier that can take a new input and a tree to make a classification. classify[x_, Except[_List, d_]] := d classify[x_, {best_, value_, d1_, d2_}] := classify[x, If[x[[best]] < value, d2, d1]] Lets try it out with the first element from our training data. It correctly classifies the iris as species 2 (virginica). classify[{6.4, 2.8, 5.6, 2.1}, tree] (* "virginica *) A random forest is nothing but an ensemble of such trees, created from a bootstrap sample of the data, that allows each one to vote. The function rf takes some input data x , a response vector y , the number of variables to select for splitting m and the number of trees to grow ntree . The function rfClassify takes a new input and a trained forest and makes a classification. rf[x_, y_, m_, ntree_] := Table[boot = RandomChoice[Range[Length[y]], Length[y]]; cart[x[[All, boot]], y[[boot]], m], {ntree}] rfClassify[input_, forest_] := First[#][[maxI[Last[#]]]] &[ Transpose[Tally[classify[input, #] & /@ forest]]] Lets try it on the iris data. First we fit a forest with our training set. And test it to make sure it works well on its own training data. In this case we get perfect classification of our training data so it looks good. f = rf[data[[train, 1 ;; -2]]\[Transpose], data[[train, -1]], 3, 500]; N@ Mean[Boole[ First[#] === Last[#] & /@ Transpose[{rfClassify[#, f] & /@ data[[train, 1 ;; -2]], data[[train, -1]]}]]] (* 1. *) Now lets try it out on the test data it has never seen before. N@ Mean[Boole[ First[#] === Last[#] & /@ Transpose[{rfClassify[#, f] & /@ data[[test, 1 ;; -2]], data[[test, -1]]}]]] (* 0.966667 *) I'd say 97% correct classification isn't bad for a relatively small data set and forest. EDIT: It is worth showing how one might use RLink and the randomForest package in Mathematica with the data I have here. The following code will fit a random forest to the iris data and return the prediction for a particular input newX . (*Enable RLink*) << RLink` InstallR[] (*Set the training data and response*) RSet["x", data[[train, 1 ;; -2]]]; RSet["y", data[[train, -1]]]; RSet["newX", data[[test, 1 ;; -2]][[1]]]; (*install the package. Note: you only need to do this once*) REvaluate["install.packages(\"randomForest\")"]; (*fit a random forest and make one classification*) REvaluate["{ library(randomForest) f = randomForest(x,as.factor(y)) predict(f,newX) }" ] (* RFactor[{1}, RFactorLevels["setosa", "versicolor", "virginica"], RAttributes["names" :> {"1"}]] *)
{ "source": [ "https://mathematica.stackexchange.com/questions/19285", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/4383/" ] }
19,416
Consider the example plotOptions = {PlotPoints -> 10, MaxRecursion -> 2} Plot3D[x y , {x, 0, 10}, {y, 0, 10}, plotOptions] Why does this causes the error: Plot3D::nonopt: Options expected (instead of plotOptions) beyond position 3 in Plot3D[x y,{x,0,10},{y,0,10},plotOptions]. An option must be a rule or a list of rules. >> ? I would say that plotOptions is as list of rules... If I use Plot3D[x y , {x, 0, 10}, {y, 0, 10}, {PlotPoints -> 10, MaxRecursion -> 2}] it works: What is then the correct way of passing a list of options to a plot? One situation on when this happens is when I want to create several plots with the same options.
Lets see the Attributes of Plot3D Attributes[Plot3D] {HoldAll, Protected, ReadProtected} The HoldAll is the reason why your options are not read within the Plot3D command. In such situations (e.g NIntegrate, Plot,..) to resolve the values of a symbol (here options ) within these commands we tend to use Evaluate to forcefully override this attribute. So one solution is Plot3D[x y, {x, 0, 10}, {y, 0, 10},Evaluate@plotOptions] Another solution is to inject the options using With : With[{iPlotOpts = plotOptions}, Plot3D[x y, {x, 0, 10}, {y, 0, 10}, iPlotOpts] ] Another way will be to get rid of this HoldAll globally using ClearAttributes[Plot3D, HoldAll] . Then you can just use Plot3D[x y , {x, 0, 10}, {y, 0, 10}, plotOptions] . But clearing attributes globally is a bad idea in general , as it disrupts the local scoping which is often a must for a function like Plot3D to work seamlessly! Try for example: ClearAttributes[Plot3D, HoldAll]; x = 5; y = 10; Plot3D[x y, {x, 0, 10}, {y, 0, 10}]
{ "source": [ "https://mathematica.stackexchange.com/questions/19416", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/932/" ] }
19,546
Here is a simple building floor plan. I would like to derive the rooms as (rectangular) components and the names of the rooms . This is very common representation of building floor plans. The problem So far I could clean up the floor plan. However, only the walls are left as one component but I would like to derive the rooms as rectangular components . In the solution - The rooms may have polygonal shapes as well as rectangles with small rectangular components called circulation areas, corridors or an other function name... alternatively they could added to living room or any other near function. My Question is how to proceed from here? Code to start with img = Import["http://i.stack.imgur.com/qDhl7.jpg"] nsc = DeleteSmallComponents[Binarize[img, {0, .2}]]; m = MorphologicalTransform[nsc, {"Min", "Max"}] Cleaned up floor plan EDIT 1 Some further information about the image. The image contains 2 types of information. The geometric The Spatial The Spatial information; it is important to abstract the room names for defining adjacency of spaces. The door and windows helps to define the adjacency matrix. The adjacency matrix with the geometric information can be used to calculate areas or boundaries. For example :
EDIT: Updated the algorithm, new part below Fun problem! Ok, my first would be to find the room centers. This is relatively easy using a distance transform and geodesic erosion. distTransform = DistanceTransform[ColorNegate@m]; ImageAdjust[distTransform] The distance transform image contains for every pixel the distance to the closest wall. We're looking for the bright "peak" in the distance transform, i.e. the center of each room. centerAreas = ImageDifference[ GeodesicDilation[Image[ImageData[distTransform] - 10], distTransform], distTransform] EDIT: The next part is new With this, we can use a watershed transform to find the rooms. The watershed transform (intuitively speaking) finds "basins" in a 3d landscape. We'll invert the distance transform image to turn the "peaks" into "basins" and use the room centers as markers: watershed = DeleteSmallComponents[ DeleteBorderComponents[ Binarize[ Image[WatershedComponents[ColorNegate[distTransform], centerAreas]]]], 1000] This segments the rooms quite well. Unfortunately, the watershed transform ignores the walls - the components we found are too big. But they're close enough that this simple "grow the room rectangle until it hits the wall"-algorithm finds the actual room areas: rooms = ComponentMeasurements[watershed, "BoundingBox"]; Clear[growRect] growRect[{{x1_, y1_}, {x2_, y2_}}] := Module[{checkRectEmpty, growSingleDirection, growSingleStep, cx, cy, left, top, right, bottom, sizeEstimate, size}, ( {cx, cy} = Round[{x1 + x2, y1 + y2}/2]; checkRectEmpty[{left_, top_, right_, bottom_}] := Max[ImageValue[ m, {cx - left ;; cx + right, cy - top ;; cy + bottom}]] == 0; growSingleDirection[size_, grow_] := If[checkRectEmpty[size + grow], size + grow, size]; growSingleStep[size_] := Fold[growSingleDirection, size, IdentityMatrix[4]]; sizeEstimate = Abs[Round[{x2 - x1, y2 - y1, x2 - x1, y2 - y1}/2 - 20]]; {left, top, right, bottom} = FixedPoint[growSingleStep, sizeEstimate, 20]; Rectangle[{cx - left, cy - top}, {cx + right, cy + bottom}] )] Using this, all that's left is to display the results: finalRectangles = growRect /@ rooms[[All, 2]]; feetAndInch[n_] := ToString[Round[n/12]] <> "'" <> ToString[Mod[n, 12]] Show[m, Graphics[ { finalRectangles[[ ;; ]] /. rect : Rectangle[{x1_, y1_}, {x2_, y2_}] :> { {EdgeForm[Red], Transparent, rect}, {Red, Text[StringForm["`` x ``\n``", feetAndInch@(x2 - x1), feetAndInch@(y2 - y1), (x2 - x1)*(y2 - y1)/(144.)], {x1 + x2, y1 + y2}/2]} } }]] or, using the original floor plan as background:
{ "source": [ "https://mathematica.stackexchange.com/questions/19546", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/840/" ] }
19,575
I have a function $F$ that maps the xyz space to a set of reals, more clearly: $c = F[x,y,z]$ Where $c$,$x$,$y$ and $z$ are reals. What are the possible ways of visualizing this 3d function in Mathematica? (if possible, please post a how-to-do-it)
One possible way is to use Graphics3D with Point and color points by function value so it's like density plot 3d. For example, xyz = Flatten[ Table[{i, j, k}, {i, 1, 10, .35}, {j, 1, 10, .35}, {k, 1, 10, .35}], 2]; f[x_, y_, z_] := x^2 y Cos[z] Graphics3D[ Point[xyz, VertexColors -> (Hue /@ Rescale[f[##] & @@@ xyz])], Axes -> True, AxesLabel -> {x, y, z}] Another possible choice is just thinking one parameter as time variable and use Manipulate: Manipulate[Plot3D[f[x, y, z], {x, 1, 10}, {y, 1, 10}], {z, 1, 10}] There should be many other way to visualize 4d data, but it's really depending on what you want to see and how you want to visualize. Like amr suggested, you can also use Image3D or Raster3D: values = Rescale[ Table[f[i, j, k], {i, 1, 10, .2}, {j, 1, 10, .2}, {k, 1, 10, .2}]]; Graphics3D[Raster3D[values, ColorFunction -> Hue]] Image3D[values, ColorFunction -> Hue] Image3D[values]
{ "source": [ "https://mathematica.stackexchange.com/questions/19575", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5725/" ] }
19,778
For example, like this: I know Join works, but it is a bit troublesome for multiple matrices. I also tried DiagonalMatrix , but it can only form a matrix from a list of elements.
ybeltukov 's blockArray from Speeding up generation of block diagonal matrix blows the methods below out of the water by orders of magnitude, in terms of performance. a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; b = {{1, 2}, {3, 4}}; ArrayFlatten[{{a, 0}, {0, b}}] // MatrixForm You can Fold this operation over a list of matrices to get a diagonal: a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; b = {{1, 2}, {3, 4}}; c = {{1, 2, 3}, {4, 5, 6}}; d = {{1, 2}, {3, 4}, {5, 6}}; Fold[ArrayFlatten[{{#, 0}, {0, #2}}] &, a, {b, c, d}] // MatrixForm Here is another way to do this, illustrating a forcing of DiagonalMatrix by using an arbitrary head ( Hold ) on top of List : DiagonalMatrix[Hold /@ {a, b, c, d}] // ReleaseHold // ArrayFlatten // MatrixForm (same output) Or a bit more cleanly using Unevaluated (though this may be harder to apply in a program as opposed to interactive input because the elements of your matrix list will probably not be named): DiagonalMatrix[Unevaluated @ {a, b, c, d}] // ArrayFlatten // MatrixForm (same output)
{ "source": [ "https://mathematica.stackexchange.com/questions/19778", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5463/" ] }
19,829
I have a list, such as: testdata = {{1, 317}, {2, 317}, {3, 317}, {4, 317}, {5, 317}, {6, 317}, {7, 318}, {8, 318}, {9, 318}, {10, 318}, {11, 319}, {12, 319}, {13, 319}, {14, 319}, {15, 314}, {16, 314}, {17, 314}, {18, 314}, {19, 314}, {20, 314}, {21, 314}, {22, 314}, {23, 314}, {24, 314}, {25, 314}, {26, 314}, {27, 314}, {28, 306}, {29, 306}, {30, 306}, {31, 306}, {32, 293}, {33, 293}, {34, 293}, {35, 293}, {36, 293}, {37, 293}, {38, 293}, {39, 223}, {40, 223}, {41, 223}, {42, 223}, {43, 154}, {44, 154}, {45, 154}, {46, 154}, {47, 219}, {48, 219}, {49, 219}, {50, 219}, {51, 267}, {52, 267}, {53, 267}, {54, 267}, {55, 293}, {56, 293}, {57, 293}, {58, 293}, {59, 300}, {60, 300}, {61, 300}, {62, 300}, {63, 287}, {64, 287}, {65, 287}, {66, 287}, {67, 273}, {68, 273}, {69, 273}, {70, 248}, {71, 248}, {72, 248}, {73, 248}, {74, 232}, {75, 232}, {76, 232}, {77, 232}, {78, 203}, {79, 203}, {80, 203}, {81, 203}, {82, 180}, {83, 180}, {84, 180}, {85, 180}, {86, 163}, {87, 163}, {88, 163}, {89, 163}, {90, 158}, {91, 158}, {92, 158}, {93, 158}, {94, 179}, {95, 179}, {96, 179}, {97, 179}, {98, 203}, {99, 203}, {100, 203}, {101, 203}, {102, 228}, {103, 228}, {104, 228}, {105, 228}, {106, 228}, {107, 228}, {108, 228}, {109, 228}, {110, 228}, {111, 228}, {112, 228}, {113, 228}, {114, 228}, {115, 230}, {116, 230}, {117, 230}, {118, 230}, {119, 225}, {120, 225}, {121, 225}, {122, 225}, {123, 214}, {124, 214}, {125, 214}, {126, 224}, {127, 224}, {128, 224}, {129, 224}, {130, 228}, {131, 228}, {132, 228}, {133, 228}, {134, 239}, {135, 239}, {136, 239}, {137, 239}, {138, 244}, {139, 244}, {140, 244}, {141, 244}, {142, 232}, {143, 232}, {144, 232}, {145, 232}, {146, 231}, {147, 231}, {148, 231}, {149, 231}, {150, 192}, {151, 192}, {152, 192}, {153, 192}, {154, 128}, {155, 128}, {156, 128}, {157, 128}, {158, 112}, {159, 112}, {160, 112}, {161, 192}, {162, 192}, {163, 192}, {164, 192}, {165, 249}, {166, 249}, {167, 249}, {168, 249}, {169, 257}, {170, 257}, {171, 257}, {172, 257}, {173, 240}, {174, 240}, {175, 240}, {176, 240}, {177, 214}, {178, 214}, {179, 214}, {180, 214}, {181, 200}, {182, 200}, {183, 200}, {184, 200}, {185, 212}, {186, 212}, {187, 212}, {188, 212}, {189, 201}, {190, 201}, {191, 201}, {192, 201}, {193, 173}, {194, 173}, {195, 173}, {196, 140}, {197, 140}, {198, 140}, {199, 140}, {200, 137}, {201, 137}, {202, 137}, {203, 137}, {204, 149}, {205, 149}, {206, 149}, {207, 149}, {208, 164}, {209, 164}, {210, 164}, {211, 164}, {212, 203}, {213, 203}, {214, 203}, {215, 203}, {216, 242}, {217, 242}, {218, 242}, {219, 242}, {220, 270}, {221, 270}, {222, 270}, {223, 270}, {224, 275}, {225, 275}, {226, 275}, {227, 275}, {228, 266}, {229, 266}, {230, 266}, {231, 275}, {232, 275}, {233, 275}, {234, 275}, {235, 285}, {236, 285}, {237, 285}, {238, 285}, {239, 291}, {240, 291}, {241, 291}, {242, 291}, {243, 277}, {244, 277}, {245, 277}, {246, 277}, {247, 271}, {248, 271}, {249, 271}, {250, 271}, {251, 271}, {252, 271}, {253, 271}, {254, 271}, {255, 271}, {256, 271}, {257, 271}, {258, 271}, {259, 271}, {260, 266}, {261, 266}, {262, 266}, {263, 266}, {264, 195}, {265, 195}, {266, 195}, {267, 195}, {268, 128}, {269, 128}, {270, 128}, {271, 128}, {272, 193}, {273, 193}, {274, 193}, {275, 193}, {276, 252}, {277, 252}, {278, 252}, {279, 276}, {280, 276}, {281, 276}, {282, 276}, {283, 271}, {284, 271}, {285, 271}, {286, 271}, {287, 256}, {288, 256}, {289, 256}, {290, 256}, {291, 250}, {292, 250}, {293, 250}, {294, 250}, {295, 236}, {296, 236}, {297, 236}, {298, 236}, {299, 211}, {300, 211}, {301, 211}, {302, 211}, {303, 188}, {304, 188}, {305, 188}, {306, 188}, {307, 165}, {308, 165}, {309, 165}, {310, 165}, {311, 156}, {312, 156}, {313, 156}, {314, 153}, {315, 153}, {316, 153}, {317, 153}, {318, 165}, {319, 165}, {320, 165}, {321, 165}, {322, 191}, {323, 191}, {324, 191}, {325, 191}, {326, 228}, {327, 228}, {328, 228}, {329, 228}, {330, 261}, {331, 261}, {332, 261}, {333, 261}, {334, 267}, {335, 267}, {336, 267}, {337, 267}, {338, 267}, {339, 267}, {340, 267}, {341, 267}, {342, 267}, {343, 267}, {344, 267}, {345, 267}, {346, 267}, {347, 266}, {348, 266}, {349, 266}, {350, 266}, {351, 259}, {352, 259}, {353, 259}, {354, 259}, {355, 258}, {356, 258}, {357, 258}, {358, 258}, {359, 251}, {360, 251}, {361, 251}, {362, 251}, {363, 254}, {364, 254}, {365, 254}, {366, 252}, {367, 252}, {368, 252}, {369, 252}, {370, 260}, {371, 260}, {372, 260}, {373, 260}, {374, 275}, {375, 275}, {376, 275}, {377, 275}, {378, 209}, {379, 209}, {380, 209}, {381, 209}, {382, 136}, {383, 136}, {384, 136}, {385, 136}, {386, 175}, {387, 175}, {388, 175}, {389, 175}, {390, 240}, {391, 240}, {392, 240}, {393, 240}, {394, 267}, {395, 267}, {396, 267}, {397, 267}, {398, 255}, {399, 255}, {400, 255}, {401, 243}, {402, 243}, {403, 243}, {404, 243}, {405, 227}, {406, 227}, {407, 227}, {408, 227}, {409, 218}, {410, 218}, {411, 218}, {412, 218}, {413, 207}, {414, 207}, {415, 207}, {416, 207}, {417, 196}, {418, 196}, {419, 196}, {420, 196}, {421, 195}, {422, 195}, {423, 195}, {424, 195}, {425, 200}, {426, 200}, {427, 200}, {428, 200}, {429, 214}, {430, 214}, {431, 214}, {432, 214}, {433, 229}, {434, 229}, {435, 229}, {436, 229}, {437, 256}, {438, 256}, {439, 256}, {440, 283}, {441, 283}, {442, 283}, {443, 283}, {444, 285}, {445, 285}, {446, 285}, {447, 285}, {448, 293}, {449, 293}, {450, 293}, {451, 293}, {452, 294}, {453, 294}, {454, 294}, {455, 294}, {456, 294}, {457, 294}, {458, 294}, {459, 294}, {460, 293}, {461, 293}, {462, 293}, {463, 293}, {464, 278}, {465, 278}, {466, 278}, {467, 278}, {468, 277}, {469, 277}, {470, 277}, {471, 277}, {472, 266}, {473, 266}, {474, 266}, {475, 251}, {476, 251}, {477, 251}, {478, 251}, {479, 250}, {480, 250}, {481, 250}, {482, 250}, {483, 250}, {484, 250}, {485, 250}, {486, 250}, {487, 250}, {488, 250}, {489, 250}, {490, 250}, {491, 250}, {492, 239}, {493, 239}, {494, 239}, {495, 239}, {496, 159}, {497, 159}, {498, 159}, {499, 159}, {500, 139}, {501, 139}, {502, 139}, {503, 139}, {504, 215}, {505, 215}, {506, 215}, {507, 215}, {508, 267}, {509, 267}, {510, 267}, {511, 267}, {512, 289}, {513, 289}, {514, 289}, {515, 289}, {516, 267}, {517, 267}, {518, 267}, {519, 267}, {520, 256}, {521, 256}, {522, 256}, {523, 256}, {524, 222}, {525, 222}, {526, 222}, {527, 194}, {528, 194}, {529, 194}, {530, 194}, {531, 185}, {532, 185}, {533, 185}, {534, 185}, {535, 181}, {536, 181}, {537, 181}, {538, 181}, {539, 195}, {540, 195}, {541, 195}, {542, 195}, {543, 199}, {544, 199}, {545, 199}, {546, 199}, {547, 199}, {548, 199}, {549, 199}, {550, 199}, {551, 214}, {552, 214}, {553, 214}, {554, 214}, {555, 226}, {556, 226}, {557, 226}, {558, 226}, {559, 255}, {560, 255}, {561, 255}, {562, 268}, {563, 268}, {564, 268}, {565, 268}, {566, 274}, {567, 274}, {568, 274}, {569, 274}, {570, 274}, {571, 274}, {572, 274}, {573, 274}, {574, 274}, {575, 274}, {576, 274}, {577, 274}, {578, 274}, {579, 268}, {580, 268}, {581, 268}, {582, 268}, {583, 270}, {584, 270}, {585, 270}, {586, 270}, {587, 260}, {588, 260}, {589, 260}, {590, 260}, {591, 250}, {592, 250}, {593, 250}, {594, 250}, {595, 230}, {596, 230}, {597, 230}, {598, 230}, {599, 227}, {600, 227}, {601, 227}, {602, 227}, {603, 240}, {604, 240}, {605, 240}, {606, 240}, {607, 240}, {608, 240}, {609, 240}, {610, 235}, {611, 235}, {612, 235}, {613, 235}, {614, 156}, {615, 156}, {616, 156}, {617, 156}, {618, 108}, {619, 108}, {620, 108}, {621, 108}, {622, 190}, {623, 190}, {624, 190}, {625, 190}, {626, 237}, {627, 237}, {628, 237}, {629, 237}, {630, 261}, {631, 261}, {632, 261}, {633, 261}, {634, 242}, {635, 242}, {636, 242}, {637, 242}, {638, 215}, {639, 215}, {640, 215}, {641, 215}, {642, 191}, {643, 191}, {644, 191}, {645, 162}, {646, 162}, {647, 162}, {648, 162}, {649, 160}, {650, 160}, {651, 160}, {652, 160}, {653, 148}, {654, 148}, {655, 148}, {656, 148}, {657, 147}, {658, 147}, {659, 147}, {660, 147}, {661, 160}, {662, 160}, {663, 160}, {664, 160}, {665, 177}, {666, 177}, {667, 177}, {668, 177}, {669, 211}, {670, 211}, {671, 211}, {672, 211}, {673, 234}, {674, 234}, {675, 234}, {676, 234}, {677, 252}, {678, 252}, {679, 252}, {680, 261}, {681, 261}, {682, 261}, {683, 261}, {684, 261}, {685, 261}, {686, 261}, {687, 261}, {688, 259}, {689, 259}, {690, 259}, {691, 259}, {692, 245}, {693, 245}, {694, 245}, {695, 245}, {696, 252}, {697, 252}, {698, 252}, {699, 252}, {700, 267}, {701, 267}, {702, 267}, {703, 267}, {704, 278}, {705, 278}, {706, 278}, {707, 278}, {708, 277}, {709, 277}, {710, 277}, {711, 277}, {712, 267}, {713, 267}, {714, 267}, {715, 267}, {716, 267}, {717, 267}, {718, 267}, {719, 267}, {720, 267}, {721, 267}, {722, 267}, {723, 267}, {724, 267}, {725, 267}, {726, 267}, {727, 267}, {728, 267}, {729, 259}, {730, 259}, {731, 259}, {732, 259}, {733, 177}, {734, 177}, {735, 177}, {736, 132}, {737, 132}, {738, 132}, {739, 132}, {740, 202}, {741, 202}, {742, 202}, {743, 202}, {744, 258}, {745, 258}, {746, 258}, {747, 258}, {748, 285}, {749, 285}, {750, 285}, {751, 285}, {752, 278}, {753, 278}, {754, 278}, {755, 278}, {756, 268}, {757, 268}, {758, 268}, {759, 268}, {760, 251}, {761, 251}, {762, 251}, {763, 251}, {764, 242}, {765, 242}, {766, 242}, {767, 251}, {768, 251}, {769, 251}, {770, 251}, {771, 222}, {772, 222}, {773, 222}, {774, 222}, {775, 186}, {776, 186}, {777, 186}, {778, 186}, {779, 164}, {780, 164}, {781, 164}, {782, 164}, {783, 161}, {784, 161}, {785, 161}, {786, 161}, {787, 177}, {788, 177}, {789, 177}, {790, 177}, {791, 198}, {792, 198}, {793, 198}, {794, 198}, {795, 234}, {796, 234}, {797, 234}, {798, 249}, {799, 249}, {800, 249}, {801, 249}, {802, 249}, {803, 249}, {804, 249}, {805, 249}, {806, 249}, {807, 249}, {808, 249}, {809, 249}, {810, 249}, {811, 249}, {812, 256}, {813, 256}, {814, 256}, {815, 244}, {816, 244}, {817, 244}, {818, 244}, {819, 239}, {820, 239}, {821, 239}, {822, 239}, {823, 248}, {824, 248}, {825, 248}, {826, 248}, {827, 256}, {828, 256}, {829, 256}, {830, 256}, {831, 244}, {832, 244}, {833, 244}, {834, 244}, {835, 228}, {836, 228}, {837, 228}, {838, 228}, {839, 225}, {840, 225}, {841, 225}, {842, 225}, {843, 224}, {844, 224}, {845, 224}, {846, 224}, {847, 222}, {848, 222}, {849, 222}, {850, 222}, {851, 154}, {852, 154}, {853, 154}, {854, 128}, {855, 128}, {856, 128}, {857, 128}, {858, 206}, {859, 206}, {860, 206}, {861, 206}, {862, 262}, {863, 262}, {864, 262}, {865, 262}, {866, 289}, {867, 289}, {868, 289}, {869, 289}, {870, 271}, {871, 271}, {872, 271}, {873, 271}, {874, 244}, {875, 244}, {876, 244}, {877, 244}, {878, 222}, {879, 222}, {880, 222}, {881, 222}, {882, 206}, {883, 206}, {884, 206}, {885, 206}, {886, 196}, {887, 196}, {888, 196}, {889, 183}, {890, 183}, {891, 183}, {892, 183}, {893, 178}, {894, 178}, {895, 178}, {896, 178}, {897, 172}, {898, 172}, {899, 172}, {900, 172}, {901, 171}, {902, 171}, {903, 171}, {904, 171}, {905, 192}, {906, 192}, {907, 192}, {908, 192}, {909, 213}, {910, 213}, {911, 213}, {912, 213}, {913, 249}, {914, 249}, {915, 249}, {916, 279}, {917, 279}, {918, 279}, {919, 279}, {920, 282}}; Q1: I would like to get the peak and valley in the graph and draw it, Q2: I would like to find how many valleys are in this list, Q3: I would like to get the first 200 points and minimum valleys. This is what I've tried so far: ListLinePlot[testdata] Thanks for your help, I have been successful :) this is my code mins=Pick[testdata,MinDetect[testdata[[All,2]]],1]; maxs=Pick[testdata,MaxDetect[testdata[[All,2]]],1]; Show[ListLinePlot[testdata[[All,2]],Filling->Axis,AxesLabel->{number,ECG_Data}],ListPlot[maxs,PlotStyle->Red,PlotLegends->{"Peak"}],ListPlot[mins,PlotStyle->Blue,PlotLegends->{"Valley"}]] Thr=200; findpeak=Position[Differences[MaxDetect[testdata[[All,2]]]],-1]; findvalley=Position[Differences[MinDetect[testdata[[All,2]]]],-1]; peak=Extract[testdata,findpeak]; valley=Extract[testdata,findvalley]; valleysmin200=Select[valley,#[[2]]<Thr&]; f1=ListLinePlot[testdata,AxesLabel->{number,ECG_Data},Filling->Axis,FillingStyle->Automatic]; f2=ListPlot[peak,PlotStyle->{Red,PointSize[Large]},PlotLegends->{"Peak"}]; f3=ListPlot[valley,PlotStyle->{Blue,PointSize[Large]},PlotLegends->{"Valley"}]; f4=ListPlot[valleysmin200,PlotStyle->{Blue,PointSize[Large]},PlotLegends->{"Valley"}]; f5=ListLinePlot[Table[Thr,{Length[testdata]}],PlotStyle -> Pink]; Show[f1,f2,f3] (*modify peak & valley*) Show[f1,f4,f5] (*valley<200*) Length[valleysmin200]/2*12
Perhaps you could try this (only in the current version of Mathematica ): mins = Pick[testdata, MinDetect[testdata[[All, 2]]], 1] maxs = Pick[testdata, MaxDetect[testdata[[All, 2]]], 1] Show[ListLinePlot[testdata[[All, 2]], Filling -> Axis], ListPlot[mins, PlotStyle -> Red], ListPlot[maxs, PlotStyle -> Blue]]
{ "source": [ "https://mathematica.stackexchange.com/questions/19829", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5990/" ] }
19,833
For some reason, when I enter the following integration in Mathematica Assuming[{k ∈ Integers}, Integrate[ Exp[ I k t], {t, -π, π}]] the result turns out to be 0. However, clearly, if $k = 0$, the integral should evaluate to $2\pi$ instead. Can someone explain this behavior?
I can explain this. The definite flavor of Integrate works with assumptions in a few ways. One is to use them in Simplify , Refine , and a few other places that accept Assumptions , to do what they will in the hope of attaining a better result (it also uses them to determine convergence and presence or absence of path singularities). Those places also get the $Assumptions default when there are no explicit Assumptions option settings in Integrate , hence one can do Assuming[...,Integrate[...]] with similar effect. But there is a difference. Simplify et al. return "generic results", so e.g. Sin[ k π]/k will simplify to 0 if told that k is an integer. Simplify[ Sin[ k π]/k, Assumptions-> k ∈ Integers] (* Out[4]= 0 *) Integrate knows Simplify will do this, and wishes it would not (always) be so aggressive. So it takes its Assumptions option and recasts things regarded as Integers into Reals . That's why the related example Integrate[ Exp[ I k t], {t, -π, π}, Assumptions -> {k ∈ Integers}] manages to provide a correct result. But Integrate does not attempt to mess with $Assumptions that may have been set outside its scope. This is what happens when one instead uses the Assuming[...,Integrate[...]] construction. In that case a trig result like the one I showed will be (over?-)simplified to zero. Upshot: Integrate subverts the explicit Integrate assumptions of the user in order to avoid this generic simplification pitfall. It's not clear to me at this point which is the bug and which is the feature. Since there are valid arguments for either, and since I think tangling with global $Assumptions inside Integrate is a risky endeavor, I regard this as best left alone.
{ "source": [ "https://mathematica.stackexchange.com/questions/19833", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5891/" ] }
19,902
I would like to know how can I completely copy one Symbol to another. When I say copy, a refer to UpValues , DownValues , FormatValues .. and so on. I created this function to do that, but I don't know if it's a good practice. SetAttributes[copy,HoldFirst]; copy[new_Symbol,org_Symbol]:=Module[{}, ClearAll@new; UpValues@new=UpValues@org/.org:> new; DownValues@new=DownValues@org/.org:> new; FormatValues@new=FormatValues@org/.org:> new; SetAttributes[new,Attributes[org]]; ] So I can copy some symbol b into a using a~copy~b . There is a simpler way to do that? Or this approach is ok? Update Thanks for all comments. This is the evolution of the function above: SetAttributes[copy,HoldFirst]; new_~copy~org_:=With[{prop={Attributes,UpValues, OwnValues, DownValues, SubValues, NValues, FormatValues, Messages,Options}}, ClearAll@new; Set[#@new,#@org/.HoldPattern@org:>new]&~Scan~prop; ]
Update It turns out that the correct way is to use ExtendedDefinition , not ExtendedFullDefinition . Please see the answer by @jkuczm for a detailed explanation. This is a simplification of your solution: Language`ExtendedFullDefinition[new] = Language`ExtendedFullDefinition[old] /. HoldPattern[old] :> new I believe Language`ExtendedFullDefinition is used in transferring definitions between the main kernel and subkernels. Also note the HoldPattern on the LHS of the rule which ensures that OwnValues will work. One thing to think about is: what should happen if old refers back to itself? Should new keep referring to old , or to itself? This solution, like yours, replaces the old in the definition as well.
{ "source": [ "https://mathematica.stackexchange.com/questions/19902", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/2266/" ] }
19,934
Has anybody used tensors in Mathematica? How to properly work with them? I find Mathematica not very friendly in this field, as I am defining my own functions for lowering & raising indices, multiplication and stuff like that. I was wondering if there is some good package or a secret way to use tensors more properly in Mathematica. For example, I need tensor analysis for general relativity kind of calculations.
Mathematica 9 contains some functionality for working with symbolic tensors . Here's a list of packages in no particular order, that may have some functionality for working with symbolic tensors. TensoriaCalc - intended for basic calculations in general relativity, but not finished (calculates only Christoffel symbols, Riemann and Ricci tensor). Parallel working with many metrics is possible. Symbolic calculations are not supported. FeynCalc grt - intended for basic calculations in general relativity, but full of bugs (only Christoffel symbols fully function). Symbolic calculations are not supported. NCAlgebra , for manipulating non-commuting algebraic expressions and computing non-commutative Gröbner bases. It allows working with symbolic matrices and symbolic block matrices (e.g. symbolic block matrix inversion ). xAct - a package designed by researchers for large scale projects in general relativity; subpackages capable of extensive tensor manipulation (xTensor, xCoba) as well as perturbation theory in general relativity to any order (xPert). Other subpackages can also work with tensor spherical harmonics, spinor computations as well as exterior calculus (diferential forms). GRQUICK MathTensor (non-free) Tensorial (non-free) Ricci (last updated Sep 2011) diffgeo (free) - a very simple package for differential geometry. Works only with given basis and metric GREATER2 (free) - a simple package for tensorial calculations. Aimed more at physicists where e.g. the metric can be input as a line element. OGRe (free) - released in 2021 for Mathematica 12.0 and later. Designed to be both powerful and user-friendly. Especially suitable for general relativity. Allows performing arbitrarily complicated tensor operations, and automatically transforms between index configurations and coordinate systems behind the scenes as needed for each operation. See also the Wikipedia page on Tensor Software .
{ "source": [ "https://mathematica.stackexchange.com/questions/19934", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5981/" ] }
19,944
I'm trying to figure out if a calculation result it's a valid result. As it return a matrix, I need to test that every element it's a number, so I thought this could work... numericTable = Range[12] ~Partition ~ 4; check=( NumberQ/@Flatten@numericTable) /.List->Sequence ; And[check] This should return True or False depending if exist or not a non-numerical element in the matrix. But it returns Sequence[True,True,True,True,True,True,True,True,True,True,True,True] So I don't understand anything, because... In[]:= Sequence[True,True,True,True,True,True,True,True,True,True,True,True]===check And[Sequence[True,True,True,True,True,True,True,True,True,True,True,True]] Out[]= True Out[]= True Where's the catch ???
Mathematica 9 contains some functionality for working with symbolic tensors . Here's a list of packages in no particular order, that may have some functionality for working with symbolic tensors. TensoriaCalc - intended for basic calculations in general relativity, but not finished (calculates only Christoffel symbols, Riemann and Ricci tensor). Parallel working with many metrics is possible. Symbolic calculations are not supported. FeynCalc grt - intended for basic calculations in general relativity, but full of bugs (only Christoffel symbols fully function). Symbolic calculations are not supported. NCAlgebra , for manipulating non-commuting algebraic expressions and computing non-commutative Gröbner bases. It allows working with symbolic matrices and symbolic block matrices (e.g. symbolic block matrix inversion ). xAct - a package designed by researchers for large scale projects in general relativity; subpackages capable of extensive tensor manipulation (xTensor, xCoba) as well as perturbation theory in general relativity to any order (xPert). Other subpackages can also work with tensor spherical harmonics, spinor computations as well as exterior calculus (diferential forms). GRQUICK MathTensor (non-free) Tensorial (non-free) Ricci (last updated Sep 2011) diffgeo (free) - a very simple package for differential geometry. Works only with given basis and metric GREATER2 (free) - a simple package for tensorial calculations. Aimed more at physicists where e.g. the metric can be input as a line element. OGRe (free) - released in 2021 for Mathematica 12.0 and later. Designed to be both powerful and user-friendly. Especially suitable for general relativity. Allows performing arbitrarily complicated tensor operations, and automatically transforms between index configurations and coordinate systems behind the scenes as needed for each operation. See also the Wikipedia page on Tensor Software .
{ "source": [ "https://mathematica.stackexchange.com/questions/19944", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/102/" ] }
20,051
I want Mathematica to express the equation $$-11 - 2 x + x^2 - 4 y + y^2 - 6 z + z^2=0$$ in the form $$(x - 1)^2 + (y - 2)^2 + (z - 3)^2 - 25=0$$ How do I tell Mathematica to do that?
You can use custom transformation rules, for example: -11 - 2 x + x^2 - 4 y + y^2 - 6 z + z^2 //. (a : _ : 1)*s_Symbol^2 + (b : _ : 1)*s_ + rest__ :> a (s + b/(2 a))^2 - b^2/(4 a) + rest returns (* -25 + (-1 + x)^2 + (-2 + y)^2 + (-3 + z)^2 *) The above rule does not account for cases where b is zero, but those are easy to add too, if needed.
{ "source": [ "https://mathematica.stackexchange.com/questions/20051", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/2241/" ] }
20,180
There are numerous examples here, whose end result is the removal of empty brackets {} and empty lists. I still can't find an example of simply removing redundant brackets though. It's hard for me to believe there isn't already a common solution to this problem. Please point me there if I missed it. As I am new to Mathematica I am learning primarily by example so when I ran into this problem I was at a loss of where to even start. For example I have this list as INPUT to a new function: { {{{0, 5}, {1, 4}, {2, 3}, {3, 2}, {4, 1}, {5, 0}}}, {{{1, 5}, {2, 4}, {3, 3}, {4, 2}, {5, 1}}}, {{{2, 5}, {3, 4}, {4, 3}, {5, 2}}}, {{{3, 5}, {4, 4}, {5, 3}}}, {{{4, 5}, {5, 4}}}, {{{5, 5}}, {{5, 5}}} } I would like the new function to generate this list as OUTPUT: { {{0, 5}, {1, 4}, {2, 3}, {3, 2}, {4, 1}, {5, 0}}, {{1, 5}, {2, 4}, {3, 3}, {4, 2}, {5, 1}}, {{2, 5}, {3, 4}, {4, 3}, {5, 2}}, {{3, 5}, {4, 4}, {5, 3}}, {{4, 5}, {5, 4}}, {{5, 5}, {5, 5}} } The actual input TO new function: {{{{0, 5}, {1, 4}, {2, 3}, {3, 2}, {4, 1}, {5, 0}}}, {{{1, 5}, {2, 4}, {3, 3}, {4, 2}, {5, 1}}}, {{{2, 5}, {3, 4}, {4, 3}, {5, 2}}}, {{{3, 5}, {4, 4}, {5, 3}}}, {{{4, 5}, {5, 4}}}, {{{5, 5}}, {{5, 5}}}} The actual output FROM new function: {{{0, 5}, {1, 4}, {2, 3}, {3, 2}, {4, 1}, {5, 0}}, {{1, 5}, {2, 4}, {3, 3}, {4, 2}, {5, 1}}, {{2, 5}, {3, 4}, {4, 3}, {5, 2}}, {{3, 5}, {4, 4}, {5, 3}}, {{4, 5}, {5, 4}}, {{5, 5}, {5, 5}}}
Starting with: a = {{{{0, 5}, {1, 4}, {2, 3}, {3, 2}, {4, 1}, {5, 0}}}, {{{1, 5}, {2, 4}, {3, 3}, {4, 2}, {5, 1}}}, {{{2, 5}, {3, 4}, {4, 3}, {5, 2}}}, {{{3, 5}, {4, 4}, {5, 3}}}, {{{4, 5}, {5, 4}}}, {{{5, 5}}, {{5, 5}}}}; This is probably the simplest: a //. {x_List} :> x A single-pass method Though using ReplaceRepeated is pleasingly concise it is not efficient with deeply nested lists. Because ReplaceAll and ReplaceRepeated scan from the top level the expression will have to be scanned multiple times. Instead we should use Replace which scans expressions from the bottom up. This means that subexpressions such as {{{{6}}}} will have redundant heads sequentially stripped without rescanning the entire expression from the top. We can start scanning at levelspec -3 because {{}} has a Depth of 3; this further reduces scanning. expr = {{1, 2}, {{3}}, {{{4, 5}}}, {{{{6}}}}}; Replace[expr, {x_List} :> x, {0, -3}] {{1, 2}, {3}, {4, 5}, {6}} Here I will use FixedPointList in place of ReplaceRepeated to count the number of times the expression is scanned in the original method: Rest @ FixedPointList[# /. {x_List} :> x &, expr] // Column {{1,2},{3},{{4,5}},{{{6}}}} {{1,2},{3},{4,5},{{6}}} {{1,2},{3},{4,5},{6}} {{1,2},{3},{4,5},{6}} We see that the expression was scanned four times, corresponding to the three levels that were stripped from {{{{6}}}} plus an additional scan where nothing is changed, which is how both FixedPointList and ReplaceRepeated terminate. To see the full extent of this scanning try: expr //. {_?Print -> 0, {x_List} :> x}; Or to merely count the total number of matches attempted: Reap[expr //. {_?Sow -> 0, {x_List} :> x}][[2, 1]] // Length 50 We see that only 7 expressions in total are scanned with the single-pass method: Reap[ Replace[expr, {_?Sow -> 0, {x_List} :> x}, {0, -3}] ][[2, 1]] // Length 7 Timings Let us compare the performance of these two methods on a highly nested expression. fns = {Append[#, RandomInteger[9]] &, Prepend[#, RandomInteger[9]] &, {#} &}; SeedRandom[1] big = Nest[RandomChoice[fns][#] & /@ # &, {{1}}, 10000]; Depth[big] 3264 big //. {x_List} :> x // Timing // First Replace[big, {x_List} :> x, {0, -3}] ~Do~ {800} // Timing // First 0.452 0.468 On this huge expression the single-pass Replace is about 800 times faster than //. .
{ "source": [ "https://mathematica.stackexchange.com/questions/20180", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/6087/" ] }
20,228
The built-in function "Drop" can delete a Matrix's row and column. Typical syntax for "Drop" is as follows: Drop[list,seq1,seq2...] But what if I want to drop a matrix in a way that the indices of the columns to be deleted is not a well ordered sequence? For example the matrix is 10x10, And I want to drop 3,4,7,9 rows and columns in a single time, then how to do it quickly?
I'm sure this question is a duplicate but I cannot find it; I think it may only be duplicated on StackOverflow (I know one duplicate is there). Basic idea A key statement in your question is: I want to drop 3,4,7,9 rows and columns in a single time, then how to do it quickly? I believe this calls for Part which can extract (and by inverse, drop) rows and columns at the same time . You must extract the parts you don't want to drop so use Complement . m = Partition[Range@100, 10]; ranges = Complement[Range@#, {3, 4, 7, 9}] & /@ Dimensions[m] new = m[[##]] & @@ ranges; new // MatrixForm As a self-contained function This is written to handle arrays of arbitrary depth. drop[m_, parts__List] /; Length@{parts} <= ArrayDepth[m] := m[[##]] & @@ MapThread[Complement, {Range @ Dimensions[m, Length @ {parts}], {parts}}] drop[m, {3, 4, 7, 9}, {4, 5, 6}] // MatrixForm Timings user asked how to test the performance of the solutions presented. Here is a very basic series of tests that one might start with. First a custom timing function based on code from Timo: SetAttributes[timeAvg, HoldFirst] timeAvg[func_] := Do[If[# > 0.3, Return[#/5^i]] & @@ Timing@Do[func, {5^i}], {i, 0, 15}] Then the functions to test: dropCarlos[m_, rows_, cols_] /; ArrayDepth[m] > 1 := Delete[Delete[m, List /@ rows]\[Transpose], List /@ cols]\[Transpose] (* copy drop from above *) Then a test function with three parameters. (The parameters are the number of randomly selected rows and columns to drop and dimensions of the array.) test[n_, r_, c_] := With[{ a = RandomReal[9, {r, c}], rows = RandomSample[Range@r, n], cols = RandomSample[Range@c, n] }, {#, timeAvg @ #[a, rows, cols]} & /@ {dropCarlos, drop} ] // TableForm We can now probe a few shapes and sizes of data. (Another option would be plotting these tests but that's best left to a separate question if there is interest.) test[5, 1000, 1000] (* delete only 5 rows and columns from a 1000x1000 array *) dropCarlos 0.006608 drop 0.001248 test[900, 1000, 1000] (* delete all but 100 rows and columns from a 1000x1000 array *) dropCarlos 0.00047904 drop 0.00017472 test[50, 10000, 100] (* delete 50 from a very tall array *) dropCarlos 0.005368 drop 0.001072 test[50, 100, 10000] (* delete 50 from a very wide array *) dropCarlos 0.002496 drop 0.0008992 These tests cover a variety of cases to see if the relative performance of the functions under test change significantly; if they do a method may have hidden strengths or weaknesses. A final test that must be included in the suite is using non -packed data (all the test above were with packed arrays). This is because there are often significant internal optimizations for packed arrays that cannot be used on unpacked data. Because of this a function that is fast on packed arrays might become suddenly slow elsewhere. For this test replace the expression RandomReal[9, {r, c}] with RandomChoice["a" ~CharacterRange~ "z", {r, c}] in the definition of test . This creates an array of strings which cannot be packed. Now run another test : test[250, 1000, 1000] (* this time with an unpacked String array *) dropCarlos 0.009232 drop 0.00424 Notice that while my function is still faster it is not as much faster; this is because Part is particularly well optimized for packed arrays.
{ "source": [ "https://mathematica.stackexchange.com/questions/20228", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/4742/" ] }
20,281
How do I get the coordinates from a contour plot I've done in Mathematica ? For example, I have a two-variable function f[x, y] , for which I can make a contour plot: contour = ContourPlot[f[x, y] == 1, {x, -1, 1}, {y, -1, 1}]; I can access a nested list, containing lists of coordinates, from an exported file using Export["output.m", contour, "TEXT"] but the nested list is inside the function Graphics . I would like to export only the corresponding nested list. What is a straightforward way to do that? Is there a way of doing that by manipulating directly the variable contour ? Edit @Jens solution was Cases[Normal@contour, Line[x_] :> x, Infinity] Is there a way to generalize it? The issue is that Line won't give us the points inside a region. E.g., I would like to get the coordinates corresponding to a region plot: region = RegionPlot[f[x, y] > 1, {x, -1, 1}, {y, -1, 1}];
Since the plot usually is a GraphicsComplex , the extraction is easiest if you first convert using Normal : contour = ContourPlot[x^2 + y^2 == 1, {x, -1, 1}, {y, -1, 1}]; Cases[Normal@contour, Line[x_] :> x, Infinity] This produces a list that shows the coordinates in the order they were drawn. Explanation: The contours in the plot are drawn using the Line command, which takes lists of points (or lists of lists of points). Usually, these points are all collected at the front of the ContourPlot output in the form of a GraphicsComplex , such that each point can later be addressed by using an index from within the Line commands. By applying Normal , these indexed points are moved to where they are actually used in the drawing part of the output. Normal@contour is the same as Normal[contour] . After that is done, we can look for all Line commands and find the coordinates in sequential order inside of them. This is done by using Cases , which selects parts of the expression that match a pattern. The pattern is specified here as Line[x_] where x_ is a "dummy variable" that gets defined whenever a Line was found, by replacing it with the contents of the line. The final step is to tell Cases that when it does find a value for x , to just output that without the wrapper Line . This search is done throughout the whole plot, which is indicated by the Infinity level specification. Update for RegionPlot Extracting points from a plot using Cases can be generalized to situations where the points aren't inside a Line . In RegionPlot , for example, you may want to extract the points that form the mesh with which the region is filled. This filling is done by a polygonal tesselation, so we have to simply replace Line with Polygon : region = Normal@RegionPlot[x^2 + y^2 <= 1, {x, -1, 1}, {y, -1, 1}]; pts = DeleteDuplicates@ Flatten[Cases[region, Polygon[x_] :> x, Infinity], 1]; Graphics[Point[pts]] Here I had to add two more steps before being able to make the plot: first, Flatten is used to remove all nested levels except the ones grouping the coordinate tuples for each point. Then, I added DeleteDuplicates just to remove any shared vertices between polygons, so one and the same point isn't re-drawn redundantly.
{ "source": [ "https://mathematica.stackexchange.com/questions/20281", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/6082/" ] }
20,284
I'm having problems working with the output from DSolve whilst in a module. To handle the result outside a module typically I would do something like f[t] = y[t] /. solution But inside a module my t is now t$ followed by some numbers. How can I create and return a function from the output of DSolve inside a module? Here is my code: Module[{equations,solution,h,t}, m=1; g=9.8; equations = {y''[t]== -m g,y'[0]==100,y[0]==0}; solution = Flatten@ DSolve[equations,y,t]; h[t] = y[t] /. solution; h[1]] I get h = 100. t$16608-4.9 t$16608^2 , but h[1] = h$16909[1) .
Since the plot usually is a GraphicsComplex , the extraction is easiest if you first convert using Normal : contour = ContourPlot[x^2 + y^2 == 1, {x, -1, 1}, {y, -1, 1}]; Cases[Normal@contour, Line[x_] :> x, Infinity] This produces a list that shows the coordinates in the order they were drawn. Explanation: The contours in the plot are drawn using the Line command, which takes lists of points (or lists of lists of points). Usually, these points are all collected at the front of the ContourPlot output in the form of a GraphicsComplex , such that each point can later be addressed by using an index from within the Line commands. By applying Normal , these indexed points are moved to where they are actually used in the drawing part of the output. Normal@contour is the same as Normal[contour] . After that is done, we can look for all Line commands and find the coordinates in sequential order inside of them. This is done by using Cases , which selects parts of the expression that match a pattern. The pattern is specified here as Line[x_] where x_ is a "dummy variable" that gets defined whenever a Line was found, by replacing it with the contents of the line. The final step is to tell Cases that when it does find a value for x , to just output that without the wrapper Line . This search is done throughout the whole plot, which is indicated by the Infinity level specification. Update for RegionPlot Extracting points from a plot using Cases can be generalized to situations where the points aren't inside a Line . In RegionPlot , for example, you may want to extract the points that form the mesh with which the region is filled. This filling is done by a polygonal tesselation, so we have to simply replace Line with Polygon : region = Normal@RegionPlot[x^2 + y^2 <= 1, {x, -1, 1}, {y, -1, 1}]; pts = DeleteDuplicates@ Flatten[Cases[region, Polygon[x_] :> x, Infinity], 1]; Graphics[Point[pts]] Here I had to add two more steps before being able to make the plot: first, Flatten is used to remove all nested levels except the ones grouping the coordinate tuples for each point. Then, I added DeleteDuplicates just to remove any shared vertices between polygons, so one and the same point isn't re-drawn redundantly.
{ "source": [ "https://mathematica.stackexchange.com/questions/20284", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5570/" ] }
20,367
If I evaluate this expression: Module[{}, 1/0;0^0]; msg = $MessageList I get: "Power::infy: Infinite expression 1/0 encountered. >>" "Power::indet: Indeterminate expression 0^0 encountered. >>" {Power::infy,mrtError::function} How can I collect the complete error messages in msg , instead of just the first part? Something for msg like: {"Power::infy: Infinite expression 1/0 encountered. >>" ,"Power::indet: Indeterminate expression 0^0 encountered. >>"} Some clue?
Update See here for a documented way to do the very same thing in v10.0 or later. This method will only catch those messages which would actually get printed, not those which are Quiet ed or turned Off . We can use handlers: messages = {} clearMessages[] := messages = {} collectMessages[m_] := AppendTo[messages, m] Internal`AddHandler["Message", collectMessages] Then do clearMessages[] 1/0; 0/0; messages Internal`RemoveHandler["Message", collectMessages] Reference and details: How to abort on any message generated?
{ "source": [ "https://mathematica.stackexchange.com/questions/20367", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/2266/" ] }
20,464
I have some numerical data from which I generate a PDF via: pdf = HistogramDistribution[data]; Which can then be easily visualised thus: DensityPlot[PDF[pdf, {x, y}], {x, 1.5, 3.3}, {y, -46, -44}, PlotPoints -> 100] What I would like to do is be able to quickly draw 90% credible intervals on top of this plot.
In comments it became clear that the question seeks a 90% credible region . This would be a region in which 90% of the probability occurs. Among such regions, a unique and natural one to choose is where the minimum value of the probability density is as large as possible (a "highest probability density set"). Such a region is bounded by an isocontour of the density. That isocontour can be found with a numeric search. To illustrate, let's generate and display some moderately interesting data. These are draws from a mixture of two bivariate normals: base = RandomVariate[BinormalDistribution[{2.4, -44.9}, {0.25, 0.3}, 2/3], 400]; contam = RandomVariate[BinormalDistribution[{2.4, -45.3}, {0.1, 0.2}, -0.9], 100]; data = base~Join~contam; ListPlot[{base, contam}] We need an estimate of the PDF that can readily be integrated; it should also be reasonably smooth. This suggests a kernel density rather than a histogram density (which is not smooth). Although there is some latitude to choose the bandwidth, reasonable choices will produce similar credible intervals. A Gaussian kernel assures smoothness: pdf = SmoothKernelDistribution[data, 0.1, "Gaussian"]; plot = ContourPlot[PDF[pdf, {x, y}], {x, 1.5, 3.3}, {y, -46, -44}, PlotRange -> {Full, Full, Full}, Contours -> 23, ColorFunction -> "DarkRainbow"] To find the credible region we will need to compute probabilities for regions defined by probability density thresholds $t$. Let's define the integrand in terms of $t$ and then numerically find which $t$ achieves the desired level by means of FindRoot . There may be problems with some root-finding methods (they can have trouble computing Jacobians) and there will be convergence issues with the numerical integration (Gaussians and other rapidly-decreasing kernels will do that), but fortunately we need relatively little accuracy for any of these computations. Here, the initial bracketed values of $0$ and $2$ for the threshold were read off the contour plot (there are some simple ways to estimate them from the ranges of the data and the kernel bandwidth). f[x_, y_, t_: 0] := With[{z = PDF[pdf, {x, y}]}, z Boole[z >= t]]; r = FindRoot[NIntegrate[f[x, y, t], {x, 1.5, 3.3}, {y, -46, -44}, AccuracyGoal -> 3, PrecisionGoal -> 6] - 0.9, {t, 0, 2}, Method -> "Brent", AccuracyGoal -> 3, PrecisionGoal -> 6] $\{t\to 0.218172\}$ There's our threshold: the credible region consists of all $(x,y)$ where the PDF equals or exceeds this value. Due to the low accuracy and precision goals used in the search, though, it behooves us to double-check it using better accuracy. We want the integral to be close to $0.90$: NIntegrate[f[x, y, t /. r], {x, 1.5, 3.3}, {y, -46, -44}] /. r $0.900042$ That's more than close enough. (If we were to obtain another $500$ independent samples of this distribution, its $90$% quantile could easily lie anywhere between the $87$th and $93$rd quantiles of this sample. Thus, we shouldn't demand more than a few percentage points accuracy when estimating the $90$% credible region. Clearly the accuracy depends on the sample size, but even so it would be rare to pin a $90$% quantile down to better than $0.1$% or so.) To display the solution, we may overlay a contour of the PDF at that threshold on the original plot. ci = ContourPlot[PDF[pdf, {x, y}] == (t /. r), {x, 1.5, 3.3}, {y, -46, -44}, ContourStyle -> Directive[Thick, White]]; Show[plot, ci] If you request too much detail, by using too small a bandwidth, you can run into problems. Here, I halved the bandwidth from $0.1$ to $0.05$. The excessive detail has broken the contours up and created "islands" of locally high density. That's usually unrealistic. We can conclude in this example that the bandwidth of $0.1$ is about as small as we would care to use; it's a reasonable compromise between excessive detail and excessive smoothing. Comparing this credible region contour to the preceding one gives some indication of how much the region itself may depend on small, incidental, arbitrary decisions during the analysis: there's considerable uncertainty about its precise position in $(x,y)$ coordinates. However, no matter which of these contours we were to use, we would have reasonable confidence that they enclose somewhere around $87$% to $93$% of the true probability and that interval could be narrowed by collecting more data.
{ "source": [ "https://mathematica.stackexchange.com/questions/20464", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5754/" ] }
20,470
I couldn't find a more descriptive title, but I guess an example will explain my problem. I set up some customized Grid function including some additional functionalities which I control with custom Options. Additionally, I would like to change some of the standard Grid Options, e.g. always use Frame->All . Take the following working example: Options[myGrid] = {Frame -> All, "Tooltip" -> False}; myGrid[content_, opts : OptionsPattern[]] := Module[{con}, If[OptionValue["Tooltip"], con = MapIndexed[Tooltip[#1, #2] &, content, {-1}], con = content ]; Grid[con, Sequence @@ FilterRules[{opts}~Join~Options[myGrid], Options[Grid]] ] ] defining an example content: mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; We can test the behavior: myGrid[mat] The custom "Tooltip" flag works as intended. Now I want to pass an Option to Grid , that has not been explicitely set in the above Options[myGrid] declaration.This eventually makes it through to the Grid, but produces an error message. myGrid[mat, Background -> Blue] To get rid of the errors I embed the Options from Grid into my custom function: Options[myGrid] = Join[ {Frame -> All, "Tooltip" -> False}, Options[Grid] ]; Now, I can change the Grid Options without raising an error: myGrid[mat, Background -> Green] but the custom setting Frame->All gets lost. myGrid[mat, Frame -> All] Apparently, the default Frame->None setting for Grid overrules my custom setting. I banged my head against this problem for too long already, therefore my plea for your assistance.
OptionsPattern : Therefore declare Options for both myGrid and Grid as valid: Options[myGrid] = {Frame -> All, "Tooltip" -> False}; myGrid[content_, opts : OptionsPattern[{myGrid, Grid}]] := . . . Then: myGrid[mat, Background -> Blue] Grid[mat, Background -> RGBColor[0, 0, 1], Frame -> All] With no error message.
{ "source": [ "https://mathematica.stackexchange.com/questions/20470", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/135/" ] }
20,557
I was trying to create a Matrix falling code image with Mathematica. Here is my code: mcolors=Blend[{{0.00,Darker[Green,0.7]},{0.90,Darker@Green},{0.90,Lighter[Green]},{1.00,Lighter[Green,0.9]}},#]&; (*DensityPlot[x,{x,0,1},{y,0,1},ColorFunction\[Rule]mcolors,ColorFunctionScaling\[Rule]False,AspectRatio\[Rule]0.2]*) stringColum[n_,opacity_]:=Module[{letters,fallingCode}, letters=MapIndexed[Text@Style[#1,mcolors[#2[[1]]/n],Opacity[opacity],Bold,14,FontFamily->"Courier"]&,FromCharacterCode/@RandomInteger[{48,90},n]]; fallingCode=Column[ letters ,Background->None ,Spacings->-0.4 ,Alignment->Center ] ] layer1=Graphics[Table[Inset[stringColum[RandomInteger[{1,30}],1.0],Scaled[{i,RandomReal[{0.7,1}]}],Top],{i,0.000,1,0.05}],PlotRange->All]; layer2=Graphics[Table[Inset[stringColum[RandomInteger[{1,30}],0.4],Scaled[{i,RandomReal[{0.7,1}]}],Top],{i,0.025,1,0.05}],PlotRange->All]; Show[layer1,layer2,AspectRatio->1,Background-> Black,ImageSize-> {600,500}] Where I get as result images like this: Not very exciting when compared to this one: How can I improve that? Some itens that I see. I see a blur that I don't know as to reproduce using Blur , for different layers. The letter are not just A to Z letters. The columns space are not linear. I don't like the way I handler all the code. It's sound to complex in Graphics part.
First, define the dimensions and colors associated with our matrix: {mheight, mwidth} = mdim = {12, 20}; mdepth = 20; mcolors = Reverse@Array[ Blend[{{0, Darker[Green, 0.9]}, {0.4, Darker[Green]}, {0.6, Darker[Green]}, {0.90, Lighter[Green]}, {1, Lighter[Green, 0.8]}}, #/(mdepth - 1)] &, mdepth, 0]; Next, define some useful character ranges: crange[digits] = Range[48, 57]; crange[punc] = Join[Range[33, 47], Range[58, 64], Range[91, 96], Range[123, 126]]; crange[lower] = Range[97, 122]; crange[upper] = Range[65, 90]; crange[hebrew] = Range[1488, 1514]; crange[greeklower] = Range[945, 969]; crange[greekupper] = DeleteCases[Range[913, 937], 930]; crange[cyrillicupper] = Range[1040, 1071]; crange[cyrilliclower] = Range[1072, 1103]; crange[katakana] = Range[12449, 12538]; crange[hiragana] = Range[12353, 12438]; crange[hangul] = Range[44032, 55211]; crange[hanzi] = Range[13312, 19901]; If you look at the matrix image, they don't really use that many funny characters, just a sprinkling, and they don't use all available sets. Here's a nice mix: mrandomchar := FromCharacterCode[ RandomChoice[ crange[RandomChoice[{0.5, 0.1, 0.3, 0.01, 0.04, 0.04} -> {digits, punc, upper, katakana, greeklower, cyrillicupper}]]]] The graphic will be made by masking characters onto swatches of our colors, which we make here: black = Rasterize[ Grid[{{""}}, Background -> Black, ItemSize -> {1, 1}, Spacings -> 0], Background -> Black, RasterSize -> 20, ImageSize -> 20]; greens = Rasterize[ Grid[{{""}}, Background -> #, ItemSize -> {1, 1}, Spacings -> 0], Background -> #, RasterSize -> 20, ImageSize -> 20 ] & /@ mcolors; We initialize the matrix to blackness and add a drip in the middle to start things off: init := Module[{}, drips = {{0, mwidth/2}}; ClearAll[matrix]; matrix = Array[{mdepth + 1, black} &, mdim];] At each step, we let the drips drip down one square. We add new drips with Poisson-distributed probability with expectation 0.8 drips per step. Each time a character has achieved 1/5 of maximum age, we blur it more and we track the age of each character. We also throw some random character blips in with Poisson expectation 0.5 per step. step := Module[{}, drips = Join[ Select[# + {1, 0} & /@ drips, First[#] <= mheight &], {1, #} & /@ RandomInteger[{1, mwidth}, {Random[PoissonDistribution[0.8]]}]]; matrix = Map[ If[#[[1]] >= mdepth, {mdepth + 1, black}, {#[[1]] + 1, If[Mod[#[[1]], Ceiling[mdepth/5]] == 0, Blur, Identity][#[[ 2]]]}] &, matrix, {2}]; (matrix[[##]] = {1, Rasterize[ Grid[{{Style[mrandomchar, mcolors[[1]], FontFamily -> "Courier", FontWeight -> Bold]}}, Background -> Black, ItemSize -> {1, 1}, Spacings -> 0], Background -> Black, RasterSize -> 20, ImageSize -> 20]}) & @@@ Join[drips,(*dots*) Table[{RandomInteger[{1, mheight}], RandomInteger[{1, mwidth}]}, {Random[ PoissonDistribution[0.5]]}]];] Iterate this for a hundred steps to get a nice animation: init; anim = {}; Monitor[Do[step; AppendTo[anim, matrix], {i, 100}], i] Render the graphic: Parallelize[ Show[ImageAssemble[ Map[If[#[[1]] <= mdepth, ImageMultiply[greens[[#[[1]]]], #[[2]]], #[[2]]] &, #, {2}]], ImageSize -> Automatic] & /@ anim] Resulting in EDIT: Update for speed! I originally envisioned this answer as being updated in real-time, not just exported to a graphic. These improvements will get us closer. First, prerender all our characters; calls to Rasterize take at least 0.3s, which is too long for dynamic updating. As long as we don't prerender Hangul or Hanzi, this takes less than a minute and a few MB. (raster[#] = ColorConvert[ Rasterize[ Grid[{{Style[FromCharacterCode[#], White, FontFamily -> "Courier", FontWeight -> Bold]}}, ItemSize -> {1, 1}], Background -> Black, RasterSize -> 20, ImageSize -> 200], "Grayscale"]) & /@ Join @@ (crange /@ {digits, punc, lower, upper, hebrew, greeklower, greekupper, cyrilliclower, cyrillicupper, katakana, hiragana}); Now we just need a random code instead of a random character: mrandomcode := RandomChoice[ crange[RandomChoice[{0.5, 0.1, 0.3, 0.01, 0.04, 0.04} -> {digits, punc, upper, hebrew, greeklower, cyrillicupper}]]] Make sure that our black is also in grayscale; in this new scheme, we don't need the greens at all, just the colors. black = ColorConvert[ Rasterize[Grid[{{""}}, ItemSize -> {1, 1}], Background -> Black, RasterSize -> 20, ImageSize -> 20], "Grayscale"] This lets us take the expensive calls to Rasterize out of our update step. Reversing the update order saves us calls to Blur when the blurred character is about to get clobbered anyway. step := (drips = Join[Select[# + {1, 0} & /@ drips, First[#] <= mheight &], {1, #} & /@ RandomInteger[{1, mwidth}, {Random[PoissonDistribution[0.8]]}]]; (matrix[[##]] = {0, raster[mrandomcode]}) & @@@ Join[drips,(*dots*) Table[{RandomInteger[{1, mheight}], RandomInteger[{1, mwidth}]}, {Random[ PoissonDistribution[0.5]]}]]; matrix = Map[If[#[[1]] >= mdepth, {mdepth + 1, black}, {#[[1]] + 1, If[Mod[#[[1]], Ceiling[mdepth/5]] == 0 && #[[1]] > 0, Blur, Identity][#[[2]]]}] &, matrix, {2}]) On my system, step now takes 0.06s and the render takes 0.08s, so now we can enjoy the proceedings in a dynamic graphic: Dynamic[Show[ ImageAssemble[ Map[If[#[[1]] <= mdepth, ImageMultiply[#[[2]], mcolors[[Max[1, #[[1]]]]]], #[[2]]] &, matrix, {2}]], ImageSize -> Automatic]] init; anim = Table[step, {i, 100}];
{ "source": [ "https://mathematica.stackexchange.com/questions/20557", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/2266/" ] }
20,696
Any suggestions on how to determine a Voronoi diagram for sites other than points, as e.g. in the picture below? The input is a raster image.
Obtain the image: i = Import["http://i.stack.imgur.com/iab6u.png"]; Compute the distance transform: k = DistanceTransform[ColorNegate[i]] // ImageAdjust; ReliefPlot[Reverse@ImageData[k]] (* To illustrate *) Identify the "peaks," which must bound the Voronoi cells: l = ColorNegate[Binarize[ColorNegate[LaplacianGaussianFilter[k, 2] // ImageAdjust]]]; Clean the result and identify its connected components (the cells): m = Erosion[Dilation[MorphologicalComponents[l] // Colorize, 2], 1]; Show this with the original features: ImageMultiply[m, ColorNegate[i]] Edit A cleaner solution--albeit one that takes substantially more processing time--exploits WatershedComponents (new in Version 8): l = WatershedComponents[k]; m = Dilation[MorphologicalComponents[l] // Colorize, 1] (* Needs little or no cleaning *) ImageMultiply[m, ColorNegate[i]] (* As before *) I like this one better, but fear it might take too much processing for large complex images.
{ "source": [ "https://mathematica.stackexchange.com/questions/20696", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5711/" ] }
20,766
Using global variables the following turns an "expression" into a Function : expr = 2 x; Function[x, Evaluate[expr]] Of course this doesn't work if for some reason a value is assigned to x . Thus, I want to turn expr into a Function inside a Module . But it seems like there is a scoping problem: Module[{x, expr}, expr = 2 x; Function[x, Evaluate[expr]] ] (* Function[x$, 2 x$1713] *) Clearly, the x used in the first argument of Function is not the same as the x in the second. I played around with Evaluate and even with Replace and Slot , also trying to create a function with an anonymous variable, but didn't succeed. The only way that I managed to get the right result is this one involving strings: Module[{x, expr}, expr = 2 x; "(" <> StringReplace[ToString@expr, ToString@x -> "#1"] <> ")&" // ToExpression ] Is there a simpler, more straight-forward way to achieve this, without ever using any global variables?
Scoping constructs, lexical scoping and variable renamings It pays off to understand a bit deeper how the scoping constructs work and what happens behind the scenes when you execute one. In addition to the documentation , this was discussed in part here , but let us present some summary. When the lexical scoping construct Sc[vars, body] executes (where Sc can stand for constructs such as With , Module , Function ), evaluation roughly happens via the following steps (or at least this represents our current understanding of it): First, the list of local variables vars is analyzed. The body is analyzed, and the presence of inner scoping constructs is tested. This test is performed verbatim, so that, to be detected, some inner scoping construct ScInner has to be present in body in the form ScInner[innerVars, innerBody] . If the inner scoping construct is dynamically generated at run-time (via ScInner @@ ... or otherwise), it is not detected by Sc during this stage. If some inner scoping constructs are found where some variables conflict with vars , then Sc renames them. It is important to stress that it is Sc that does these renamings in the inner scoping constructs. Indeed, those are inert during that stage (since Sc has HoldAll attribute and so body is kept unevaluated), so Sc is the only function in a position to do those renamings. The actual variable binding happens. The body is searched for instances of vars , and those instances are lexically bound to the variables. Depending on the nature of the scoping construct, further actions may be performed. Function does nothing, With performs the replacements of symbols (variables) with their values in body (according to bindings), while Module creates var$xxx variables (according to the bindings, both in the initialization and body), and then performs variables initializations. The code in body is actually allowed to evaluate. How to fool scoping constructs From the above description, it is clear that, if one wants to avoid renamings for some inner lexical scoping construct ScInner[innerVars, innerBody] for whatever reason, one has to dynamically generated this code, so that it is not present inside Sc verbatim. Again, depending on the situation, one may or may not want to evaluate innerVars and innerBody . More often than not one wants to prevent such evaluation, so it is typical to use something like With[{y = boundToZ}, With @@ Hold[{y = z}, boundToZ]] or With[{y = boundToZ}, Hold[{y = z}, boundToZ] /. Hold -> With] or anything else that would prevent the innerVars or innerBody from unwanted early evaluation. Here is a more meaningful example. The following is a new scoping construct, which executes some code code with a variable var bind to a current value extracted from a Java iterator object: ClearAll[javaIterate]; SetAttributes[javaIterate, HoldAll]; javaIterate[var_Symbol, code_][iteratorInstance_?JavaObjectQ] := While[iteratorInstance@hasNext[], With @@ Hold[{var = iteratorInstance@next[]}, code] ]; The iteratorInstance is expected to be a Mathematica reference for Java object implementing Iterator interface. The variable var is bound to the current value of the iterator (extracted via iteratorInstance@next[] ), using With . This is non-trivial, since we construct this With from pieces, and therefore generate lexical binding of this var to the occurrences of var in code , at every iteration of the While loop. In this case, the outer protecting scoping construct is actually SetDelayed . And we need the construct With @@ Hold[...] to prevent variable var renaming, which is exactly what we don't want here. However, there are cases, where we do want some or all of innerVars or innerBody to evaluate before the binding stage for the inner scoping constructs. The case at hand falls into this category. In such a case, perhaps the most straight-forward way is to use Sc @@ {innerVars, innerBody} , which is what acl did in his answer. The case at hand It is now clear why this solution works: Module[{x, expr}, expr = 2 x; Function @@ {x, expr} ] Function[x$5494, 2 x$5494] Since there wasn't a line Function[x,...] present verbatim, Module did not detect it. And since we do want the variable and body to evaluate before Function performs the variable bindings, the second version ( Function @@ {...} ) has been used. You will note that Evaluate is not needed because List is does not have the HoldAll attribute. This specific syntax is not the only approach. For example h[x, expr] /. h -> Function or ReplacePart[{x, expr}, 0 -> Function] would also work because there is not an explicit Function[x, . . .] in the code. It is instructive to realize that this version works too: Module[{x, expr}, expr = 2 x; Function[Evaluate[x], Evaluate[expr]] ] while Function[...] is present here, the presence of extra Evaluate around x in Function made it impossible for Module to detect the conflict. Of course, there are many other ways one can achieve the same effect. It is now also clear why the following will not work: Module[{x, expr}, expr = 2 x; Function[x, z] /. z -> expr ] Function[x, 2 x$151] The point is, the substitution z -> expr happens only at the stage when the body of the Module is evaluated, while the binding stage happens earlier (as described above). During the binding stage, Module detects the name conflict all right, and of course renames. Only then is x converted into a newly created x$151 , and only after all that the code inside Module executes - by which time it is too late since the symbols inside Function and expr are different. The case of Block Block is a natural approach when guarding against global values, but as Szabolcs comments it must be used with care. Block is not seen a scoping construct for the purposes of the automatic renaming described in the tutorial. You can also see some additional relevant discussion here . Because of that you will not get the "protection" that you may be accustomed to. Using Szabolcs's example: f[z_] := Block[{x, expr}, expr = 2 x + z; Function[x, Evaluate[expr]]] f[x] Function[x, 3 x] Note that this function will triple its argument rather than doubling and adding Global`x which may or may not be what you were expecting. Such injection is often very useful but at the same time if you are accustomed to the automatic renaming behavior (even if you are unaware of the mechanism) this may come as a surprise.
{ "source": [ "https://mathematica.stackexchange.com/questions/20766", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/4296/" ] }
20,836
I'm trying to create a chart usually called "Helio chart". It's a chart type very suited for canonical correlation analysis involving several dependent and independent variables. However, it is a little bit difficult to find good examples of for this chart on the web and the best example I have can be found on the 6th page of this paper on the NASA website: http://ti.arc.nasa.gov/m/profile/adegani/Canonical%20Correlation.pdf It is possible to create such a chart in Mathematica?
Here's some code that could help you to start: sample data: data = RandomReal[{-1, 1}, 30]; plot: angleBar[max_, length_: .1][{{t0_, t1_}, {r0_, r1_}}, v_, meta_] := Block[{angle, coords, x, y}, angle = t0 + (t1 - t0)/2; coords = {Cos[angle], Sin[angle]}; x = r0 coords; y = r1 coords; {{Gray, Dashed, Line[{x, y}]}, {Black, If[meta[[1]] > 0, EdgeForm[],FaceForm[White]], Translate[ Rotate[Scale[ Rectangle[{0, -.5}, {1, .5}], { meta[[1]]/max, length}, {0, 0}], angle, {0, 0}], x]} } ]; newdata = 1 -> # & /@ data; max = Max[Abs[data]]; PieChart[newdata, ChartElementFunction -> angleBar[1.3 max, .1], SectorOrigin -> {Automatic, 1.5}, PolarGridLines -> {None, {0, 1.5}}, PerformanceGoal -> "Speed"] I added names and grouping. angleBarName[max_, length_: .1][{{t0_, t1_}, {r0_, r1_}}, v_, meta_] := Block[{angle, coords, x, y, tangle, offset}, angle = t0 + (t1 - t0)/2; coords = {Cos[angle], Sin[angle]}; x = r0 coords; y = r1 coords; If[Pi/2 <= Mod[angle, 2 Pi] <= 3/2 Pi, tangle = angle + Pi; offset = {1, 0}, tangle = angle; offset = {-1, 0}]; {{Gray, Dashed, Line[{x, 1.2 y}]}, {Black, If[meta[[1, 1]] > 0, EdgeForm[], FaceForm[White]], Translate[ Rotate[Scale[ Rectangle[{0, -.5}, {1, .5}], {meta[[1, 1]]/max, length}, {0, 0}], angle, {0, 0}], x]}, Translate[ Rotate[Text[Style[meta[[1, 2]], "Title", 10, Black], {0, 0}, offset], tangle, {0, 0}], 2.1 x]}]; angleBarName[max_, length_: .1][{{t0_, t1_}, {r0_, r1_}},v_, {{"Group", msize_}}] := Block[{angle, end, start, offset}, If[v == msize, {}, offset = (t1 - t0)/(v/msize *2); start = {Cos[t0 + offset], Sin[t0 + offset]}; end = {Cos[t1 - offset], Sin[t1 - offset]}; {Black, Thick, Line[{2.7 start, 3 start}], Line[{2.7 end, 3 end}], Circle[{0, 0}, 2.7, {t0 + offset, t1 - offset}]}]]; angleBarName[max_, length_: .1][{{t0_, t1_}, {r0_, r1_}}, v_, {"LineBreaker"}]:= {} Sample data with names and grouping: data = Transpose[{RandomReal[{-2, 2}, 30], ChemicalData[][[;; 30]]}]; max = Max[Abs[data[[All, 1]]]]; getherdata = GatherBy[data, StringTake[#[[2]], 1] &]; gdata = Length[#] -> {"Group",1} & /@ getherdata; newdata = 1 -> # & /@ Flatten[getherdata, 1]; Chart: PieChart[{newdata, gdata}, ChartElementFunction -> angleBarName[1.1 max, .1], SectorOrigin -> {{Pi/2, "Clockwise"}, 1.5}, PolarGridLines -> {None, {1.5}}, PerformanceGoal -> "Speed", PlotRange -> All] I edited code to give space in the middle. To do that, I assumed the given data already separated into two part. filterData[data_] := Block[{fdata, size}, fdata = Flatten[data, 1]; size = 1/Length[fdata]; {Join[{.005 -> "LineBreaker"}, size -> # & /@ fdata, {.005 -> "LineBreaker"}], Join[{.005 -> "LineBreaker"}, (size Length[#]) -> {"Group", size} & /@ data, {.005 -> "LineBreaker"}]} ] sample data: data = Transpose[{RandomReal[{-2, 2}, 22], ChemicalData[][[;; 22]]}]; ldata = GatherBy[data[[;; 7]], StringTake[#[[2]], 1] &]; rdata = GatherBy[data[[8 ;;]], StringTake[#[[2]], 1] &]; draw chart: max = Max[Abs[ldata[[All, 1, 1]]], Abs[rdata[[All, 1, 1]]]]; newdata = MapThread[Join, {filterData[rdata], filterData[ldata]}]; PieChart[newdata, ChartElementFunction -> angleBarName[1.2 max, .1], SectorOrigin -> {{Pi/2, "Clockwise"}, 1.5}, PolarGridLines -> {None, {1.5}}, PerformanceGoal -> "Speed", PlotRange -> All, Epilog -> {Orange, Thick, Line[{{0, -4.5}, {0, 4.5}}]}]
{ "source": [ "https://mathematica.stackexchange.com/questions/20836", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5369/" ] }
20,851
Does Mathematica have a graphics option that makes plots intelligible for people with colorblindness?
A nice set of color-blind proof and print friendly color schemes can be find here (see also the pdf ). Actually, the distinct color scheme describe in the above links is not very different from the default Mathematica color set.
{ "source": [ "https://mathematica.stackexchange.com/questions/20851", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/4427/" ] }
20,855
I have a set of points in the plane which I would like to have "glow". I would like for each point to glow individually and I would also like some increase in the intensity corresponding to an increase in density of the points. I've come up with a couple ideas for how to do this using DensityPlot but neither are quite what I'm hoping for. I'll describe them below. I need some points, say pts = Table[{Re[E^(I t/2 - t/10)], Im[E^(I t/2 - t/10)]}, {t, 1, 50}]; The first idea is to consider an density function like $$ \frac{1}{\epsilon + \min_{a \in \text{pts}}\operatorname{dist}((x,y),a)}. $$ My code for this is eps = 1/16; exponent = 1/2; distfunc1[x_, y_] = 1/(eps + Min[ Table[ ((x - pts[[k, 1]])^2 + (y - pts[[k, 2]])^2)^(exponent), {k, 1, Length[pts]} ] ]); Show[ DensityPlot[distfunc1[x, y], {x, -1, 1}, {y, -1, 1}, PlotPoints -> 40], Graphics[{PointSize[0.007], Point[pts]}] ] which produces The non-differentiability of the density function leads to sharp divisions between the glows. To get around that I considered adding the distances instead of taking the minimum, like $$ \sum_{a \in \text{pts}} \frac{1}{\epsilon + \operatorname{dist}((x,y),a)}. $$ My definition is distfunc2[x_, y_] = Sum[ 1/(((x - pts[[k, 1]])^2 + (y - pts[[k, 2]])^2)^(exponent) + eps), {k, 1, Length[pts]} ]; By varying the parameters eps and exponent I can get parts of what I want. For example with eps = 1/4 and exponent = 1/2 I get nice smooth glows around the outer points but the inner region becomes too "hot": With eps = 1/2 and exponent = 1/1400 the middle is no longer too hot and has the brightest glow from the density but the outer points no longer have significant idividual glows: I haven't yet found a way to have a nice strong glow in the center as well as distinct, nontrivial glows for each of the outer points. I appreciate any ideas you may have. Also, I'm new to Mathematica and I don't really know how ColorFunction works. Is it easy to increase the range of lights/darks (i.e. increase contrast) in the color function used by DensityPlot to render its pictures? I would like the darkest color to be near-black in the above pictures if possible.
One important thing you probably want is PlotRange -> All . The white-hot spots are from plot range clipping. Another thing I add below is a little smoothing by considering (more or less) the harmonic mean of the distances to the two nearest points: pts = Table[{Re[E^(I t/2 - t/10)], Im[E^(I t/2 - t/10)]}, {t, 1, 50}]; distfunc1[x_, y_, a_] := Max[1 - a / Total[1/EuclideanDistance[{x, y}, #] & /@ Nearest[pts, {x, y}, 2]], 0]^2; Show[DensityPlot[distfunc1[x, y, 10], {x, -1, 1}, {y, -1, 1}, PlotPoints -> 40, PlotRange -> All], Graphics[{PointSize[0.007], Point[pts]}]] The intensity is given by 1 - a times the mean distance or 0 , whichever is greater. The spread of the glow is controlled by a , the spread decreasing as a increases. Squaring Max smooths the transition of the intensity to 0 . The image above is for a == 10 .
{ "source": [ "https://mathematica.stackexchange.com/questions/20855", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/863/" ] }
20,912
NB : By higher-genus surface , I mean a closed orientable surface of genus at least 2. This question has come up before on math.SE, and even MathOverflow, but most posters suggested using either Blender or Inkscape. However, I would like to draw these higher-genus surfaces in Mathematica, because I am trying to create a Manipulate which takes as input a word in the fundamental group of such a surface, and outputs the corresponding geodesic, drawn on the surface. So, for example, let's say I am trying to draw a genus 2 surface. What I am doing now is the following: torus = ParametricPlot3D[{(2 + Cos[s]) Cos[t], (2 + Cos[s]) Sin[t], Sin[s]}, {t, 0, 2 Pi}, {s, 0, 2 Pi}, Mesh -> None, Axes -> False, Boxed -> False, PlotStyle -> Opacity[.3], RegionFunction -> Function[{x, y, z, u, v}, x < 2]]; antitorus = Graphics3D[ Translate[ GeometricTransformation[torus[[1]], ReflectionTransform[{1, 0, 0}, {2, 0, 0}]], {1, 0, 0}], Boxed -> False, Axes -> False]; bound = ParametricPlot3D[{{t, (2 + Cos[s]) Sqrt[ 1 - 4/((2 + Cos[s])^2)], Sin[s]}, {t, -(2 + Cos[s]) Sqrt[1 - 4/((2 + Cos[s])^2)], Sin[s]}}, {s, 0, 2 Pi}, {t, 2, 3}, PlotStyle -> {Opacity[.7]}, Axes -> False, Boxed -> False, Mesh -> None, PlotPoints -> 100]; Show[antitorus,torus,bound,Lighting->"Neutral"] This gives me this (not-so-bad!) picture: I am wondering what other methods there are for creating these surfaces, perhaps with a smoother finished product than the one I currently have. And of course, ideally, I would eventually draw the two "building blocks" of all such surfaces, the once- and twice-punctured tori. Then I could dynamically build these surfaces on the fly...
If you dig through Eric Weisstein notebook you can find this well parametrized version. I changed parameters and styles a bit to get closer to your shape. With[{R = 1.2, r = 1/2, a = Sqrt[2]}, ContourPlot3D[-a^2 + ((-r^2 + R^2)^2 - 2 (r^2 + R^2) ((-r - R + x)^2 + y^2) + 2 (-r^2 + R^2) z^2 + ((-r - R + x)^2 + y^2 + z^2)^2) ((-r^2 + R^2)^2 - 2 (r^2 + R^2) ((r + R + x)^2 + y^2) + 2 (-r^2 + R^2) z^2 + ((r + R + x)^2 + y^2 + z^2)^2) == 0, {x, -2 (r + R), 2 (r + R)}, {y, -(r + R), (r + R)}, {z, -r - a, r + a}, BoxRatios -> Automatic, PlotPoints -> 35, MeshStyle -> Opacity[.2], ContourStyle -> Directive[Orange, Opacity[0.8], Specularity[White, 30]], Boxed -> False, Axes -> False]] OK digging through Eric Weisstein another notebook I figured a "tentative" generalization, - at least it works with n=3 or n=4. The rest needs more time (also look here ): torusImplicit[{x_, y_, z_}, R_, r_] = (x^2 + y^2 + z^2)^2 - 2 (R^2 + r^2) (x^2 + y^2) + 2 (R^2 - r^2) z^2 + (R^2 - r^2)^2; build[n_] := Module[{f, cp, polys, cartPolys, cartPolys1},(*implicit polynomial*) f = Product[ torusImplicit[{x - 1.5 Cos[i 2 Pi/n], y - 1.5 Sin[i 2 Pi/n], z}, 1, 1/4], {i, 0, n - 1}] - 10; cp = ContourPlot3D[ Evaluate[f == 0], {x, -3, 3}, {y, -3, 3}, {z, -1/2, 1/2}, BoxRatios -> Automatic, PlotPoints -> 35, MeshStyle -> Opacity[.2], ContourStyle -> Directive[Orange, Opacity[0.8], Specularity[White, 30]], Boxed -> False, Axes -> False]]; build[3]
{ "source": [ "https://mathematica.stackexchange.com/questions/20912", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/191/" ] }
21,117
Working on a CDF for report creation, I miss having a nice grid interface, where I would have basic operations like being able to sort a columns by clicking on the columns head (ascending and descending), or maybe group and ungroup data. This is a great example of what can be done in Mathematica , but the code is not avaliable.
This code is not generalized. It has been written for a specific problem but you can take it and should be able to make it a more general function -- add flexibility (e.g. add grid options) or tailor it to your needs. ClearAll[frozenPaneGrid]; Options[frozenPaneGrid] = {"RowLabelSort" -> False}; frozenPaneGrid[tl_, tr_, bl_, br_, OptionsPattern[]] := DynamicModule[{scroller = 1, scrollx = 0, scrolly = 0, options, columns = Length[tr], headings = tr, i = 1, order = Range[Length[bl]], initialOrder = Ordering[Flatten[{bl}]]}, options = { Background -> {None, {{White, GrayLevel[0.93]}}}, BaseStyle -> Directive[FontFamily -> "Helvetica", 11], Frame -> False, FrameStyle -> Directive[Thin, GrayLevel[0.75]]}; Dynamic[ Deploy@Grid[{ {Pane[ Grid[ {{EventHandler[ MouseAppearance[tl, Framed[Style["Left Click Sort\nRight Click Reverse Sort", 9], Background -> White]], {{"MouseClicked", 1} :> (If[TrueQ[OptionValue["RowLabelSort"]], order = initialOrder, order = Range[Length[bl]]]), {"MouseClicked", 2} :> (If[TrueQ[OptionValue["RowLabelSort"]], order = Reverse@initialOrder, order = Reverse@Range[Length[bl]]])}]}}, Alignment -> {Left, Center}, Dividers -> {{1 -> White, -1 -> LightGray}, {1 -> True, -1 -> True}}, ItemSize -> {20, 1.75}, Spacings -> {2, 0.5}, options], {270, All}, Alignment -> {Right, Top}, ImageMargins -> 0], Pane[ Grid[ {Table[ With[{j = j}, EventHandler[ MouseAppearance[headings[[j]], Framed[Style[ "Left Click Sort\nRight Click Reverse Sort", 9], Background -> White]], {{"MouseClicked", 1} :> (i = j; order = Ordering[br[[All, i]]]), {"MouseClicked", 2} :> (i = j; order = Reverse@Ordering[br[[All, i]]])}]], {j, columns}]}, Alignment -> {Right, Center}, Dividers -> {{-1 -> White}, {1 -> True, -1 -> True}}, ItemSize -> {8, 1.75}, Spacings -> {{2, {0.5}, 2}, 0.5}, options], {655, All}, Alignment -> {Left, Top}, ImageMargins -> 0, ScrollPosition -> Dynamic[{scrollx, scroller}]]}, {Pane[ Grid[ bl[[order]], Alignment -> {Left, Center}, Dividers -> {{1 -> White, -1 -> LightGray}, None}, ItemSize -> {20, 1.75}, Spacings -> {2, 0.5}, options], {270, 505}, Alignment -> {Right, Top}, AppearanceElements -> None, ImageMargins -> 0, ScrollPosition -> Dynamic[{scroller, scrolly}]], Pane[ Grid[ br[[order]], Alignment -> {Right, Center}, Dividers -> {{-1 -> White}, None}, ItemSize -> {8, 1.75}, Spacings -> {{2, {0.5}, 2}, 0.5}, options], {670, 520}, Alignment -> {Left, Top}, AppearanceElements -> None, ImageMargins -> 0, ScrollPosition -> Dynamic[{scrollx, scrolly}], Scrollbars -> {True, True}] }}, Alignment -> {{Right, Left}, Top}, Spacings -> {0, 0}], TrackedSymbols :> {order}] ]; If you start with a grid of data and sort/reverse sort how do you recover the initial order of the 1st column? My approach here is to introduce an option "RowLabelSort" which, when False , will sort the first column according to the initial ordering. To make this Excel like -- similar to frozen panes -- I have joined 4 grids. To get the 4 grids joined and coordinated for scrolling I "link" the scroll position in each pane. On my system (at the time was 8.0.4 and mac 10.6.8) I had to use scroller = 1 to overcome some intermittent problems. I think the rest of the code is pretty much self explanatory. Most of the code is grid option settings for appearance. Left click on a column header to sort. Right click to reverse sort. To make this explicit I have made a big mouse appearance instruction box. You can obviously replace that. Because I have created this on a Mac, you may find that you have to tweak some of the sizes on Windows. See this for further discussion. Usage: frozenPaneGrid[top left cell, rest of top row, left hand column, main body of data, options] Test data: SeedRandom[123]; tmp = RandomInteger[{1, 100}, {27, 14}]; frozenPaneGrid["header", Table[y, {14}], List /@ {"Ajax", "admixes", "Acrux", "Alex", "affix", "admixtures", "Alexei", "affixed", "admixing", "ambidextrously", "admixed", "admix", "affixing", "ambidextrous", "Alexandrians", "Alexandria", "Anaxagoras", "Alexandrian", "annexation", "Alexandra", "admixture", "Alexis", "Alexanders", "annex", "affixes", "ambidexterity", "Alexander"}, tmp, "RowLabelSort" -> False]
{ "source": [ "https://mathematica.stackexchange.com/questions/21117", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/2266/" ] }
21,123
I've been asked to reproduce a bar chart generated in Excel in Mathematica . The original Excel chart looks like this; My Mathematica version looks like this; There are a couple of things wrong that I'd like to fix; The BarChart and ListPlot overlay doesn't seem to match up. The ChartLabels seem to have disappeared on the BarChart . Is there a nice way to make the ticks on the left and right sides match up (like when the Excel chart matches 9 % on the left to 90 % on the right)? I can't get the box and line to center align to the text in the legend. Questions 1 and 2 are what I really need to fix, but 3 and 4 would be nice to have. Any help would be appreciated. Here's the code I used to generate my chart; purple = RGBColor[97/255, 16/255, 106/255]; orange = RGBColor[245/255, 132/255, 31/255]; labels = { "FY15 Q1/2", "FY15 Q3/4", "FY16 Q1/2", "FY16 Q3/4", "FY17 Q1/Q2", "FY17 Q3/Q4", "FY18 Q1/2", "FY18 Q3/4" }; starvedTime = {7.55, 11.23, 8.58333, 6.88833, 4.65167, 1.89, 6.49833, 1.95}; satTime = {70.1483, 81.1467, 81.115, 86.5483, 84.6833, 90.685, 79.6017, 91.0133}; plot1 = BarChart[starvedTime, PlotRange -> {0, 12}, ChartStyle -> purple, BaseStyle -> "Text", Frame -> {True, True, True, False}, FrameTicks -> {False, True}, FrameLabel -> {None, Style["Smelter Starved Time (%)", "Text"], None, None}, PlotLabel -> "Smelter Starved Time by 6 Month Period: Base Case", ImageSize -> Large, ChartLabels -> {Placed[Style[#, "Text"] & /@ labels, Below], None}, AxesOrigin -> {0, 0}, PlotRangePadding -> {0, 0}, BarSpacing -> 1]; plot2 = ListPlot[satTime, Joined -> True, PlotRange -> {60, 100}, PlotStyle -> orange, Frame -> {False, False, False, True}, FrameTicks -> {None, None, None, All}, FrameLabel -> {None, None, None, Style["Smelter Operating at Constraint Rate (%)", "Text"]}, BaseStyle -> "Text", GridLines -> {None, Automatic}, GridLinesStyle -> Directive[Gray, Dashed], ImageSize -> Large]; box = Graphics[{purple, Rectangle[]}, ImageSize -> 12]; text = Style[" Smelter Starved (%) ", "Text"]; line = Graphics[{orange, Line[{{0, 0.5}, {1, 0.5}}]}, ImageSize -> {30, Automatic}]; text2 = Text[Style[" % Time Smelter at Constraint Rate (%) ", "Text"]]; legend = Row[{box, text, line, text2}]; Column[{Overlay[{plot1, plot2}], legend}, Alignment -> {Center, Center}]
Answers to your 4 questions step by step to see how each of these changes the composite plot: 1. The image padding around the two images differs so you need to set a fixed value for each. With ImagePadding -> {{50, 50}, {50, 10}} as an option for both plots I get this: 2. ChartLabels -> Placed[Style[#, "Text"] & /@ labels, Below],ImagePadding -> {{50, 50}, {20, 10}}, 3. in plot #2 add PlotLabel -> "" 4. I almost always prefer Grid to Row : box = Graphics[{purple, Rectangle[]}, ImageSize -> 12]; text = "Smelter Starved (%)"; line = Graphics[{orange, Line[{{0, 0.5}, {1, 0.5}}]}, ImageSize -> {30, Automatic}]; text2 = "% Time Smelter at Constraint Rate (%)"; legend = Grid[{{box, text, line, text2}}, Alignment -> {{Right, Left}, Center}, BaseStyle -> Directive[FontFamily -> "Arial"], Spacings -> {{0, 0.5, 2}, 0}]; Finishing touches Bar chart plot ranges go from 0.5 to length of data + 0.5. So set the plot range of your bar chart to PlotRange -> {{0.5, 8.5}, {0, 12}} and for the list plot to PlotRange -> {{0.5, 8.5}, {60, 100}} . Now set your data range for ListPlot to be DataRange -> {1, 8} . This will ensure that the point coincide with the middle of your bars. plot1 = BarChart[starvedTime, AspectRatio -> 1/GoldenRatio, AxesOrigin -> {0, 0}, BarSpacing -> 1, BaseStyle -> Directive[FontFamily -> "Arial"], ChartLabels -> Placed[labels, Below], ChartStyle -> purple, Frame -> {True, True, True, False}, FrameLabel -> {None, "Smelter Starved Time (%)", None, None}, FrameTicks -> {{#, "", {0, 0.01}} & /@ Range[0.5, 8.5, 1], {0, 3, 6, 9, 12}, None, None}, FrameTicksStyle -> Directive[Plain, 12], GridLines -> {None, {3, 6, 9}}, GridLinesStyle -> Directive[Gray, Dashed], ImagePadding -> {{50, 50}, {20, 10}}, ImageSize -> 600, LabelStyle -> Directive[Bold, 12], PlotLabel -> Style["Smelter Starved Time by 6 Month Period: Base Case", 13], PlotRange -> {{0.5, 8.5}, {0, 12}}, PlotRangePadding -> 0, Ticks -> None]; plot2 = ListPlot[satTime, AspectRatio -> 1/GoldenRatio, Axes -> False, BaseStyle -> Directive[FontFamily -> "Arial"], DataRange -> {1, 8}, Frame -> {False, False, False, True}, FrameTicks -> {None, None, None, {60, 70, 80, 90, 100}}, FrameTicksStyle -> Directive[Plain, 12], FrameLabel -> {None, None, None, "Smelter Operating at Constraint Rate (%)"}, ImageSize -> 600, ImagePadding -> {{50, 50}, {20, 10}}, Joined -> True, LabelStyle -> Directive[Bold, 12], PlotRangePadding -> 0, PlotRange -> {{0.5, 8.5}, {60, 100}}, PlotStyle -> orange, PlotLabel -> Style["", 13]]; Note #1. there is scope for you to match the fonts of the Excel chart. Note #2. Labeled could be used instead of Column . Note #3. To completely match the Excel chart you actually need the grid lines to be used in the bar chart rather than the list plot. Note #4. Added some ticks between the bars. Note #5. Corrected labels: "FY17 Q1/Q2", "FY17 Q3/Q4",
{ "source": [ "https://mathematica.stackexchange.com/questions/21123", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/2487/" ] }
21,186
Suppose I have the following list lis = Range[100]; and I want to remove n consecutive terms periodically from the list. For example suppose I want to drop terms 4 and 5, 9 and 10, 14 and 15 etc. I could do this sequentially as follows: Drop[Drop[lis, {5, -1, 5}], {4, -1, 4}]; This gives: {1, 2, 3, 6, 7, 8, 11, 12, 13, 16, 17, 18, 21, 22, 23, 26, 27, 28, 31, 32, 33, 36, 37, 38, 41, 42, 43, 46, 47, 48, 51, 52, 53, 56, 57, 58, 61, 62, 63, 66, 67, 68, 71, 72, 73, 76, 77, 78, 81, 82, 83, 86, 87, 88, 91, 92, 93, 96, 97, 98} This gets really messy if I have to drop n consecutive terms where n is large. Is there a way to do this with just one Drop function or a better more compact and efficient way to achieve this where my list is huge. In my example above, n is 2 , but it could be 3 , 4 etc. What I want is a general solution. Thanks.
The simplest (and probably fastest) way is to use Partition with the appropriate offset: list = Range@100; Flatten@Partition[list, 3, 5] (* {1, 2, 3, 6, 7, 8, 11, 12, 13, 16, 17, 18, 21, 22, 23, 26, 27, 28, 31, 32, 33, 36, 37, 38, 41, 42, 43, 46, 47, 48, 51, 52, 53, 56, 57, 58, 61, 62, 63, 66, 67, 68, 71, 72, 73, 76, 77, 78, 81, 82, 83, 86, 87, 88, 91, 92, 93, 96, 97, 98} *) The logic is: "Take 3, drop 2, take 3, drop 2,... " till the end of the list (the argument 5 is just 3+2 ). You can change these numbers as desired.
{ "source": [ "https://mathematica.stackexchange.com/questions/21186", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5709/" ] }