Skip to main content

Posts

Showing posts from June, 2017

performance tuning - Is there a linter to help write good Mathematica code?

I don't do much real programming, but I've recently been turned on to Atom , which has linter plugins for over 50 languages to make coding easier (most drawing on pre-existing lint-like programs). In other languages, linters help me learn about operator precedence (unnecessary parentheses), good programming styles/techniques, and get warnings about code that may not have been intended. Is there something along these lines for Mathematica? If not, is there a reason why not? At first glance it seems like a number of the suggestions/tips I pick up from reading answers here could be automated. For example, maybe the Mathematica linter would remind you to memoize your functions with f[n_]:=f[n]= if that setting is turned on. Edit: For a couple days in November 2016 there was work on a linter for Atom for Mathematica on github , but the project seems to have died quickly and I couldn't get it to work.

bugs - Wolfram Cloud deployment obstacles

What are official restrictions about FormFunctions /general deployment contents? There are problems with many things which sometimes I have workarounds for but I see no general pattern. Edit: I moved examples to the answer to keep a clean index here. Features / bugs bug : Special characters (e.g. \[EmptySet\] ), in form values, break FormFunction validation. bug : Some special characters in form layout break the form completely: bug : Reserved HTML characters (e.g. < ) are not escaped properly (CASE:4025512) bug : String representation of boxes causes problems feature : StandardForm is not supported for FormFunctions feature : Styling options ignored unless CloudCDF ExportForm is used. feature : Unclear dependencies collecting by CloudDeploy with Manipulate Fixed problems: (may be relevant for users with old MMA / EPC) bug : Form/APIFunction dependencies collection problems Pending review: Additionally, are there any general rules to follow?

extract data from a graph image

How do I convert the following image graph into data (if possible into function)? I checked this answer and found that my problem is grid and plot have same color. Answer If the problem is only to remove the grid, that's relatively easy. You just remove everything but the grid, then take the difference. You can use Closing with a rectangular structuring element to remove everything but the horizontal / vertical grid lines, like this: img = Import["http://i.stack.imgur.com/TkvSR.png"]; hFilter = Closing[img, BoxMatrix[{10, 0}]]; vFilter = Closing[img, BoxMatrix[{0, 10}]]; then take the pixel-wise min to get the full grid: grid = ImageApply[Min, {hFilter, vFilter}]; Then simply binarize the difference: Binarize[ImageDifference[img, grid]] (From here, you should be able to use code from the answers already linked.)

plotting - displaying (result of Show function)

I used Show to represent some functions. I want the displaying box to start and end by (0, 40) in the x-direction and (0,100) in y-axis. I mean I don't want the little separation between zero and vertical axis below pic: exmple for show function result Answer Probably you are referring to PlotRangePadding . Just disable it: Plot[-.3 x^2 + 10 x, {x, 0, 40}, Frame -> True, PlotRange -> {{0, 40}, {0, 100}}, PlotRangePadding -> None] You can use the same commands for Show as well.

evaluation - How can I interrupt a calculation without aborting it?

Before version 10.0, there was a menu item, Evaluation → Interrupt Evaluation..., which could be used to interrupt a calculation without aborting it. It would bring up this window: It was possible to enter a subsession , examine the kernel state, then resume the calculation using Return[] . How do I access this functionality in version 10.0 or later? Answer The menu item is gone, but the functionality is still there in version 11.0. It can be accessed by a keyboard shortcut: Command-Option- . on OS X Alt- , on Windows and Linux The front end token is called "EvaluatorInterrupt" It can be used e.g through a palette button. Alternatively, use Evaluation → Evaluate in Subsession for similar functionality. E.g., Table[Pause[1]; i, {i, 30}] Now enter i and evaluate it using the above menu item before the Table has finished running. You will see the current value of i .

programming - Question about collections of custom GUI controls for Mathematica

Background: I have only recently begun programming GUIs in Mathematica, so I have a continuous need for custom controls. I needed a scrollable list control and with the help of Google I found a beautiful one in this MathGroup post (One of Sjoerd, if I am correct.) The point being: there is a lot of excellent Mathematica code shattered all over. Most matured languages have libraries of custom controls. I am not aware of any existing for Mathematica. Question(s): What is the best managed collection of (open source) custom GUI controls for Mathematica that you know of? Where do you get your custom GUI controls? Should there be a collection of custom GUI controls for Mathematica? Answer One of the excellent places to look is the Wolfram Demonstration Project . There are many cases with custom controls there. You can test out controls immediately and download the source code. Because I know that site pretty well I will keep the list here. Relief-Shaded Elevation Map 3D Waves Potter'

series expansion - Chebyshev Approximation

Is there functionality in Mathematica to expand a function into a series with Chebyshev polynomials? The Series function only approximates with Taylor series. Answer You can just take Bob Hanlon 's answer from 2006 directly, and modify the plot just a bit to update it. ChebyshevApprox[n_Integer?Positive, f_Function, x_] := Module[{c, xk}, xk = Pi (Range[n] - 1/2)/n; c[j_] = 2*Total[Cos[j*xk]*(f /@ Cos[xk])]/n; Total[Table[c[k]*ChebyshevT[k, x], {k, 0, n - 1}]] - c[0]/2]; f = 3*#^2*Exp[-2*#]*Sin[2 #*Pi] &; ChebyshevApprox[3, f, x] // Simplify ((-(3/4))*((-E^(2*Sqrt[3]))*(Sqrt[3] - 2*x) - 2*x - Sqrt[3])*x* Sin[Sqrt[3]*Pi])/E^Sqrt[3] GraphicsGrid[ Partition[ Table[Plot[{f[x], ChebyshevApprox[n, f, x]}, {x, -1, 1}, Frame -> True, Axes -> False, PlotStyle -> {Blue, Red}, PlotRange -> {-2, 10}, Epilog -> Text["n = " <> ToString[n], {0.25, 5}]], {n, 9}], 3], ImageSize -> 500]

implementation details - How does Interpolation really work?

I'm looking for some explanation or advice, not help in solving something. Recently I finished my program and my supervisor said "Ok, now it's time for your first paper: write a scientific text about how your program works". If I understand him correctly it means I have to describe the algorithm I used instead of writing in a manner like "for this purpose I use the built-in Interpolation function, and for this purpose I use NDSolve " etc. I know how FindRoot and NDSolve work because there is an explanation in the doc pages about the methods they use, but I did not find detailed information about Interpolation . The only thing I know it fits with polynomial curves. So my question is: What exactly does the Interpolation function do? How does it work? How does it determinate (partial) derivatives? And why do 3D data points have to be situated in rectangle order to interpolate a surface? If there is some literature I may read and then reference it would be g

list manipulation - Convert to normal numerical array

I have an array whose elements are like this {{{c2 -> 2917.68}}, {{c2 -> 1921.78}}, ... ] . I am unable to ListPlot this array. It givess ListPlot called with 0 arguments error. How can I convert this to normal array? Answer ListPlot @ Flatten @ Values @ {{{c2 -> 2917.68}}, {{c2 -> 1921.78}}}

import - Release the web camera after using CurrentImage[]

CurrentImage[] will capture an image from the webcam. It is even possible to create a live video in the notebook using Dynamic@CurrentImage[] After using this function even a single time, Mathematica will not switch off or release the webcam any more, making it impossible to use the webcam from other programs on some systems. How can I switch off / release the webcam from Mathematica, without quitting Mathematica completely? Answer To turn the camera off you could use the undocumented function IMAQ`StopCamera[] . Similarly IMAQ`StartCamera[] will turn it back on again. Alternatively you can use the On/Off button on the control interface returned by ImageCapture[] :

notebooks - Friendly way to make previous large calculation results reusable in a new session

Very often, I need to do same calculations under different parameters for comparing the results. Every calculation may generate a large data set; for example, the calculation result of Eigensystem is often a large list. If we want to make a careful systematic investigation of the whole parameter space, the best way is to export calculation result into external file. But before we make a careful systematic investigation of the whole parameter space, we usually need to look into several typical parameter cases to see whether the result is consistent with my original conjecture or not. Under these circumstances, my personal experience is that exporting and importing is not as flexible as directly leaving results in the notebook. Then here is the issue of how to store results from large calculations compactly in the notebook and how to obtain the results without a re-calculation when I reopen the notebook to continue my previous analysis. For example: The following assigns an eigensystem

plotting - How can we plot the complex roots of an equation?

If we'd like to display the $n$ roots of a polynomial on the complex plane as points, how can we do this? For example, if we have the equation $x^3 + x^2 + x + 1$, how can we plot the 3 roots as points in the complex plane? There's more. We can suppose that we're given a range of the coefficients for an $n$th degree polynomial: $$f(x) = c_0 x^0 + c_1 x^1 + c_2 x^2 + \dots + c_n x^n$$ Here all $c_k$ values for $0 \le k \le n$ range from $r \le c_k \le s,\, c_k \in \mathbb{Z}$. I'd like to plot all possible roots for all possible polynomials on the same graph, given these constraints. In other words, we're given the parameters $n$, $r$, and $s$. I'd like to plot all possible roots of the polynomials that meet these conditions on the same plot. One more thing, and this is probably the most important. I'm wondering if we can use a color scheme for the plot. For example, we can use a gray scale, indicating the number of times a root appears. If the same root appe

differential equations - How do I fit NDSolve result to experimental data?

I have two coupled ordinary differential equations which I solve numerically in Mathematica , but now I want to fit the solution with experimental data. I do following, (the experimental data corresponds to z[t] in my notation) ss = ParametricNDSolve[{ z'[t] == 4*(1 - X^-1)*z[t] + 4*z[t]*y[t]/X - 8*(z[t])^2 && y'[t] == γ*z[t] - γ*y[t]/X && z[0] == z0 && y[0] == y0} /. {X -> 20}, {z, y}, {t, 0, 5000}, {γ, z0, y0}] I know the value of X = 20 . The rest has to be determined by fitting. Also time has to be rescaled to fit with experimental data. hence in total of 4 parameters. γ and y0 does not have any constraint apart from being positive. but x0 has to be very small (close to zero). data = {{4.01, 0.0338}, {6.02, 0.0719}, {7.99, 0.14}, {9.99, 0.216}, {9.98, 0.25}, {12., 0.307}, {12., 0.35}, {14., 0.459}, {16., 0.558}, {16., 0.605}, {18., 0.688}, {20., 0.767}, {22., 0.848}, {24., 0.898}, {26., 0.932}, {28., 0.965}, {30., 0

programming - Efficient priority queues?

I'm trying to figure out how to transfer the concept of a priority queue to the functional world. Searches have turned up some implementations that use Append and other expense list copying techniques. I'm guessing there is a better way. An example of what I am trying to solve is consider the products of all pairs of N digit numbers in descending value order. For small N I can do something like... Reverse[ Cases[ SortBy[ Flatten[ Table[{i, j, i*j}, {i, 1, 9}, {j, 1, 9}], 1], Last[#] &], {i_, j_, k_} /; i <= j] ] Alternative solutions to the problem in particular are welcomed, but I am really looking for a generic answer of how to apply the priority queue concept to the functional world. Answer This is going to be transcript of Roman E. Maeder 's priority queue code with any updates I can find to make to take advantage of functions added since he wrote it. I believe I am within right to copy it here fo

dynamic - Using a setterbar to set text alignment while keeping the current vertical cursor bar position

The code below generates a SetterBar that dynamically updates with the current text justification (where the vertical cursor bar is located) and allows you to change it to a new justification. See gif below. SetterBar[ Dynamic[e = CurrentValue[NotebookSelection[], TextAlignment], {SelectionMove[InputNotebook[], All, Cell]; SetOptions[NotebookSelection[InputNotebook[]], TextAlignment -> #]} &], {Left, Center, Right}] The code contains the function SelectionMove[InputNotebook[], All, Cell] . The problem with keeping that function in the code is that I lose the current vertical curser bar position. See gif below. I would like to keep the current cursor bar position where its at, but if remove that function the setter bar doesn't work anymore. Do you have any ideas?

cdf format - Setting output width for CopyToClipboard

Suppose I have a long string and I copy it to the clipboard: s = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345"; CopyToClipboard[s] When I paste the clipboard contents into a text editor I get that string all on a single line. But when I use CopyToClipboard[{s}] I get {"12345678901234567890123456789012345678901234567890123456789012345678\ 90123456789012345"} How can I avoid the line splitting? I see Options and Streams and TotalWidth in the documentation but I can't make heads or tails of any of it. (You might wonder why I'm using {s} rather than just s : That seems to be the only way I can get a CDF document to copy anything to the clipboard.) Answer Converting a comment to an answer, in the 10.1.0 Front End this works: SetOptions[$FrontEndSession, {"PageWidth" -> 1000, "ExportTypesetOptions" -> {"PageWidth" -> 1000}}] I do not use CDF so I do not know how this relates.

plotting - How to draw lines between specified dots on ListPlot?

I would like to create a plot where I have unconnected dots and some connected. So far, I have figured out how to draw the dots. My code is the following: ListPlot[{{1, 1}, {2, 2}, {3, 3}, {4, 4}, {1, 4}, {2, 5}, {3, 6}, {4, 7}, {1, 7}, {2, 8}, {3, 9}, {4, 10}, {1, 10}, {2, 11}, {3, 12}, {4,13}, {2.5, 7}}, Ticks -> {{1, 2, 3, 4}, None}, AxesStyle -> Thin, TicksStyle -> Directive[Black, Bold, 12], Mesh -> Full] I have thought using ListLinePlot command, but I don't know how to specify to the command to draw only selected lines between the dots. Do have any suggestions/hints on how to do that? Thank you. Answer One possibility would be to use Epilog with Line : ListPlot[ {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {1, 4}, {2, 5}, {3, 6}, {4, 7}, {1, 7}, {2, 8}, {3, 9}, {4, 10}, {1, 10}, {2, 11}, {3, 12}, {4, 13}, {2.5, 7}}, Ticks -> {{1, 2, 3, 4}, None}, AxesStyle -> Thin, TicksStyle -> Directive[Black, Bold, 12], Mesh -> Full, Epilog -> { Line[

cluster analysis - Finding connected components in an array

I have an $w\times h$ array with non-negative integers. I wish to partition the set of coordinates $(c,r)$ with $1\leq c \leq w$ and $1\leq r \leq h$, in subsets, so that each subset corresponds to a cluster of the same value in the array. Two coordinates are neighbouring if they either are on top of another, or one is down-left of the other. This corresponds to finding clusters in a parallelogram. belisarius was nice to provide a picture: I have some code to find one connected cluster in an array (I call it gt ): FloodFillExtractTile[gt_, {sr_, sc_}] := Module[{r, c, toExplore, visited = {}}, toExplore = {{sr, sc}}; While[Length@toExplore > 0, (* Pop *) {r, c} = Last@toExplore; toExplore = Most[toExplore]; AppendTo[visited, {r, c}]; (* Down-left *) If[c > 1 && r < h && gt[[r + 1, c - 1]] == gt[[r, c]] && ! MemberQ[visited, {r + 1, c - 1}], AppendTo[toExplore, {r + 1, c - 1}]; ]; (* Down-right *) If[ r <

performance tuning - Optimizing a Numerical Laplace Equation Solver

Laplace's Equation is an equation on a scalar in which, given the value of the scalar on the boundaries (the boundary conditions), one can determine the value of the scalar at any point in the region within the boundaries. Initially, I considered using NDSolve , but I realized that I did not know how to specify the boundary conditions properly. In the example below, my boundary is a square with value 0 along the top, left and right boundary and 1 along the bottom boundary. Alternatively, the solutions to the equation can be approximated via the Method of Relaxation . In the method, the region is divided into a grid, with the grid squares along the boundary being assigned (fixed) boundary conditions, and the value for the grid squares within the boundary being iteratively calculated by assigning the average values (in the previous time-step) of four grid squares adjacent to it. My current code is as follows localmeaner = Mean@{#1[[#2 - 1, #3]], #1[[#2 + 1, #3]], #1[[#2, #3 - 1]],

performance tuning - Is there an NDSolve`ProcessEquations analog for NIntegrate?

NDSolve has an interface for repeatedly solving an equation with different initial conditions without having to analyze the equation and set up the solving algorithm each time. This can improve performance dramatically. For example, nd = First@NDSolve`ProcessEquations[{y'[t] == -y[t], y[0] == 1}, {y}, t] (* NDSolve`StateData[<0.>] *) solve[y0_] := Module[{}, nd = First@NDSolve`Reinitialize[nd, y[0] == y0]; NDSolve`Iterate[nd, 1]; NDSolve`ProcessSolutions[nd]] Timing[NDSolve[{y'[t] == -y[t], y[0] == #}, y, {t, 0, 1}]&/@Range[0.001, 1, 0.001]]//First (* 0.527396 *) Timing[solve /@ Range[0.001, 1, 0.001]] // First (* 0.250309 *) Is there an analogous interface to NIntegrate that would allow me to process the integral once, then do integrations using the same integration method (as chosen by NIntegrate ) repeatedly using different constants in the integrand and/or different limits of integration? Answer NIntegrate performs a certain symb

Solving matrix equation

How can I solve the forward equation S[t]=C+A*S[t+1]*(Inverse((I-B*S(t+1)))*A for t=1 to t=10 and S[11]=0 with S , A , C , and B beeing 2*2 matrices? A={{0.1,0},{0,0.1}} B={{2,3},{-3,1}}, C={{0.2,0.6},{0.2,0}}, I={{1,0},{0,1}}

cluster analysis - data clustering

I have some data set which i would like to partition into 3 groups a:set 1 b: set 2 c: background. I use FindClusters[] function but as you can see (after evaluating the commands) the result is not what I am looking for. Can someone help? data1 = RandomReal[{-0.1, 0.1}, {10^2, 2}]; data2 = RandomReal[{-1, 1}, {2*10^2, 2}]; data3 = RandomReal[{-0.3, -0.2}, {2*10^2, 2}]; data5 = Join[data1, data2, data3]; ListPlot[FindClusters[data5, 3]]

differential equations - Solving 2D+1 PDE with Pseudospectral in one direction with periodic boundary condition?

According to the documentation about the pseudospectral difference-order: It says: Following the discussion here : I found the messy behavior is always on the artificial boundary in $\omega$-direction ($u(t,\theta,\omega_{cutoff})=0$ because I want $\omega$ to be unbounded.) Perhaps, this is so called Runge phenomenon ? In principle, we should not use pseudospectral difference-order for all directions. However, it is not clear how to specify them separately. Here is code: a = 1; T = 1; ωb = -15; ωt = 15; A = 8; γ = .1; kT = 0.1; φ = 0; mol[n_Integer, o_: "Pseudospectral"] := {"MethodOfLines", "SpatialDiscretization" -> {"TensorProductGrid", "MaxPoints" -> n, "MinPoints" -> n, "DifferenceOrder" -> o}} With[{u = u[t,θ, ω]}, eq = D[u, t] == -D[ω u,θ] - D[-A Sin[3θ] u, ω] + γ (1 + Sin[3θ]) kT D[ u, {ω, 2}] + γ (1 + Sin[3θ]) D[ω u, ω]; ic = u == E^(-((ω^2 +θ^2)/(2 a^2))) 1/(2 π a) /. t ->

list manipulation - Partition a set into $k$ non-empty subsets

The Stirling number of the second kind is the number of ways to partition a set of $n$ objects into $k$ non-empty subsets. In Mathematica, this is implemented as StirlingS2 . How can I enumerate all the sets? Ideally I would like to get a list of lists, where each list contains $k$ lists. The question Partition a set into subsets of size k seems relevant. Answer << Combinatorica` KSetPartitions[{a, b, c}, 2] (* {{{a}, {b, c}}, {{a, b}, {c}}, {{a, c}, {b}}} *) StirlingS2[3, 2] (* 3 *)

Possible Bug of loading Package @ Mathematica 10.1

When I open mathematica, there will pop-up some messages where << package` is in the following file FindFile["init.m"] (* C:\Users\HyperGroups\AppData\Roaming\Mathematica\Kernel\init.m *) package content in the package file: BeginPackage["Test1`"] Test1::usage = ""; Begin["`Private`"]; Nearest[{1, 2, 3, 5, 8, 5}, 5] End[] EndPackage[] I've tried * Mathematica * 10.1@Windows and 10.0[without this problem] Seems the problem is related with some special functions, like Nearest Answer Update This has been fixed in a general way as of version 11.2.0. For more details, see this answer. This is a known issue. It is not about package loading (or Nearest ) but about Catch / Throw not working correctly when used during kernel initialization. For example, just putting the following in init.m Catch[Throw[1]] will result in similar behavior. See also Arnoud Buzing 's post here . The workaround I've been using is to run any init code

expression manipulation - How to Clear variables represented as a list of strings?

Say I have a string list called fullpara fullpara={"width", "long", "line", "distance"} And there are corresponding variables to each string, and I want to Clear these variables Clear[width, long, line, distance] How to do it in a way to manipulate fullpara as a whole? Clear@@(ToExpression/@fullpara) obviously won't work because ToExpression will evaluate the variable that already has a value. Answer According to the documentation of Clear or ClearAll it is possible to provide symbols in form of regular expression ( limited ), in particular as string with exact symbol name. Clear @@ {"width", "long", "line", "distance"} Let's say there is no possibility to do that, one way would be: Map[Clear, ToExpression[{"width", "long", "line", "distance"}, InputForm, Hold], {2}]; // ReleaseHold

mac os x - Add blank line before end of file with export

I have a list of points (e.g. {1.2,0.4} ) which I export to a file using Export[fileName, list]; I want to add a line before the end of file. For instance instead of ending the file with 1.236677 4.64567567 1.236677 4.64567567 1.236676 4.64567567 ending like 1.236677 4.64567567 1.236677 4.64567567 1.236676 4.64567567 # a blank line here I tried appending {} , {,} , "" to the list, but none of them added a blank line. I need this because xmgrace is not parsing the last line of the exported mathematica file: it expects a blank line before the End of File. EDIT: As pointed out in the comments by Kuba and Pinguin Dirk, appending "" works on Windows XP (and probably others.) I'm using OS X. Answer Here, on my OSX the following works Export["tmp/foo.txt", Append[Range[10], "\n"]]

dynamic - DynamicModule, SaveDefinitions and global functions

Unfortunately, I had not checked stackoverflow, because there, the exact same behavior was already reported. Please see the Q&A "SaveDefinitions considered dangerous" . Up-front, I'm on Ubuntu 12.04 with Mathematica 9.0.1 and let's start with the questions: Should functions which are used in a Manipulate be local to this dynamic cell, when I save them with SaveDefinitions`? Is it OK, that after a kernel-restart Manipulate defines global functions? I noticed this behavior a while ago when something did not work as I expected it. Here is a small toy example. First we define a function, which (we assume we don't know this now) is not correct and will be fixed later: f[x_?NumericQ] := "Wrong Implementation"; Now we make a small dynamic environment where we use this function and we save the definitions used there. Manipulate[f[x] + x, {x, 0, 1}, SaveDefinitions -> True] Sliding a bit around gives the correct output: Now, we notice our error in f , b