source_id
int64
1
4.64M
question
stringlengths
0
28.4k
response
stringlengths
0
28.8k
metadata
dict
5,846
When the Wolfram Demonstrations were introduced and the Documentation-Center was redesigned, I remember it was the first time I thought someone had put some effort into creating a beautiful stylesheet. I don't like most of the other styles and in fact, I think PrimaryColor is so ugly that I cannot believe it is included in the standard templates. On the other hand, I have seen some quite nice things when I spoke on a Mathematica -day and we used a common stylesheet for the slides. That's why I wonder whether there are other styles out there which are worth sharing. Question: Does someone know resources where people shared their stylesheets? I'm especially interested in things one can use for talks.
Seeing as there are no good repositories for Mathematica stylesheets and packages, I created a github account for the community. The account resides at github/stackmma . I know there's library.wolfram.com, but we should be independent of WRI. On the topic of this question, I created a public stylesheets repository and I've added halirutan and jmlopez as collaborators. If anyone wants to be added to this, please let me know (via chat/comment) and I'll gladly add you. Long term goals of this project I think the stackmma account can eventually be a place for us to host community developed projects (if and when we do) host notebooks and snippets for blogposts host data files/notebooks, etc. for questions (only in the rare and non-localized cases when a minimum-working-example is not illustrative enough). I've created an Attachments repository to re-upload files hosted on dropbox or other filesharing services to github. As a start, I've edited this question and uploaded the attachment to this repository. You can find it here . I'll be searching and editing questions over the next few days to find such links and upload them here (if the OP hasn't removed it already). among others. For now, I'll be handling the main account myself, as I don't see an easy way to add an account-wide admin (I'm still finding my way around it). But I can create repositories and add collaborators, just as I did for the above repository. So please let me know if new repos need to be created or you want to be added to anything. We'll figure out a saner plan as we move forward. I'll periodically update this post with more info.
{ "source": [ "https://mathematica.stackexchange.com/questions/5846", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/187/" ] }
5,852
Is there a function to find the period of an arbitrary (possibly complex) function in Mathematica ?
You can check out this one. I don't know how well it works Periodic`PeriodicFunctionPeriod[E^(I 2 Pi t) + Cos[3/9 Pi t], t] 6 Perhaps you are also interested in the other functions in that context. Check Names["Periodic`*"] EDIT As @Artes notes in the comments, in v10 there's a documented version of this function called FunctionPeriod
{ "source": [ "https://mathematica.stackexchange.com/questions/5852", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/651/" ] }
5,930
With Format -> Edit Stylesheet... it is possible to adjust text-properties, text-colors, formatting of equations, etc of a notebook and to use this style-definitions again by installing it as Stylesheet . Lately, I saw a very nice screen-shot of a notebook and I noticed, that not only the text-properties were adjusted, but the style of the input code too. Using the style-sheet editor notebook it is absolutely not obvious to me, how I could achieve the coloring of the input code. Question: Can someone explain what steps are necessary to set up my own code style?
The colors used by the syntax highlighter can be set by changing the styles for StandardForm . The following is a how-to that explains how I styled the input cell in the screenshot in the question. This should be a starting point to get your own custom highlighting scheme up and running. Note that you can also do the same by choosing the colours in Preferences > Appearance , but this is not easily portable and gets wiped away with a reinstall/corrupted/deleted FE/init.m file. Controlling via stylesheets is preferable. 1: Adding a new style cell and editing it To add new definitions for StandardForm , open the stylesheet that you wish to change, and enter StandardForm in the box next to the "Choose a style" Next, select the cell and press Cmd Shift E to show the cell contents (if you already have an existing style, edit that instead of creating a new one). You should see something like: Cell[StyleData["StandardForm"], ... ] 2: Setting up the different colours The syntax highlighting colours are set via nested rules for AutoStyleOptions , with individual style tokens corresponding to patterns, errors, undefined variables, etc. The basic syntax for this is Cell[StyleData["StandardForm"], AutoStyleOptions -> { "StyleToken1" -> {FontColor -> RGBColor[...], FontSlant -> ...}, "StyleToken2" -> {FontColor -> RGBColor[...]}, ... } ] Here's a dummy example that I put together to show the different style tokens and what they each are responsible for In addition to colours, you can set each of these to have different slants/weights, etc. A full list of style tokens is {"CommentStyle", "EmphasizedSyntaxErrorStyle", "ExcessArgumentStyle", "FunctionLocalVariableStyle", "LocalScopeConflictStyle", "LocalVariableStyle", "MissingArgumentStyle", "OrderOfEvaluationConflictStyle", "PatternVariableStyle", "StringStyle", "SymbolShadowingStyle", "SyntaxErrorStyle", "UndefinedSymbolStyle", "UnknownOptionStyle", "UnwantedAssignmentStyle"} I personally do not like using all possible tokens and only set the ones shown in the dummy example. Too many colours makes it jarring, but to each his own. 3: Changing the main font and background colors Finally, you can set the main font properties. This is what controls the colour of the "defined" variables. For example (include the styles from above in the ... ), Cell[StyleData["StandardForm"], ... FontFamily -> ..., FontSize -> 12, FontWeight -> "Plain", FontSlant -> "Plain" ] When you put all of these together, close the cell contents by pressing Cmd Shift E again. Now you're all set to use the new styles. These styles will be set only for that particular notebook. If you want to set them as default for all notebooks, you should save the stylesheet in $UserBaseDirectory/SystemFiles/FrontEnd/StyleSheets/
{ "source": [ "https://mathematica.stackexchange.com/questions/5930", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/187/" ] }
5,933
This should be easy but I can't seem to find the right way to do it. I have an equation of the form $a x + b x + c y + a z + d z = 0$, and I'd like to solve for relations between the parameters $a,b,c,d$, etc. such that the equation holds for all values of $x,y,z$, etc. This is a very simplified example of the kind of equation I'm dealing with; there are actually 308 variables $x,y,\ldots$ and 42 parameters $a,b,\ldots$, making this nontrivial. As in the short sample equation, different variables could have the same parameter and could appear multiple times with different parameters. So far my best attempt is: Solve[ForAll[{x, y, ...}, a*x + b*y + ... == 0], {a, b, ...}] This yields the correct solution on a smaller equation (about 20 variables and 9 parameters) but is far too slow for this one. Is there a more specific technique I could use that's more optimized for this kind of problem specifically? Leaving out ForAll yields solutions in terms of the x-variables, which is kind of useless. EDIT: nikie mentioned a much better way to do it (in the comments)! Thanks!
The colors used by the syntax highlighter can be set by changing the styles for StandardForm . The following is a how-to that explains how I styled the input cell in the screenshot in the question. This should be a starting point to get your own custom highlighting scheme up and running. Note that you can also do the same by choosing the colours in Preferences > Appearance , but this is not easily portable and gets wiped away with a reinstall/corrupted/deleted FE/init.m file. Controlling via stylesheets is preferable. 1: Adding a new style cell and editing it To add new definitions for StandardForm , open the stylesheet that you wish to change, and enter StandardForm in the box next to the "Choose a style" Next, select the cell and press Cmd Shift E to show the cell contents (if you already have an existing style, edit that instead of creating a new one). You should see something like: Cell[StyleData["StandardForm"], ... ] 2: Setting up the different colours The syntax highlighting colours are set via nested rules for AutoStyleOptions , with individual style tokens corresponding to patterns, errors, undefined variables, etc. The basic syntax for this is Cell[StyleData["StandardForm"], AutoStyleOptions -> { "StyleToken1" -> {FontColor -> RGBColor[...], FontSlant -> ...}, "StyleToken2" -> {FontColor -> RGBColor[...]}, ... } ] Here's a dummy example that I put together to show the different style tokens and what they each are responsible for In addition to colours, you can set each of these to have different slants/weights, etc. A full list of style tokens is {"CommentStyle", "EmphasizedSyntaxErrorStyle", "ExcessArgumentStyle", "FunctionLocalVariableStyle", "LocalScopeConflictStyle", "LocalVariableStyle", "MissingArgumentStyle", "OrderOfEvaluationConflictStyle", "PatternVariableStyle", "StringStyle", "SymbolShadowingStyle", "SyntaxErrorStyle", "UndefinedSymbolStyle", "UnknownOptionStyle", "UnwantedAssignmentStyle"} I personally do not like using all possible tokens and only set the ones shown in the dummy example. Too many colours makes it jarring, but to each his own. 3: Changing the main font and background colors Finally, you can set the main font properties. This is what controls the colour of the "defined" variables. For example (include the styles from above in the ... ), Cell[StyleData["StandardForm"], ... FontFamily -> ..., FontSize -> 12, FontWeight -> "Plain", FontSlant -> "Plain" ] When you put all of these together, close the cell contents by pressing Cmd Shift E again. Now you're all set to use the new styles. These styles will be set only for that particular notebook. If you want to set them as default for all notebooks, you should save the stylesheet in $UserBaseDirectory/SystemFiles/FrontEnd/StyleSheets/
{ "source": [ "https://mathematica.stackexchange.com/questions/5933", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1304/" ] }
5,935
Compile[{{x, _Real, 1}}, MemberQ[x, 2]][{2}] outputs False . In fact, it seems to get compiled as False for every input if you look at a CompilePrint . It doesn't call the main evaluator, and MemberQ is included in the Compile`CompilerFunctions[] list Any ideas?
The colors used by the syntax highlighter can be set by changing the styles for StandardForm . The following is a how-to that explains how I styled the input cell in the screenshot in the question. This should be a starting point to get your own custom highlighting scheme up and running. Note that you can also do the same by choosing the colours in Preferences > Appearance , but this is not easily portable and gets wiped away with a reinstall/corrupted/deleted FE/init.m file. Controlling via stylesheets is preferable. 1: Adding a new style cell and editing it To add new definitions for StandardForm , open the stylesheet that you wish to change, and enter StandardForm in the box next to the "Choose a style" Next, select the cell and press Cmd Shift E to show the cell contents (if you already have an existing style, edit that instead of creating a new one). You should see something like: Cell[StyleData["StandardForm"], ... ] 2: Setting up the different colours The syntax highlighting colours are set via nested rules for AutoStyleOptions , with individual style tokens corresponding to patterns, errors, undefined variables, etc. The basic syntax for this is Cell[StyleData["StandardForm"], AutoStyleOptions -> { "StyleToken1" -> {FontColor -> RGBColor[...], FontSlant -> ...}, "StyleToken2" -> {FontColor -> RGBColor[...]}, ... } ] Here's a dummy example that I put together to show the different style tokens and what they each are responsible for In addition to colours, you can set each of these to have different slants/weights, etc. A full list of style tokens is {"CommentStyle", "EmphasizedSyntaxErrorStyle", "ExcessArgumentStyle", "FunctionLocalVariableStyle", "LocalScopeConflictStyle", "LocalVariableStyle", "MissingArgumentStyle", "OrderOfEvaluationConflictStyle", "PatternVariableStyle", "StringStyle", "SymbolShadowingStyle", "SyntaxErrorStyle", "UndefinedSymbolStyle", "UnknownOptionStyle", "UnwantedAssignmentStyle"} I personally do not like using all possible tokens and only set the ones shown in the dummy example. Too many colours makes it jarring, but to each his own. 3: Changing the main font and background colors Finally, you can set the main font properties. This is what controls the colour of the "defined" variables. For example (include the styles from above in the ... ), Cell[StyleData["StandardForm"], ... FontFamily -> ..., FontSize -> 12, FontWeight -> "Plain", FontSlant -> "Plain" ] When you put all of these together, close the cell contents by pressing Cmd Shift E again. Now you're all set to use the new styles. These styles will be set only for that particular notebook. If you want to set them as default for all notebooks, you should save the stylesheet in $UserBaseDirectory/SystemFiles/FrontEnd/StyleSheets/
{ "source": [ "https://mathematica.stackexchange.com/questions/5935", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/109/" ] }
5,940
Mathematica has a lot of very useful undocumented features. For example a hash table , a built-in list of compilable functions , additional options to CurrentValue , {"Raw", n} histogram bin specification, etc ... A natural question that arises is: Why is this functionality undocumented? Is it because the feature is under development? Or because the syntax has not been finalized and may be changed? Something else? Also: Is using this functionality safe in the sense that it will not cause problems when a new version is released?
The two main arguments against using undocumented functions are: Your code might not work as expected in future versions; Your code might not work as you intended in the current version, because you only have a partial understanding of a function or option that is undocumented. In the case of Mathematica, though, there is no guarantee that even documented functions will remain unchanged in future versions. Even a basic function like Random , which was introduced in version 1, was deprecated in version 6 in favour of RandomReal and RandomInteger (and of course, RandomVariate in version 8). Sometimes the old functions still work, but in other cases the Compatibility Checker detects that code changes are necessary. (See this list of changes in version 6 - the very last line mentions the Compatibility Checker .) This is despite Wolfram's claims and best efforts to maintain forward compatibility of old code . A search of the documentation provides a large list of symbols that have been obsoleted in recent versions. There is even a tutorial describing all the incompatible changes between versions. It only goes up to version 7, so it seems there might be some undocumented changes even here. The two main arguments for using undocumented functions are: Oftentimes they presage the permanent inclusion of that functionality in a future version. For example, ScalingFunctions is only documented for charting functions like BarChart , but it has been shown to work also for ListPlot and Plot (but not DateListPlot ). I predict that they will get around to completing (and documenting) this functionality in a future version. ( EDIT: In fact, that's exactly what happened in 10.4, even though the online version of the documentation doesn't make it clear that this is new. ) The functionality might be documented, but not completely documented. For example, some option values (say PlotRegion ) are documented as applying to "graphics functions", without specifying which ones. So the functionality is there, and might well remain stable for several versions. Mathematica is a complex system with an enormous array of possibilities for the use and abuse of its rich functionality. Even with the massive documentation that exists, there are bound to be some undocumented or incompletely documented functions. Undocumented functions (and options) need to used with some care, but given the usefulness of some of the functionality they offer, it might well be worth the risk.
{ "source": [ "https://mathematica.stackexchange.com/questions/5940", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/745/" ] }
5,959
Piggybacking on this , I am somehow not fully convinced that I can't save data generated by a calculation in a mathematica file so that when I re-launch said file, I wouldn't have to run my calculations again. I ask because I use NDSolve for 4th order non linear PDEs and sometimes I need to run it for really large times (in excess of a few hours, yes that sounds crazy but I am just trying to get results for a fluid dynamics problem here and I am not all that interested in being a computer scientist to reduce run times). So after reading the linked article, I did this for an example problem: sol = NDSolve[{D[u[t, x], t] == D[u[t, x], x, x], u[0, x] == 0, u[t, 0] == Sin[t], u[t, 5] == 0}, u, {t, 0, 10}, {x, 0, 5}] DumpSave["pde0.mx", sol] Then I quit mathematica and relaunch it and load pde0.mx with Get Get["pde0.mx"] And when I plot, Plot3D[Evaluate[u[t, x] /. sol], {t, 0, 10}, {x, 0, 5}, PlotRange -> All] Voila, I get the plot as if I had run the simulation. So.. did I run the simulation again by invoking sol through Get or was my kernel state saved?
What was saved was the content of sol , which happens to contain the solution to your equation (you explicitly set it to that), and therefore is certainly sufficient for your plot. Saving Kernel state however would involve saving things like the random seed, so the following would give the same output twice (using a hypothetical function SaveKernelState and corresponding LoadKernelState ): SaveKernelState["somefile"] Print[RandomInteger[10, 10]] (* ==> {5, 0, 1, 1, 7, 4, 4, 7, 9, 8} *) LoadKernelState["somefile"] Print[RandomInteger[10, 10]] (* ==> {5, 0, 1, 1, 7, 4, 4, 7, 9, 8} *) Also there are internal caches for things like FullSimplify , e.g. FullSimplify[Sum[Sin[k^2 x],{k,0,8}]]//Timing (* {2.89218, Sin[x] + Sin[4 x] + Sin[9 x] + Sin[16 x] + Sin[25 x] + Sin[36 x] + Sin[49 x] + Sin[64 x]} *) FullSimplify[Log[Sum[Sin[k^2 x],{k,0,8}]]]//Timing (* {0.028002, Log[Sin[x] + Sin[4 x] + Sin[9 x] + Sin[16 x] + Sin[25 x] + Sin[36 x] + Sin[49 x] + Sin[64 x]]} *) Here, the result of the first FullSimplify was cached and reused in the second one. Saving full Kernel state would include saving those caches, so the second simplification would go much faster in the restarted session as well. Edit: After reading Leonid's answer and the comments (as well as the answer he linked), I've now written a function which does exactly what you ask for in your title: Save the data inside your notebook: SetAttributes[PermanentSet,HoldAll]; PermanentSet[var_Symbol,value_]:= (If[OwnValues[var] === {}, Module[{nb=EvaluationNotebook[]}, SelectionMove[nb, Before, EvaluationCell]; NotebookWrite[nb,Cell[ToString[Unevaluated[var]] <> " = Uncompress[\"" <> Compress[var=value] <> "\"]", "Input", Editable->False]]]]; var) This is used as follows: To set the ( previously unassigned ) variable a to the result of the time-consuming calculation Pause[2];1+1 , just write PermanentSet[a, Pause[2];1+1] Executing this while a is not set will evaluate the expression and assign the result ( 2 ) to a, but will additionally add a cell before this one, containing a = Uncompress["1:eJxTTMoPymRiYGAAAAtMAbA="] (now in this case, a = 2 would have been shorter :-)). So when you evaluate the notebook in order, you'll first evaluate that line, setting a to 2 , and only then the PermanentSet . Since PermanentSet now finds a already assigned, it doesn't evaluate the second argument again, but just returns the value. Bugs and Limitations: If the evaluation contains side effects, those side effects will not be executed when the variable is set from the previous cell. Therefore this should only be used for side-effect-free calculations. This code depends on the previous cell being evaluated before this one. Otherwise the evaluation is restarted. However, with side-effect-free calculations, it should be safe to abort that calculation and execute the previous cell. This code doesn't work if the variable has a value, therefore if you want to replace an existing value, you have to unset the value first. However that unsetting must not happen in the same cell, but in a cell before. Otherwise it will undo the setting by the previous cell on re-evaluation. If the cell containing PermanentSet is an initialization cell, the generated cell should be an initialization cell as well. However it isn't (because I don't know how to do that). Also, this will place the selection immediately before the cell containing the call. Ideally it would save where the current selection is and restore it afterwards. However I don't know how to do that either. Edit 2: Based on Rojo's idea to store the data in notebook tagging rules (a feature which I didn't know about before), I've now written a different version of PermanentSet which resolves some of the problems with the previous one. It now saves both the expression and the resulting value in the tagging rules. This way, the function is evaluated again iff the expression has changed. SetAttributes[PermanentSet,HoldAll]; PermanentSet[var_Symbol, value_] := Module[{nb=EvaluationNotebook[], name=ToString[Unevaluated[var]], expr=Compress[Unevaluated[value]]}, If[TrueQ[CurrentValue[nb, {TaggingRules, "Storage", name <> "expression"}] == expr], var = Uncompress@CurrentValue[nb, {TaggingRules, "Storage", name<>"value"}], CurrentValue[nb, {TaggingRules, "Storage", name<>"expression"}] = expr; CurrentValue[nb,{TaggingRules, "Storage", name<>"value"}] = Compress[var=value]]; var]; Bugs and Limitations: As soon as the expression is evaluated, it won't be evaluated again until the expression is changed. That may be desired, but it also may be undesired (e.g. if re-evaluating because some variables changed). You can force a re-evaluation be PermanentSet ting to a dummy value (e.g. Null ) before re-evaluating. I don't see an easy way to automate that, though, because the variables may be used in functions called during the evaluation; therefore it's not possible to automatically determine which variables/values are needed. Maybe a TrackedVariables option like the one for DynamicModule would be useful for this. There probably should be a PermanentUnset counterpart to PermanentSet . As in the previous version, it is not a good idea to have side effects in the expression, because they will not happen again.
{ "source": [ "https://mathematica.stackexchange.com/questions/5959", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/204/" ] }
5,968
It is known that space curves can either be defined parametrically, $$\begin{align*}x&=f(t)\\y&=g(t)\\z&=h(t)\end{align*}$$ or as the intersection of two surfaces, $$\begin{align*}F(x,y,z)&=0\\G(x,y,z)&=0\end{align*}$$ Curves represented parametrically can of course be plotted in Mathematica using ParametricPlot3D[] . Though implicitly-defined plane curves can be plotted with ContourPlot[] , and implicitly-defined surfaces can be plotted with ContourPlot3D[] , no facilities exist for plotting space curves like the intersection of the torus $(x^2+y^2+z^2+8)^2=36(x^2+y^2)$ and the cylinder $y^2+(z-2)^2=4$: Sometimes, one might be lucky and manage to find a parametrization for the intersection of two algebraic surfaces, but these situations are few and far between, especially if the two surfaces are of sufficiently high degree. The situation is worse if at least one of the surfaces is transcendental. How might one write a routine that plots space curves defined as the intersection of two implicitly-defined surfaces? It would be preferable if the routine returns only Line[] objects representing the space curve. A routine that handles only algebraic surfaces would be an acceptable answer, but it would be nice if your routine can handle transcendental surfaces as well. A bonus feature for the routine might be the ability to determine if the two surfaces given do not have a space curve intersection, or intersect only at a single point, or other such degeneracies.
I take zero credit for this. It is a method I learned from Maxim Rytin. ContourPlot3D[{(x^2 + y^2 + z^2 + 8)^2 - 36 (x^2 + y^2), y^2 + (z - 2)^2 - 4}, {x, -4, 4}, {y, -4, 4}, {z, -2, 2}, Contours -> {0}, ContourStyle -> Opacity[0], Mesh -> None, BoundaryStyle -> {1 -> None, 2 -> None, {1, 2} -> {{Green, Tube[.03]}}}, Boxed -> False]
{ "source": [ "https://mathematica.stackexchange.com/questions/5968", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/50/" ] }
5,978
I would like to create a progress bar tool that allows me to see how my computations are going. I found answers to this question on many sites, I even found a package for it ( http://www.physics.ohio-state.edu/~jeremy/mathematica/progress/#download ), but unfortunately, I have no knowledge whatsoever on programming and such, so I could not really understand the instructions for installing it properly (didn't know wether to use a notebook to create the package, go to the kernel, or something else?). So I would really really appreciate if somebody could provide detailed step by step instructions for me to be able to get the progress bar going.
I'd build something using Monitor and ProgressIndicator . For example: Monitor[ Table[Pause[0.1]; Prime[i], {i, 100}], Row[{ProgressIndicator[i, {1, 100}], i}, " "] ] This shows a progress indicator while the calculation is underway and then it disappears once the calculation has finished If you look at Jeremy's file progress.m you linked to, you'll see that he defined functions like ProgressTable that are able to understand the iterator specifications. This is a decent approach, and I'm now going to do something similar in writing a ShowProgress function that understands basic Table iterators and has a generic fallback. (* ShowProgress needs to hold it's arguments, otherwise it tries to show progress for something that's already completely done.*) SetAttributes[ShowProgress, HoldAll]; (* Basic table syntaxes. Excludes {i, {i1, i2, ...}} and multi-iterator forms *) ShowProgress[Table[e_, {i_, max_}]] := ShowProgress[Table[e, {i, 1, max, 1}]] ShowProgress[Table[e_, {i_, min_, max_}]] := ShowProgress[Table[e, {i, min, max, 1}]] ShowProgress[Table[e_, {i_, min_, max_, step_}]] := Monitor[ Table[e, {i, min, max, step}], Row[{ProgressIndicator[i, {min, max}], i}, " "] ] (* Fall-back: shows an indeterminate progress bar and elapsed time, updating a few times per second *) ShowProgress[a_] := With[{progressStartTime = AbsoluteTime[]}, Monitor[ a, Dynamic[Refresh[ Row[{ ProgressIndicator[Dynamic[Clock[]], Indeterminate], AbsoluteTime[] - progressStartTime }, " "], UpdateInterval -> 0.25]] ]] Here are some examples of ShowProgress in use: I like this approach instead of the use of Progress... functions like in Jeremy's package because you don't need to change much of your code. You could hook ShowProgress in via $Pre to get automatically applied to everything. If you're willing to change code and use a special function when needed, then the Progress... functions are fine, although not too much different from ShowProgres[...] . The indeterminate progress bar with elapsed time is hopefully a little bit useful in the generic case where it can be difficult to know ahead of time how long a calculation will take. (Technically, there are times when it's unknown ahead of time whether something will finish at all.)
{ "source": [ "https://mathematica.stackexchange.com/questions/5978", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1307/" ] }
5,998
I have restricted the context of my notebooks to each individual notebook. So variables in each notebook are local and are not seen in another notebook. But in two of my notebooks I have two functions that I want to plot simultaneously with the command Show . Please note that I want variables of each notebook to be local except for those two functions. So I need to define two global variables and then plot that two functions in Show . How can I define global variables in Mathematica?
You can explicitly define variables in the global context by prefixing their name with Global` , for example, Global`i = 3 or Global`f[x_]:=x^2 . However if you have set the notebook to have private context, you don't have Global` in your $ContextPath (in order to prevent interference from other notebooks with non-private context). Therefore in your notebooks the context Global` isn't really special, you can use any context, like myShared` . Indeed, that's desirable because that way you know that a third notebook will be unlikely to interfere. So you would write in your first notebook myShared`function[x_]:=x^2 and then could access that function from the other notebook as myShared`function[3] (* ==> 9 *) Note that you can add your context to the context path by using AppendTo[$ContextPath, "myShared`"] This then allows you to refer to the function above without the prefix, e.g. function[3] (* ==> 9 *) However note that with this, your local symbols may shadow the shared ones (however access as myShared`function still works even then), so you have to make sure that you don't use the unprefixed symbol in any way before the prefixed one was created. You might consider avoiding the issue by using PrependTo instead of AppendTo , but then you are vulnerable to variable injection (including accidental one) from the other notebook. For example, imagine that you have the definitions a = 3; PrependTo[$ContextPath, "myShared`"] and then you do in your other notebook Begin["myShared`"] function[a_] := a^2 other[a_] := 5 End[] Let's assume the symbol a had not yet been used in that notebook, then it is created, together with the symbols function and other , in the context myShared` , and therefore in your first notebook now hides the local definition of a . That is, if you now evaluate a in your first notebook, the kernel will find myShared`a (without a value) first, and therefore use that instead of the local a ; of course it won't evaluate to 3. Yet another way to access the symbol without prefix would be the definition function := myShared`function which however only works in a context with evaluation. Especially it should not be used for shared variables because after variable := myShared`variable a subsequent assignment like variable = 42 does not change the shared variable, but only the local one (which no longer refers to the shared one). Therefore I think it is a better idea to not do either, but always use the prefixed version. Note that the PrependTo scenario is also an argument against using Begin["myShared`"] … End[] to simplify definitions in this case: It's too easy to accidentally introduce new symbols in that context which were not intended to be there. Note that another way of sharing functions is to make them into a package and use that package from both notebooks. Ultimately this also boils down to having a shared context, as rcollyer noted in the comments. However a properly written package protects against or at least warns about most problems with hiding. Of course, writing a package might be overkill for your specific situation.
{ "source": [ "https://mathematica.stackexchange.com/questions/5998", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1205/" ] }
6,004
In a Fourier series, the maximum error bound is the difference of the function and the partial sum of its Fourier series. Within an interval, as we increase the number of terms of partial sums, the error decreases. $$e(x) = \left|f(x) − s(x)\right|$$ How can I determine the number of terms needed to calculate the partial sum so as to have a specific maximum error bound? For e.g $|e(x)| ≤ 0.01$ or $|e(x)| ≤ 0.001$ For example in a typical question, $f(x)$ defined as $$f (x) = \begin{cases} 0 &−3 \leq x \leq 0\\ x^2(3 − x) & 0 < x < 3 \end{cases}$$ is a periodic function with period $6$ i.e., $f (x + 6) = f (x)$ Plot $|e(x)|$ versus $x$ for $0 ≤ x ≤ 3$ for several values of $m$. Find the smallest value of $m$ for which $|e(x)| ≤ 0.1$ for all $x$. Constructing the Fourier series for this periodic function and plotting $|e(x)|$ versus $x$ for several partial sums like $m = 5, 10, 20$ is easy. It can be accomplished by DiscretePlot . How can I find the smallest value of $m$ (i.e., the number of terms needed in the partial sum to achieve a specific error bound)? I use Mathematica 6 and 7.
You can explicitly define variables in the global context by prefixing their name with Global` , for example, Global`i = 3 or Global`f[x_]:=x^2 . However if you have set the notebook to have private context, you don't have Global` in your $ContextPath (in order to prevent interference from other notebooks with non-private context). Therefore in your notebooks the context Global` isn't really special, you can use any context, like myShared` . Indeed, that's desirable because that way you know that a third notebook will be unlikely to interfere. So you would write in your first notebook myShared`function[x_]:=x^2 and then could access that function from the other notebook as myShared`function[3] (* ==> 9 *) Note that you can add your context to the context path by using AppendTo[$ContextPath, "myShared`"] This then allows you to refer to the function above without the prefix, e.g. function[3] (* ==> 9 *) However note that with this, your local symbols may shadow the shared ones (however access as myShared`function still works even then), so you have to make sure that you don't use the unprefixed symbol in any way before the prefixed one was created. You might consider avoiding the issue by using PrependTo instead of AppendTo , but then you are vulnerable to variable injection (including accidental one) from the other notebook. For example, imagine that you have the definitions a = 3; PrependTo[$ContextPath, "myShared`"] and then you do in your other notebook Begin["myShared`"] function[a_] := a^2 other[a_] := 5 End[] Let's assume the symbol a had not yet been used in that notebook, then it is created, together with the symbols function and other , in the context myShared` , and therefore in your first notebook now hides the local definition of a . That is, if you now evaluate a in your first notebook, the kernel will find myShared`a (without a value) first, and therefore use that instead of the local a ; of course it won't evaluate to 3. Yet another way to access the symbol without prefix would be the definition function := myShared`function which however only works in a context with evaluation. Especially it should not be used for shared variables because after variable := myShared`variable a subsequent assignment like variable = 42 does not change the shared variable, but only the local one (which no longer refers to the shared one). Therefore I think it is a better idea to not do either, but always use the prefixed version. Note that the PrependTo scenario is also an argument against using Begin["myShared`"] … End[] to simplify definitions in this case: It's too easy to accidentally introduce new symbols in that context which were not intended to be there. Note that another way of sharing functions is to make them into a package and use that package from both notebooks. Ultimately this also boils down to having a shared context, as rcollyer noted in the comments. However a properly written package protects against or at least warns about most problems with hiding. Of course, writing a package might be overkill for your specific situation.
{ "source": [ "https://mathematica.stackexchange.com/questions/6004", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1312/" ] }
6,013
I cannot find how to use relative paths in Mathematica. My directory structure is simple. Import["G:\\Research\\Acc and Vel Runs\\5-24\\Mathematica\\Data\\250 \ Acc.xls"][[1]] // TableForm That demonstrates the absolute path by using the insert path from the menus. I want this notebook to be portable. I want to give someone the "Mathematica" directory and I want them to be able to run the code. I don't want the paths to break because It will be run on a different machine. Basically I just want to use a relative path starting at the Mathematica level shown above.
If your notebook is in the top directory, you can use Import[FileNameJoin[{NotebookDirectory[], "path", "to", "your", "file.xls"}]] where the string is the relative path from that directory. If your notebook is elsewhere in the directory tree and you want to set paths relative to a different directory, then you could define a global $ParentDirectory and then use all paths relative to that by joining strings as in the above example. Then all that the other person needs to do is to set this global value once and they're good. For example: $ParentDirectory = FileNameJoin[{"absolute", "path", "to", "mathematica"}]; Import[FileNameJoin[{$ParentDirectory, "path", "to", "your", "file.xls"}] As Albert Retey points out, you can also use ParentDirectory[NotebookDirectory[]] to give you the parent directory of the notebook's directory. In other words, it is an equivalent of cd .. from that directory and can be nested as many times as required.
{ "source": [ "https://mathematica.stackexchange.com/questions/6013", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1317/" ] }
6,036
I'm writing a numerical optimization, and I'm having a problem with an expression of the form $$ e^{-t} (1+\mathrm{erf}(t)) $$ The overall shape of the function looks correct, but when $t$ is small, $e^{-t}$ is huge while $(1+\mathrm{erf}(t))$ is very small, and their product is also small. This leads to horrible floating point inaccuracies. I know, of course, that there are multiple things I can do to remedy this, including scaling my problem so that the values are more reasonably sized. Another is to reformulate the expression to avoid ever computing the huge intermediate values. In the particular example I've given, this is simple: $$ e^{-t} (1+\mathrm{erf}(t)) \\ \exp{\left[ \log(e^{-t}) + \log{(1+\mathrm{erf}(t))} \right]} \\ \exp{\left[ -t \log{(1+\mathrm{erf}(t))} \right]} $$ ...which is well behaved for all reasonable values of $t$. However, in my actual expression, there are various parameters with respect to which I take the derivative. The resulting expressions are hideous and reformulating them by hand is daunting (although tractable). Is there a way to make Mathematica reformulate an expression while attempting to avoid expressions that will be numerically unstable? I don't expect Mathematica to be automatically aware of which expressions will be problematic, but if I could, for example, simply instruct it to avoid using Exp[] unless it absolutely must, this would be a very useful tool for me (and I suspect for other people working on numerical optimization!). Note: I am not doing the optimization work in Mathematica. I'm only using Mathematica to help derive analytical gradients for my merit function. Therefore, any features of Mathematica which would eliminate the numerical inaccuracy only in Mathematica doesn't really help me.
If you at least know in advance the range in which you will later evaluate, you might consider Taylor series or related approximate forms, using Mathematica to derive such forms and to approximate an error bound. In your example: In[5]:= func = Exp[-t]*(1 + Erf[t]); ser = Series[Exp[-t]*(1 + Erf[t]), {t, 0, 4}]; approxpoly = Normal[ser] Out[7]= 1 + (-1 + 2/Sqrt[Pi])*t + (1/2 - 2/Sqrt[Pi])*t^2 + (-(1/6) + 1/(3*Sqrt[Pi]))*t^3 + (1/24 + 1/(3*Sqrt[Pi]))*t^4 That is a Taylor polynomial approximation near the origin. We can find the coefficient of the next term to give a first order approximation of the error term. In[4]:= SeriesCoefficient[Exp[-t] (1 + Erf[t]), {t, 0, 5}] // N Out[4]= -0.0365428 So the error is around 3/100*t^5 in magnitude near t = zero. This of course assumes the series converges in that region, but in this case at least we know it does (if it did not, your problems would go beyond numerical (in)stability). At t=1, this error is In[13]:= func - approxpoly /. t -> 1. Out[13]= -0.0732347 If you anticipate values of t in that range you might want to use more terms in the polynomial, or else switch before t=1 to a different approximation (this is assuming an error of 7% is more than you want to allow). The table below will give a better idea of the error sizes for t in the range of (-1,1). In[16]:= Table[func - approxpoly, {t, -1., 1., .1}] Out[16]= {-0.0239914, -0.0110741, -0.00431147, -0.0012192, \ -0.0000860751, 0.000162876, 0.000119029, 0.0000438515, 7.806*10^-6, 3.05852*10^-7, 0., -4.21962*10^-7, -0.0000151951, -0.000127231, \ -0.000581433, -0.00189768, -0.00499075, -0.0112854, -0.0228166, \ -0.0423096, -0.0732347} As you would be evaluating outside of Mathematica, you would be substituting the approximations for the function of interest. What I indicate above is an idea of how Mathematica might be utilized to derive and assess them for quality.
{ "source": [ "https://mathematica.stackexchange.com/questions/6036", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1322/" ] }
6,055
When I solve this equation in Mathematica 8, I can get the right answer, but with some uncomfortable warnings. Equation: Solve[-26.81 == 194 k + k*l*32.9 && 22.2 == -74 k + k*l* 59.7, {k, l}] Warnings: Solve::ratnz: Solve was unable to solve the system with inexact coefficients. The answer was obtained by solving a corresponding exact system and numericizing the result. >> If I transform the above equation to the following, then it works fine, but this is not convenient: {k, kl/k} /. Solve[-26.81 == 194 k + kl*32.9 && 22.2 == -74 k + kl* 59.7, {k, kl}] So my question is, how can I get rid of such warnings?
You can get rid of the warning by converting everything to exact numbers yourself before passing the equation to Solve (the warning message suggests that this is what Solve does itself): In[2]:= Rationalize[-26.81 == 194 k + k*l*32.9 && 22.2 == -74 k + k*l*59.7] Out[2]= -(2681/100) == 194 k + (329 k l)/10 && 111/5 == -74 k + (597 k l)/10 In[3]:= Solve[%] Out[3]= {{l -> -(2322860/2330937), k -> -(2330937/14016400)}} In[4]:= N[%] Out[4]= {{l -> -0.996535, k -> -0.166301}} Solve (like all symbolic manipulation function) is meant to be used with exact numbers where roundoff errors are not an issue. For solving the equation numerically, use NSolve : In[5]:= NSolve[-26.81 == 194 k + k*l*32.9 && 22.2 == -74 k + k*l*59.7] Out[5]= {{l -> -0.996535, k -> -0.166301}} Some background on exact and inexact numbers: Exact and Approximate Results In Mathematica, any number with a decimal point in it is considered to be inexact, i.e. known only to a certain number of digits. 2 is exact, 2.0 is inexact machine precision and 2.0`5 is inexact arbitrary precision known to 5 digits . Symbolic computations ( Integrate , Solve , Reduce , etc.) work best with exact numbers. Try to avoid inexact numbers with such functions. See more on Numbers
{ "source": [ "https://mathematica.stackexchange.com/questions/6055", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/907/" ] }
6,081
I have a list of coordinates in form {{x1,y1},{x2,y2},...} Is there a way in mma to builds density plots based on position ( ListDensityPlot calculates density based on value in {x,y,value} )? I want to create something similar to heatmap.py .
There are two functions that can do this: DensityHistogram Histogram3D These functions also come in a smoothed version (prepend Smooth to the name), which can be used to obtain results similar to what Heike plotted. Edit If you work in a regime where individual points are resolved, you may notice a disconcerting shift in the output of SmoothDensityHistogram (at least I see it on Mac OS X, MMA version 8.0.4): data = RandomReal[1, {100, 2}]; Show[ SmoothDensityHistogram[data, 0.015, "PDF", ColorFunction -> "Rainbow", Mesh -> 0, PlotRange -> {{0, 1}, {0, 1}}], Graphics[Point@data], PlotRange -> {{0, 1}, {0, 1}} ] I only noticed this after looking at R.M.'s plot with the original points superimposed, as shown above. To fix this and at the same time understand better what these smoothed histogram plots really do, you could take a look at the following function: heatMap[data_, opts : OptionsPattern[]] := Module[ {n, size, xRange, pr}, n = "Points" /. {opts} /. {"Points" -> 100}; pr = PlotRange /. {opts} /. {PlotRange :> Map[{Min[#], Max[#]} &, Transpose[data]]}; xRange = -Subtract @@ pr[[1]]; size = Floor[ n ("Radius" /. {opts} /. {"Radius" -> xRange/6})/xRange]; Graphics[{ Inset[ ArrayPlot[ Rescale@GaussianFilter[ ImageData@ColorNegate@ColorConvert[ Rasterize[Graphics[Point[data], Background -> White, PlotRangePadding -> 0, ImagePadding -> 0, ImageMargins -> 0, PlotRange -> pr], "Image", ImageSize -> n], "GrayScale"], {3 size, size}, Padding -> 0], ColorFunction -> (ColorFunction /. {opts} /. {ColorFunction -> ColorData["LakeColors"] } ), ImagePadding -> 0, PlotRangePadding -> 0, Frame -> False], pr[[All, 1]], {0, 0}, xRange]}, PlotRange -> pr, Frame -> True, PlotRangePadding -> Scaled[.02] ] ] Show[heatMap[data, "Points" -> 300, "Radius" -> .02, PlotRange -> {{0, 1}, {0, 1}}, ColorFunction -> ColorData["Rainbow"]], Graphics[Point@data], PlotRange -> {{0, 1}, {0, 1}}] So I basically re-implemented this plotting function by using GaussianFilter , without trying to implement all the options provided by the built-in function. The options it recognizes are "Points" (the number of sampling points in the horizontal direction), "Radius" (the radius of the Gaussian) and PlotRange . Besides giving better alignment between the heat map and the points, this manual approach also could be used to do some non-standard things. For example, you could change Padding -> 0 to Padding -> "Periodic" if the data points live on a torus topology. To show the dependence on the choice of radius, here is a movie: Export["l.gif", Join[#, Reverse[#]] &@ Table[Show[ heatMap[data, "Points" -> 300, "Radius" -> r^2, PlotRange -> {{0, 1}, {0, 1}}], Graphics[Point@data], PlotRange -> {{0, 1}, {0, 1}}], {r, .15, .25, .015}], "DisplayDurations" -> .1] Edit I forgot to add ColorFunction as an option - that's now done, with "LakeColors" as the default, as it is for SmoothDensityHistogram . There was also a Frame -> False missing in ArrayPlot , which I fixed in the code. As an added bonus, plots created with heatMap take much less space when exported as PDF .
{ "source": [ "https://mathematica.stackexchange.com/questions/6081", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/4/" ] }
6,114
Span ( ;; ) is very useful, but doesn't work with a lot of functions. Given the following input list = {{"a", "b", "c"}, {"d", "e", "f", "g"}, {"h", {{"i", "j"}, {"k", "l"}, {"m", "n"}, {"o", "pp"}}}} We would like MapAt[Framed, list, 1 ;; 2] MapAt[Framed, list, {{1, 1}, {2, 2 ;; 3}, {3, 2, 1 ;; 3, 1}}] to work as expected Here is my first go at it: SpanToRange[Span[x_:1,y_:1,z_:1]] := Module[{zNew = z}, If[x>y && z==1, zNew = -1]; Range[x, y, zNew] ] /; And[VectorQ[{z,y,z}, IntegerQ], And @@ Thread[{z,y,z} != 0]] helper = Function[list, Module[{li=list}, If[FreeQ[li, Span], li, li = Replace[li,s_ /; Head[s] =!= Span :> {s}, {1}]; li = li /. s:_Span :> SpanToRange[s]; Sequence @@ Flatten[ Outer[List, Sequence @@ li], Depth[Outer[List, Sequence @@ li]]-3]] ] ]; protected = Unprotect[Span, MapAt]; Span /: MapAt[func_, list_, s:Span[x_:1,y_:1,z_:1]]:= MapAt[func, list, Thread[{SpanToRange[s]}]]; MapAt[func_, list_, partspec_] /; !FreeQ[partspec, Span] := Module[{f,p = partspec}, MapAt[func, list, Join[helper /@ p]] ]; Protect[Evaluate[protected]]; But this is far from finished, and the extended down values should support all valid uses of Span such as MapAt[Framed, list, 3 ;;] MapAt[Framed, list, ;; ;; 2] MapAt[Framed, list, ;; 10 ;; 2]
There is a hidden update in V9: MapAt works with Span . I've checked it does not work on V8 and V7. I just started to do this once in the past and it worked. I was newbie in Mathematica when there was V8 or V7 so I have not realised it is new till Mr. Wizard poited out in comments that I'm smoking crack :). I do not remember other case but it is the second, which I can recall, where there is no mark about this in documentation. I do not mean examples, I mean there is no " Last modyfied in 9 " for MapAt only " New in 1. ". Couple of examples where I've used it: Manipulate list from Excel Make a huge vector in a wise way I strongly recommend this, it is so handy, and, as Mr. Wizard noticed, fast ! big = Range[1*^5]; First@Timing@MapAt[#^2 &, big, List /@ Range[30000, 40000]] First@Timing@MapAt[#^2 &, big, 30000 ;; 40000] 10.202465 0.015600 Extended comparision inspired by RunnyKine : test = {}; Do[ big = Range[10^i]; AppendTo[test, {i, Mean@Last@Last@Reap@Do[ Sow@First@Timing@MapAt[#^2 &, big, List /@ Range[3000, 4000]], {10}], Mean@Last@Last@Reap@Do[ Sow@First@Timing@MapAt[#^2 &, big, 3000 ;; 4000], {10}] }] , {i, 5, 6.4, .2}] ListLogPlot[Transpose[test][[2 ;;]], Joined -> True, DataRange -> {5, 6.4}]
{ "source": [ "https://mathematica.stackexchange.com/questions/6114", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/403/" ] }
6,144
I'm looking for robust code to solve the "Longest Common Substring" problem : Find the longest string (or strings) that is a substring (or are substrings) of two or more strings. I can just code it up from that description, but I'd thought I'd ask here, first, in case someone knows of an implementation either distributed with Mathematica or available from an open source. I found a hint here that a solution might be part of the (huge) Combinatorica package, but a quick search of the documentation did not disclose it.
Mathematica supports two related functions, LongestCommonSequence[] and LongestCommonSubsequence[] . The first one finds the longest (contiguous or non-contiguous) sequence common to the two strings given as arguments to it: LongestCommonSequence["AAABBBBCCCCC", "CCCBBBAAABABA"] "AAABB" while the second function is constrained to give the longest contiguous sequence: LongestCommonSubsequence["AAABBBBCCCCC", "CCCBBBAAABABA"] "AAAB" These functions became available only in version seven; if you need to do this in an earlier version, István's routine is useful.
{ "source": [ "https://mathematica.stackexchange.com/questions/6144", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/387/" ] }
6,157
When creating a notebook with images, like photos, the file tends to quickly get big, which makes it difficult to use the notebook format for training material containing a lot of images. Are there different ways of passing an image into a notebook, in relation to memory used? (Please note that the purpose is to show the images in the “middle” of other content, like text, etc, and not simply have the image information in some kind of abstract code) I've noticed that every time I copy an image to a notebook, its FullForm reveals that it is "stored" with an "exhaustive" description of each pixel color value(s). Is there a way of storing it with indexed color definition (like the GIF format)? Is there a way of storing it with some kind of compression (like JPEG or similar)? EDIT: Meanwhile I discovered the following curiosity: if I Import a GIF file (of my printscreen), and then save it, my file gets to 150 kb. If I save it again (without changing anything), it gets reduced to 32 kb. If instead of Import ing it, I just copy it from the clipboard to the notebook, it always keeps the 150 kb.
The technique is mentioned in one of Wolfram CDF virtual conference talks ( See the course: Developing Real-World CDF Applications ), as well as being used in a lot of CDF examples ( for instance, the slideshow at the beginning of this example ) but I will repeat it here, with some improvement. Recompressing images with better compression (Note: While writing an answer, Rojo already provided the same method.) As it is mentioned by other users here, you don't have to manually use Compress since images are already being compressed using it when being stored inside a notebook cell. Compress is based on gzip and it is overall OK, except that it can be pretty horrible with images. Let's try to use other compression, for instance PNG (lossless) or JPEG (lossy) (or anything for that matter). Let's say our image is img . I am grabbing an image from the Hubble Gallery as an example. url = "http://imgsrc.hubblesite.org/hu/db/images/hs-2006-01-a-1920x1200_wallpaper.jpg"; img = Import[url]; This is a pretty big image. In[3]:= ByteCount[img] Out[3]= 6912464 Now, compress it using the compression of your choice and store it as string using ExportString . jpeg = ExportString[img, "JPEG"]; Of course, you can use any other compression (for instance, "PNG" or "GIF") or control compression rate for JPEG by using "CompressionLevel" option (default is 0.25). To embedded this data in a cell, it has to be converted to Base64 (essentially using non-special characters). base64 = ExportString[jpeg, "Base64"] This is a slightly larger than actual binary JPEG, but still far smaller than uncompressed size, or compressed size. In[6]:= ByteCount[base64] Out[6]= 219224 (To be fair, Mathematica will save it using aforementioned Compress and the size will be smaller than what ByteCount[img] is reporting, but not this small). By using ImportString , you can convert it back to the image: ImportString[base64, "Base64"] (You don't have to call ImportString again for the compression, since it will be automatically taken care of) To embedded the raw data ( jpeg ) and let FrontEnd uncompress it during the time of reading a notebook, try the following code. With[{a = base64}, Dynamic[ImportString[a, "Base64"], SingleEvaluation->True]] or With[{a = base64}, Dynamic[Refresh[ImportString[a, "Base64"], None]]] The extra option ( SingleEvaluation ) and Refresh are used to make sure that it is evaluated just once. Also, With is needed to ensure that the embedded cell contains the content of base64 , instead of a symbol base64 . This can play nicely with other cells, such as texts and other graphics, using Row or other constructions. Now, let's try to save it. First try: nb = CreateDocument[With[{a = base64}, Dynamic[ImportString[a, "Base64"], SingleEvaluation -> True]]]; NotebookSave[nb, "jpeg.nb"] Try to check the size of the file, and you will be surprised... It is smaller than a notebook with just the image (which will be around 5MB), but still not quite as smaller as we expected it to be. What's wrong? It is because Mathematica caches images by default. Let's disable it ( CacheGraphics->False will do it. You can set it using the Option Inspector too). nb2 = CreateDocument[With[{a = base64}, Dynamic[ImportString[a, "Base64"], SingleEvaluation -> True]], CacheGraphics->False]; NotebookSave[nb2, "jpeg2.nb"] Now, much reasonable: Using native compression of imported image Sometimes, your image is coming from external source with its own native compression. The problem with the first approach is that it essentially uncompress it then recompress using different compression / rate (sort of transcoding...). In particularly with lossy compression like JPEG, it may leads to image distortion. To minimize this, you can do the following. (Note: Szabolcs provided a nice solution using Import . Thank you) We can read the file's native binary data by caling Import[..., "String"] . jpeg = Import[url, "String"]; First, the image has to be in local storage. Bring its native binary data using BinaryReadList . Also, use "Character8" and StringJoin so that it will turn into the string of binary data. jpeg = StringJoin@@BinaryReadList["hs-2006-01-a-1920x1200_wallpaper.jpg", "Character8"]; It should be about the same size as the original file (+/- some due to the string representation in Mathematica). From here, you can follow the above steps to turn it into "Base64" and then embed. Reading image from online If you have a lot of images, then this can be applicable. Dynamic[Refresh[Import[url], None]] If it times out, you can increase the timeout using DynamicEvaluationTimeout or try the following to show a nice indicator while loading. DynamicModule[{img = None}, Dynamic[If[img === None, ProgressIndicator[Clock[Infinity], Indeterminate], img], TrackedSymbols :> {}], Initialization :> (img = Import["http://imgsrc.hubblesite.org/hu/db/images/hs-2006-01-a-1920x1200_wallpaper.jpg"]), SynchronousInitialization -> False] This course notebook contains some useful examples including a spinner for progress and such. Also, these techniques can be used to embed any large data, such as MOV file!
{ "source": [ "https://mathematica.stackexchange.com/questions/6157", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/78/" ] }
6,164
I'm sure I'm about to embarrass myself... but, here goes... I can't read any (but the most basic) typeset formulas in Mathematica. The fonts are simply way too small on my 2560x1440 monitor. If I make the font sizes bigger, Mathematica seems to simply scale-up the existing formula - making it large enough to be read, but it's ugly-as-sin. Too small (Mathematica): Too ugly (Mathematica): What I'm looking for: $\displaystyle \frac{\sum_{i = 1}^{n} x_i }{\sum_{i = 1}^{n} y_i} = \frac{\sum_{i = 1}^{n} ( (\frac{x_i}{y_i}) p ) }{n} $
The simplest way to get a slightly more acceptable typeset result is to use TraditionalForm as follows, after you enter the expression as in the question: \!\( \*UnderoverscriptBox[\(\[Sum]\), \(i = 1\), \(n\)] \*SubscriptBox[\(x\), \(i\)]\)/\!\( \*UnderoverscriptBox[\(\[Sum]\), \(i = 1\), \(n\)] \*SubscriptBox[\(y\), \(i\)]\) == \!\( \*UnderoverscriptBox[\(\[Sum]\), \(i = 1\), \(n\)]\((\(( \*FractionBox[ SubscriptBox[\(x\), \(i\)], SubscriptBox[\(y\), \(i\)]])\) p)\)\)/n Magnify[%] // TraditionalForm The reason this doesn't look exactly like what you want is that it wasn't wrapped in HoldForm . For more discussion of how to conveniently enter math expressions especially in the context of graphics labeling, see this answer . Here is a better way to enter things, but I better show just the image: Edit 2 In the other answer I linked above, I mentioned another way to input formulas that actually belongs into the context of this more general question as well. Therefore, I've made a screen capture to illustrate the steps for getting what I think is the closest to a typesetting interface with Mathematica. The screen movie has to be short because it's a GIF animation: I'm starting with the expression typeset in an input cell. In the next cell I add TraditionalForm content with a dummy string The content of the string ( aaa inside the quotation marks) is converted to TraditionalForm via the menu The original expression is pasted into the invisible FormBox that was now created around the aaa The resulting string can be edited further (e.g., I replace the == by = , but you can do arbitrary edits here) With an optional Magnify appended, I evaluate the cell and get the desired result
{ "source": [ "https://mathematica.stackexchange.com/questions/6164", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1342/" ] }
6,177
I've written my incredibly complex, incredibly elegant analysis function, that works great on small test data. But when I run it on my real (bigger) data set it keeps running out of memory. It turns out that the analysis function does not free memory, but I can't imagine why. It takes a large number of points, but returns only several scalar values. Every time I run this it takes up about 500 MB of memory. ( here is another example). What is the best way to debug memory problems? I've read the memory management tutorial, turned off caching and verified I have no lingering variables in my contexts and of course I have set $HistoryLength to zero. Also running Reverse@Sort[{ByteCount[Symbol[#]], #} & /@ Names["`*"]] show no huge memory symbols. Just the data: {{191816648, "alldata"}, {28184, "before"}, {28184, "after"}, {24096, "compiledSelectBin"}, {15344, "AppendLeftRight"}, {8840, "compiledSelectBinFunc"}...} EDIT One can use this code to track memory consumption: DynamicModule[{pm = {}}, Dynamic@Refresh[pm = Append[pm, MemoryInUse[]]; If[Length[pm] > 120, pm = Drop[pm, 1]]; ListPlot[pm/1024/1024, AxesLabel -> {"Time [s]", "Memory [MB]"}, PlotRange -> {0, All}], UpdateInterval -> 1, TrackedSymbols :> {}]] I think I finally have a minimum example. Here it is . Unzip to a folder and evaluate the two cells in LeakP.nb. If you evaluate the second cell multiple times you can watch the memory consumption grow. Could somebody (on win7 64 bit mma 8) confirm this? EDIT 1 I really hope I have nailed it down. Here is a self contained example: $HistoryLength = 0; data = RandomReal[{-1, 1}, {10, 100000, 2}]; data = Developer`ToPackedArray[#] & /@ data; data = Flatten[data, 1]; Dimensions[data] HistogramList[data, 30, Automatic]; ClearAll[data]; ClearSystemCache[]; EDIT 2 This is fixed in Mathematica 9.0.0.
Preamble It is hard to say what exactly is causing this without seeing the code, but, assuming that there are no memory leaks in the built-in functions you are using, I am only aware of a very few possible causes for memory leaks in Mathematica. Since almost anything is immutable, the leaks must be associated with some symbols for which definitions are accumulated but not cleared. I will show here one rather obscure case of leaking of local Module variables, which happens when the variable is referenced by some object / symbol, external w.r.t. its scope. In such cases, such variables are not garbage-collected even after the symbols referencing them get Remove -d, in case if they get assigned DownValues , SubValues or UpValues ( OwnValues are ok). One subtle case with a memory leak MemoryInUse[] 17350016 $HistoryLength = 0; Module[{g}, Module[{f}, g[x_] := f[x]; Do[f[i] = Range[i], {i, 5000}]; ]; g[1]] {1} MemoryInUse[] 72351376 One way to ensure that this does not happen is to insert Clear[f] at the end of the outer Module , storing the result in a separate variable and returning it afterwards. There are more advanced ways to prevent such things as well. I may elaborate on those at some later time. Memory leaks associated with UI-building One common cause of memory leaks which is often ovelooked is when some local symbols make it into UI elements. The problem is that UI elements are Mathematica expressions, which do reference those symbols, and therefore, they are not garbage-collected. Here is an example I borrowed from this thread memModule[] := Module[{data, memBefore, mu}, mu := Grid[{{"Memory in use: ", MemoryInUse[]/(2^30.), "GB"}}]; memBefore = mu; data = RandomReal[1, {300000, 20}]; DynamicModule[{d1}, d1 := data[[1]]; Panel[Grid[{{memBefore}, {mu}}]] , UnsavedVariables -> {dl} ] ]; Now, every time when it gets executed, more memory is being leaked: memModule[] memModule[] memModule[] Please see my answer in the linked thread for one way out, in this particular case. Generally, this is something to watch out for. Monitoring symbols So, one good place to start is to call Names["Global`*"] {"f", "f $", "f$ 119", "g", "i", "x", "x$"} or whatever main context you are using (or other contexts, if you create symbols there), and watch for some symbols with high memory usage. In this particular case, the culprit it f$119 . Here are some utility functions which may help with monitoring symbols: Clear[ $globalProperties]; $ globalProperties = {OwnValues, DownValues, SubValues, UpValues, NValues, FormatValues, Options, DefaultValues, Attributes, Messages}; ClearAll[getDefinitions]; SetAttributes[getDefinitions, HoldAllComplete]; getDefinitions[s_Symbol] := Flatten@Through[ Map[ Function[ prop, (* Unevaluated needed here just for Options, which is not holding *) Function[sym, prop[Unevaluated @ sym], HoldAll] ], $globalProperties ][Unevaluated[s]] ]; ClearAll[symbolMemoryUsage]; symbolMemoryUsage[sname_String] := ToExpression[sname, InputForm, Function[s, ByteCount[getDefinitions[s]], HoldAllComplete] ]; ClearAll[heavySymbols]; heavySymbols[context_, sizeLim_: 10^6] := Pick[#, UnitStep[# - sizeLim] &@Map[symbolMemoryUsage, #], 1] &@ Names[context <> "*"]; For example, calling heavySymbols["Global`"] returns {f$119}
{ "source": [ "https://mathematica.stackexchange.com/questions/6177", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/745/" ] }
6,206
I'm trying to extrude a nice 3D form from the 2D binary image below using the code posted, but I haven't had any luck in figuring out the error that's keeping GraphicsComplex from running. The end result should be the 3D points and a plot. Any help would certainly be appreciated! pts= ImageData[testimage]; twoD = Rescale[Table[Thread[{pts[[i]], pts[[i]]}], {i, 1, Length[pts]}]]; extrude[pts_, h_] := Module[{vb, vt, len = Length[pts], nh, shape}, If[! NumericQ[h], nh = 0., nh = N@h]; vb = Table[{pts[[i, 1]], pts[[i, 2]], 0}, {i, len}]; vt = Table[{pts[[i, 1]], pts[[i, 2]], nh}, {i, len}]; shape = GraphicsComplex[ Join[vb, vt], {Polygon[Range[len]], Polygon[Append[ Table[{i, i + 1, len + i + 1, len + i}, {i, len - 1}], {len, 1, len + 1, 2 len}]], Polygon[Range[len + 1, 2 len]]}] ]
One way to extrude a 3D object from a binary 2D image is to use RegionPlot3D : pts = ImageData[ColorNegate@Binarize@Import["http://i.stack.imgur.com/UWO6k.png"], "Bit"]; g = RegionPlot3D[pts[[Sequence @@ Round@{i, j}]] == 1, {i, 1, #1}, {j, 1, #2}, {z, 0, 1}, PlotPoints -> 100, Mesh -> False, Axes -> False, Boxed -> False] & @@ Dimensions[pts] pts = Cases[g, x_GraphicsComplex :> First@x, Infinity]
{ "source": [ "https://mathematica.stackexchange.com/questions/6206", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/686/" ] }
6,236
How do I get ShowLegend to put the max and min values that a plot produces. for example, when using ListDensityPlot , with PlotRange->Automatic , the plot can sometimes clip. How do I get ShowLegend to tell me what the values are that it is clipping at. For example: data = RandomReal[{0, 1}, {10, 10}]; Needs["PlotLegends`"]; ShowLegend[ ListDensityPlot[data, PlotRange -> Automatic], {ColorData["TemperatureMap"][1 - #1] &, 20, "upper", "lower", LegendPosition -> {1, 1}}] when data has a large dynamic range, mathematica cuts it off at the upper value and the lower value, I want to make it tell me what those values are in place of "upper" and "lower" I essentially want to figure out what the range of z values are that PlotRange picks, and then put them in the legend. I found AbsoluteOptions , however, when I do it on a contour plot it just gives the x,y ranges, not the z range.
Edit I updated the definitions of reportColorRange and colorLegend : added more comments in the code, allowed more customization options for the legend. Color gradients are produced by VertexColors for better-looking PDF export; gradients can also be replaced by color bands (using the "ColorSwathes" option). The labels on the color bar can be specified by adding the option Contours -> n where n is the number of subdivisions of the color legend. I'll add some examples at the end ot illustrate these new features. End Edit This question needs two parts to be answered fully: How to extract the range of height values from a ListDensityPlot How to get a legend, because ShowLegend has many problems: e.g., the numerical labels on the color bar are cut off, and it's just plain ugly. So I'll address both points here. Extract height range This is a particular challenge if the plot range is clipped, as happens for example when there is a near-divergence in the plot. To get the necessary values, one could do what Michael suggested in his answer. Instead, I collect the height values at the time the plot is created . My rationale is that this may make it possible to apply the same extraction algorithm not just to ListDensityPlot but also to other types of plot that work with ColorFunction , such as ContourPlot , in a more robust way that doesn't depend precisely on the internal tree structure of the plot output. I'll test that below, but first let's define a test list that has a near-singularity: t = Flatten[ Table[{x, y, 2/((x - 1)^2 + y^2)}, {x, -5, 5, .3}, {y, -5, 5, .3}], 1]; The function that extracts all the necessary information while simultaneously doing the plot is defined here: reportColorRange[plotFunction_] := Module[ {p, min, max, plotHead, plotBody, colFunc, colScale, h, b, cf, cfs}, {plotHead, plotBody} = First@Cases[ Hold[plotFunction], h_[b__] -> {h, Hold[b]}, 1 ]; (* plotBody is kept inside Hold because it will later be wrapped in plotHead which may have attribute HoldAll *) colFunc = Replace[ (* Replace wraps string colorfunction names in ColorData[...] *) First@ Join[Cases[plotBody, HoldPattern[ColorFunction -> cf_] -> cf], {ColorData[ "LakeColors"]} (*Extract color function or use default*) ], s_String :> ColorData[s]]; colScale = First@Append[ Cases[plotBody, HoldPattern[ColorFunctionScaling -> cfs_] -> cfs], True (*ColorFunctionScaling is True by default*)]; (*Turn off ColorFunction and scaling:*) plotBody = plotBody /. HoldPattern[ColorFunction -> _] | HoldPattern[ColorFunctionScaling -> _] -> Sequence[]; (*Make plot with Hue because it takes a single argument that's linear in the heigh value.*){min, max} = {Min[#], Max[#]} &@Flatten@Last@Reap[ p = Apply[ plotHead, Join[ (* Join creates a single Hold[...] expression, and Apply replaces hold with plotHead: *) plotBody, Hold[ (* Collect the function values - color function scaling must be turned off: *) ColorFunction -> {(Sow[#]; Hue[#]) &}, ColorFunctionScaling -> False] (* Hue now could have arguments outside the interval [0,1]. We'll recover them when restoring the original ColorFunction. *) ] ] ]; (*Reap collects the unscaled height values, and we keep the extremal values max, min to rescale if desired:*) {If[ (* If p consists of ploygons colored by Hue, convert it back to the original color function: *) Cases[p, Hue[_], Infinity] =!= {}, If[ (* Recover function values from Hue and plot them with desired color, scaled/unscaled: *) colScale, p /. Hue[x_] :> colFunc[(x - min)/(max - min)], p /. Hue[x_] :> colFunc[x] ], (* If plotHead is one of my private custom plot functions, then p may be a raster image where Hue no longer appears explicitly. Then we have to re- do the entire plot with the original color function: *) plotFunction ], colFunc, {min, max} } (* The auxiliary Hue is replaced by the original ColorFunction stored in colFunc.*)] SetAttributes[reportColorRange, HoldAll]; The last line means that you can provide an argument to this function that represents a density plot command, but the command isn't executed right away. Instead, the command is stored in the variable plotFunction and then pre-processed by changing the color function temporarily. The original, user-specified (or default) color function is restored to the plot result after extracting the height values. Here is what the function does to a ListDensityPlot of the test table t : {plot, colors, range} = reportColorRange[ ListContourPlot[t] ] This will work with DensityPlot or ListDensityPlot as well. The last tuple is the desired range information, and the first element is the plot. In the middle, we also receive the color function that has been used. I keep that information because it's needed to make the plot legend next. Important usage note: As mentioned above, reportColorRange monitors the plotting function as it creates the plot. Therefore, you have to provide the actual plotting function as the argument: reportColorRange[DensityPlot[...]] and not something like this: p = DensityPlot[...]; reportColorRange[p] . The latter won't work because the variable p then contains the already finished plot, and this can't be used to monitor the true minima and maxima of the function range that was explored during the creation of p . Color bar legend The legend first needs a color bar, and the output of the above test shows us how to get started: just look at the InputForm of the bar appearing in ColorDataFunction and copy the code. That's essentially what I did to define the colorLegend function listed below. There are a couple of other functions required for the display that I'll also list here: trimPoint[n_, digits_] := (* display number n with given number of sig. digits, \ trim trailing decimal point *) NumberForm[n, digits, NumberFormat -> (DisplayForm@ RowBox[Join[{StringTrim[#1, RegularExpression["\\.$"]]}, If[#3 != "", {"\[Times]", SuperscriptBox[#2, #3]}, {}]]] &)] Options[colorLegend] = {LabelStyle -> Black, Background -> LightGray, FrameStyle -> None, RoundingRadius -> 10, "ColorSwathes" -> None, "LeftLabel" -> False, "Digits" -> 3, Contours -> None, BoxFrame -> 0, "ColorBarFrameStyle" -> Black}; colorLegend[cFunc_, rawRange_, OptionsPattern[]] := Module[ {frameticks, tickPositions, nColor, nTick, range = N@Round[rawRange, 10^Round[Log10[Abs@First@Differences[{-1.5, .5}]]]/1000], colors, contours = OptionValue[Contours], colorBarLabelStyle = OptionValue[LabelStyle], colorBarFrameStyle = OptionValue["ColorBarFrameStyle"], outerFrameStyle = OptionValue[FrameStyle], colorSwathes = OptionValue["ColorSwathes"] }, (* Here we decide how many color gradations to diplay - either a given number, equally spaced, or "continuous," i.e. 256 steps: *) Switch[colorSwathes, _?NumericQ, nColor = colorSwathes; colors = (Range[nColor] - 1/2)/nColor; nTick = nColor, _, nColor = 256; colors = (Range[nColor] - 1)/(nColor - 1); nTick = 1 ]; (* Number of labels is nTick+1, unless changed by numerical Contours setting below: *) Switch[contours, _?NumericQ, tickPositions = (range[[ 1]] + (range[[-1]] - range[[1]]) (Range[contours + 1] - 1)/ contours); , List[Repeated[_?NumericQ]], tickPositions = contours, _, tickPositions = (range[[ 1]] + (range[[-1]] - range[[1]]) (Range[nTick + 1] - 1)/nTick); ]; frameticks = {If[TrueQ[OptionValue["LeftLabel"]], Reverse[#], #] &@{None, Function[{min, max}, {#, trimPoint[#, OptionValue["Digits"]], {0, .1}} & /@ tickPositions]}, {None, None}}; (* DisplayForm@ FrameBox replaces Framed because it allows additional BoxFrame option to specify THICKNESS of frame: *) DisplayForm@FrameBox[ (* Wrapped in Pane to allow unlimited resizing: *) Pane@Graphics[ Inset[ Graphics[ (* Create strip of colored, translated unit squares. If colorSwathes are selected, colors don't vary inside squares. Otherwise, colors vary linearly in each of 256 squares to get smooth gradient using VertexColors: *) MapIndexed[ { Translate[ Polygon[ {{0, 0}, {1, 0}, {1, 1}, {0, 1}}, VertexColors -> { cFunc[#[[1]]], cFunc[#[[1]]], cFunc[#[[2]]], cFunc[#[[2]]] } ], {0, #2[[1]] - 1} ] } &, Transpose[ If[ colorSwathes === None , {Most[colors], Rest[colors]} (* Offset top versus bottom colors of polygons to create linear VertexColors *) , {colors, colors} (* Top and bottom colors are same when uniform colorSwathes are desired *) ] ] ] (** End MapIndexed **), (* Options for inset Graphics: *) ImagePadding -> 0, PlotRangePadding -> 0, AspectRatio -> Full (* AspectRatio -> Full allows colored squares to strecth with resizing in the following. *) ], (* Options for Inset: *) {0, First[range]}, {0, 0}, {1, range[[-1]] - range[[1]]} (* this sets the size of the inset in the enclosing Graphics whose PlotRange is given next: *) ], (* Options for enclosing Graphics: *) PlotRange -> {{0, 1}, range[[{1, -1}]]}, Frame -> True, FrameTicks -> frameticks, FrameTicksStyle -> colorBarLabelStyle, FrameStyle -> colorBarFrameStyle, AspectRatio -> Full ], (* Options for FrameBox: *) Background -> OptionValue[Background], FrameStyle -> outerFrameStyle, RoundingRadius -> OptionValue[RoundingRadius], BoxFrame -> OptionValue[BoxFrame] ] ] at[position_, scale_: Automatic][obj_] := (* convenience function to position objects in Graphics *) Inset[obj, position, {Left, Bottom}, scale]; display[g_, opts : OptionsPattern[]] := Module[ {frameOptions = FilterRules[{opts}, Options[Graphics]]}, (* Same as Graphics, but with fixed PlotRange *) Graphics[ g, PlotRange -> {{0, 1}, {0, 1}}, Evaluate@Apply[Sequence, frameOptions] ] ] The functions at and display are adapted from another answer and serve only to make it easier to position the plot and its legend in a single Graphics . The trimPoint is adapted from here , and is intended to make the labels in the legend look nicer. To illustrate how it's used, take the above example plot for t : contour = display[{ plot // at[{0, 0}, .8], colorLegend[colors, range] // at[{0.85, .1}, Scaled[{.15, .5}]]}, AspectRatio -> .85] The variables plot , colors and range are the ones returned by reportColorRange above. The first argument of at is the desired position of the bottom left corner of the Graphics object preceding them. These positions are measured in a range from 0 to 1 across the horizontal and vertical dimensions of the output. The second argument of at is the scale at which the preceding graphic is to be placed in the output. It could be be specified as a single number (e.g, 0.8 above), as a tuple {width, height} or as a Scaled tuple (e.g., Scaled[{.15, .5}] above). The Scaled is useful only if you plan to include the final result in another plot, because then Scaled will be measured relative to that new size. I'm using that for the colorLegend , but it's not required. The colorLegend is very malleable, in that you can stretch or squeeze it arbitrarily using the second (scale) argument to at . To show some more customization, let's take different example: {plot, colors, range} = reportColorRange[ DensityPlot[1/(x^2 + y^2), {x, -5, 5}, {y, -5, 5}, ColorFunction -> ColorData["FallColors"], ClippingStyle -> Automatic] ]; density = display[{ plot // at[{0, 0}, 1], colorLegend[colors, range, "Digits" -> 2] // at[{0.8, .1}, Scaled[{.15, .5}]]}, AspectRatio -> 1] Here, I placed the legend inside the plot. That happened because the width for plot is specified by at to be 1 (corresponding to 100%), and the bottom right corner of the legend has been placed at position {0.8, .1} . The plot legend can sometimes become too ugly if you include too many digits of the height extrema. That's why I added an option "Digits" -> 2 to the function that specifies the number of significant digits to display in the labels. The other options accepted by colorLegend are "LeftLabel" (if True , make labels on the left of the color bar), LabelStyle (color etc. for the labels), Background (to change from LightGray to something else), FrameStyle and RoundingRadius . The central tool for combining plots and legends above is Inset . To show how much flexibility that approach gives you for positioning graphics (compared to GraphicsGrid , e.g.), I'll just combine the two examples from above with some arbitrary arrangement: display[{ Graphics[{Opacity[.5], Cyan, Disk[]}] // at[{0, 0}, 1], density // at[{0, 0}, .6], contour // at[{0.3, 0.4}, .7] }, AspectRatio -> 1, ImageSize -> 600, GridLines -> Automatic] Edit: illustrating additional options The following examples show some of the customizations for the color bar, such as frame color and thickness, and the style and orientation of the labels. A density plot with a legend that uses almost all of the available options: {densityPlot, densityColors, densityRange} = reportColorRange[ DensityPlot[ 1/(1 + Cos[x - 1]^20) - 1/(1 + Cos[(y - 1)^2 + x^2]^20), {x, -3, 3}, {y, -3, 3}, ColorFunction -> ColorData["Rainbow"], PlotPoints -> 80]]; With[{plotWidth = .85, aspectRatio = .9}, density = display[{ densityPlot // at[{0, 0}, plotWidth], colorLegend[ densityColors, densityRange, LabelStyle -> LightGray, FrameStyle -> Orange, "ColorBarFrameStyle" -> LightGray, Background -> Darker@Darker@Darker@Blue, "ColorSwathes" -> None, Contours -> 10, RoundingRadius -> 0, BoxFrame -> 3, "Digits" -> 2 ] // at[{plotWidth, 0}, {1 - plotWidth, plotWidth/aspectRatio} ]}, AspectRatio -> aspectRatio, ImageSize -> 400] ] The actual plot is contained in the variable densityPlot , and it is combined with the legend as in the previous examples. You could try to play with the settings to see what the options do. I also added some extra calculations to determine the positions of the plot and legend above. The goal was to give two parameters: plotWidth and aspectRatio , and determine how to fit the plot and legend into the resulting image so as to use up all available space. The plotWidth is specified as a fraction of the horizontal plot width. Since by default the aspect ratio of the plot ( densityPlot ) is fixed, there will be wasted space or clipping if we play around with the aspectRatio variable which applies to the entire image including the legend. For example, try setting aspectRatio -> 1 or .5 . This shows that there may still be some manual adjustment required to find the best positioning of the legend. Keep in mind that the position and size of the legend can always be editd using the interactive tools as well, see the documentation on Resizing, Cropping, and Adding Margins to Graphics . Next, a test with a different kind of plot ( SmoothDensityHistogram ) that also uses a color ramp: data = RandomReal[1, {100, 2}]; {sDensityPlot, sDensityColors, sDensityRange} = reportColorRange[ SmoothDensityHistogram[data, 0.015, "PDF", ColorFunction -> "Rainbow", Mesh -> 0, PlotRange -> {{0, 1}, {0, 1}}]]; With[{labelWidth = .15, labelHeight = .5, aspectRatio = .8}, density = display[{ sDensityPlot // at[{1 - aspectRatio, 0}, {aspectRatio, 1}], colorLegend[sDensityColors, sDensityRange, Background -> None, "LeftLabel" -> True ] // at[{0, 0}, {labelWidth, labelHeight} ]}, AspectRatio -> aspectRatio, ImageSize -> 400] ] Here, I also tried a different way of calculating the positioning of the legend: I assumed the width and height of the legend are given as fractions of the image dimensions in labelWidth and labelHeight , and decided to align the legend with the left side, the plot with the right side of the image. So now you will see that the alignments behave differently when you change the value of aspectRatio . Try making it smaller, e.g., aspectRatio = .6 , and you'l see extra white space between the legend and plot. Also try increasing labelHeight to 1 . Finally, here is an example with ContourPlot where I would like to show a legend that has color bands instead of gradients. This goes back to the first example of the post (see above): t = Flatten[ Table[{x, y, 2/((x - 1)^2 + y^2)}, {x, -5, 5, .3}, {y, -5, 5, .3}], 1]; {contourPlot, contourColors, contourRange} = reportColorRange[ListContourPlot[t]]; Block[{ labelWidth = .15, labelHeight = 1, aspectRatio = .8, numberOfContours = Length[Cases[contourPlot, Tooltip[__], Infinity]], plotRange}, plotRange = FindDivisions[Round[contourRange, .1], numberOfContours]; numberOfContours = Length[plotRange] - 1; display[{contourPlot // at[{0, 0}, aspectRatio], colorLegend[contourColors, plotRange[[{1, -1}]], LabelStyle -> Darker[Brown], Background -> None, "ColorSwathes" -> numberOfContours ] // at[{1 - labelWidth, 0}, {labelWidth, 1} ]}, AspectRatio -> aspectRatio, ImageSize -> 400] ] As in the first example, note that the white region in the middle isn't part of the color range - it's an exclusion due to the singularity in the data. That's why the color legend doesn't have white at the top. The important option here is "ColorSwathes" which says how many color bands there are. To figure out that number isn't completely straightforward, though. That's why I don't have an automated way of doing it, except what I added in the Block above. The idea is that numberOfContours can be obtained by counting the number of Tooltip occurrences, assuming that the ContourPlot follows the default setting which wraps each contour in Tooltip . This would be easier if the contours could be extracted using AbsoluteOptions , but that's unfortunateley not the case. I still use the results of reportColorRange to determine what the correct labels for the legend should be. But here, too, there is some work required because with the Automatic setting for the contours in ContourPlot , the values will be at "nice" divisions that don't have to be rationally related to the minimum or maximum function values. I used FindDivisions to guess what the contour divisions should be. Edit The last example with a banded color legend was also the topic of another question where I added a different variant of colorLegend . That definition can be added to the one in this answer without conflict. The linked version simply has a third argument n corresponding to the number of discrete tick marks in the legend. This may sometimes be more convenient that the "ColorSwathes" option.
{ "source": [ "https://mathematica.stackexchange.com/questions/6236", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/54/" ] }
6,242
Initially I was interested in renderring a 3D analog of a blurred disk like this DensityPlot[1 - HeavisideLambda[(x^2 + y^2)/8]/2, {x, -4, 4}, {y, -4, 4}, FrameTicks -> False, ColorFunctionScaling -> False, ColorFunction -> "SunsetColors", PlotRange -> {0, 1}, PlotPoints -> 50] The only idea that came to my mind was playing with Opacity , which gives hardly an impressive result: Graphics3D[{Orange}~Join~ Table[{Opacity[i], Sphere[{0, 0, 0}, 1 - i]}, {i, 0.1, 1, 0.1}] // Flatten] So, 1) is it possible to get "true" blurred ball and 2) how to extrapolate this idea to other 3D objects?
UPDATE: latest Mathematica 9 functionality This is very easy now with latest Mathematica 9 functionality. Just use Image3D or Raster3D functions: data = Developer`ToPackedArray[With[{step = .03}, ParallelTable[Exp[-(i^2 + j^2 + k^2)^4/.99], {k, -1.2, 1.2, step}, {i, -1.2, 1.2, step}, {j, -1.2, 1.2, step}]]]; Image3D[data, ColorFunction -> #, Axes -> True, ImageSize -> 400] & /@ {Automatic, "XRay"} -------- OLDER VERSIONS ---------------- METHOD 1 - volumetric rendering - from scratch I will use ideas from this post by Yu-Sung. First create data for 3D texture: data = Developer`ToPackedArray[ With[{step = .05}, ParallelTable[{1, 0, 0, Exp[-(i^2 + j^2 + k^2)^4/.8]}, {k, -1, 1, step}, {i, -1, 1, step}, {j, -1, 1, step}]]]; Next create many polygons with applied texture: Graphics3D[{ EdgeForm[], Opacity[.4],(*Overall transparency of the textured polygons*) Texture[data],(*Set volumetric texture*) With[{pts = Table[{{0, 0, z}, {1, 0, z}, {1, 1, z}, {0, 1, z}}, {z, 0, 1, .05}]}, Polygon[pts, VertexTextureCoordinates -> pts]]}, PlotRange -> {{0, 1}, {0, 1}, {0, 1}}, Lighting -> "Neutral", Background -> Black, RotationAction -> "Clip", SphericalRegion -> True, BoxStyle -> Directive[Opacity[.2], White], ImageSize -> 4 {100, 100}, BoxRatios -> {1, 1, 1}, Axes -> False, BaseStyle -> {RenderingOptions -> {"DepthPeelingLayers" -> 100}}] Below are the views in different directions. It's pretty fast: METHOD 2 - volumetric rendering - CUDA - on GPU from built-in interface Again, I will use ideas from this post by Yu-Sung. We will use built-in interface CUDAVolumetricRender to render our 3D fading out texture on GPU. Make sure you have latest CUDA paclet - read this tutorial . Create data which are good for 3D texture understood by CUDAVolumetricRender data = Developer`ToPackedArray[ With[{step = .05}, Table[Round[255 Exp[-(i^2 + j^2 + k^2)^1/.8]], {k, -1, 1, step}, {i, -1, 1, step}, {j, -1, 1, step}]]]; Load CUDA package and follow Yu-Sung CUDA cooking recipes as shortly given below (see details in this post ) << CUDALink` Clear[prepareCUDAVolumeData]; prepareCUDAVolumeData::arg = "The argument should be an integer array of depth 3."; prepareCUDAVolumeData[array_] /; ArrayQ[array, 3, IntegerQ] := Module[{x, y, z}, {x, y, z} = Dimensions[array]; Developer`ToPackedArray[ Partition[#, x] & /@ Partition[Flatten[array], x*z]]]; prepareCUDAVolumeData[___] /; (Message[prepareCUDAVolumeData::arg]; False) := Null; CUDAVolumetricRender[prepareCUDAVolumeData[data]] After playing with options of the interface (see control positions) and the usual zooming of Mathematica 3D graphics you can get this beautiful view: METHOD 3 - opaque spheres --------------------------------------------- This is not ideal, but just a demonstration of a concept. We can approximate a complex volume opacity by filling the volume with small transparent spheres. The more spheres we have and the smaller and closer they are the better. In the example below I even make spheres to overlap to mask the gaps between them. Computation and rendering of 64000 transparent spheres is not short and it is tedious to rotate that 3D object. Due to cubic grid only certain viewing direction result in the image below (I set that with ViewPoint option). I suspect that cubic close packed (face-centered cubic fcc) and hexagonal close-packed (hcp) will show more uniform viewing from various perspectives. I may add the code for those later. Block[{r = 20}, Graphics3D[ Table[{Red, Opacity[7 N@Exp[-(i^2 + j^2 + k^2)/(r/2)^2]], Sphere[{i, j, k}, 3]}, {i, -r, r}, {j, -r, r}, {k, -r, r}], Boxed -> False, Axes -> False, Lighting -> "Neutral", ViewPoint -> {0, 0, 1}]]
{ "source": [ "https://mathematica.stackexchange.com/questions/6242", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/219/" ] }
6,247
Note: This question was asked when Mathematica 8 was latest release. Version 9 has built-in support for volume rendering through Image3D . There's an example on wolfram.com showing some medical data rendered in 3D. Unfortunately there's no code, only an animation. Note that the data is shown as a solid three-dimensional body, not only 2D slices of it like in the example on the doc page of Texture . Given a 3D texture, how can such a visualization of a solid 3D body be made using Mathematica? You will find the volumetric data on the doc page of Texture, under Applications -> Volume Rendering. I notice there's something included with CUDALink . Unfortunately I can't try it (I don't have the hardware), but it looks quite different from the image I linked to above, so I think there must be an independent way to produce the image above. [With Sjoerd's hardware (it's pretty cool, movements are totally smooth):] Link to the MathGroup version of this post.
Solution 1: Using 3D Texture with Polygons The idea is to use Polygon with 3D texture supported by Texture , but it requires a bit of undocumented hack to make it smooth. The original data set is from Stanford Graphics Group website . The dataset that has been used is CThead, 8-bit tiffs ( download ). Before proceed, make sure that you have a plenty of memory (~500MB would be enough). Also, if you don't have a good graphics card, turning off 3D antialiasing (through "Preference" menu) will be helpful. Step 1 Download slices into Mathematica (it takes a long time...). filename = "cthead-8bit.tar.gz"; (* Appropriate path to the downloaded file *) slices = Import[filename, #] & /@ Import[filename]; The images should look like this: Step 2 Let's apply some colors and transparency. We apply color function using Colorize , then add alpha channel based on binarized image using ColorCombine . Don't forget to specify the color space "RGB" (otherwise, the last channel will not be interpreted as opacity). Since it is a lot of slices, we will use ParallelMap . I am reversing the result to match the orientation. colored = Reverse[ParallelMap[ With[{img = #}, ColorCombine[{ Colorize[img, ColorFunction -> "SunsetColors"], Binarize[img] }, "RGB"]] &, slices]]; The result will look like this: We will combine them and pack them so that it will make a nice volumetric color dataset. Again, notice that option DataReversed is used to reverse the orientation. data = Developer`ToPackedArray[Map[ImageData[#, DataReversed -> True] &, colored]]; Step 3 Basically, we put a lot of polygons with textures coming from this volumetric color dataset. But to make it work rather smooth, you need to use undocumented option BaseStyle -> {RenderingOptions -> {"DepthPeelingLayers" -> n}} (n being some reasonable number). I won't go deep into how this option works, I will just say that this sets limit on rendering of translucent polygons. Here is the main code to display it: (* All are in 0-1 coordinates. *) (* top is z-value for x-y cutaway. *) (* right is x value for y-z cutaway. *) (* step defines how many polygon slices will be inserted. Smaller -> more *) With[{top = 0.4, right = 0.4, rpad = -.2, step = 0.01}, Graphics3D[{ EdgeForm[], Opacity[.4], (* Overall transparency of the textured polygons *) Texture[data], (* Set volumetric texture *) (* Bottom part up until the variable top *) With[{pts = Table[{{0, 0, z}, {1, 0, z}, {1, 1, z}, {0, 1, z}}, {z, 0, top, step}]}, Polygon[pts, VertexTextureCoordinates -> pts] ], (* Top part from top to 1, but from 0 to right in x direction *) With[{pts = Table[{{x, 0, top}, {x, 1, top}, {x, 1, 1}, {x, 0, 1}}, {x, 0, right, step}]}, Polygon[pts, VertexTextureCoordinates -> pts] ], (* Cutaway decoration *) EdgeForm[Directive[Opacity[.6, RGBColor[1., .8, .1]], Thick]], FaceForm[], Polygon[{{right, 0, top}, {1 + rpad, 0, top}, {1 + rpad, 1, top}, {right, 1, top}, {right, 1, 1}, {right, 0, 1}}] }, PlotRange -> {{0, 1 + rpad}, {0, 1}, {0, 1}}, Lighting -> "Neutral", Background -> Black, RotationAction -> "Clip", SphericalRegion -> True, BoxStyle -> Directive[Opacity[.2], White], ImageSize -> 4 {100, 100}, (* Rendering option for smooth volumetric rendering *) BaseStyle -> {RenderingOptions -> {"DepthPeelingLayers" -> 100}}, BoxRatios -> {1 + rpad, 1, .9}] ] Here is the result: Warning: Be very careful of decreasing step or increasing DepthPeelingLayers and ImageSize . It will crash the Front End... Solution 2: Using CUDAVolumetricRender It is a limited solution for the people who has CUDA capable graphics cards. Essentially, it will call CUDAVolumetricRender function which is a part of CUDALink . Step 0 We need to load the CUDALink package. <<CUDALink` The following line will make it sure that you get the latest CUDA paclet. CUDAResourcesInstall[Update -> True] It takes a long time to download full paclet, so if you are sure that your CUDA distribution is up to date ( CUDAResourcesInstall[] returns 8.0.4.2, as of 5/31/2012), then you can skip this step. Step 1 Download slices into Mathematica (the same as above). filename = "cthead-8bit.tar.gz"; (* Appropriate path to the downloaded file *) slices = Import[filename, #] & /@ Import[filename]; Step 2 Create a volume data suitable for the CUDAVolumetricRender . First, the data should be a packed integer array with depth 3, each element should range from 0 to 255 (0 being background). Since original data is already in 0-255 range (8-bit TIFF), you can use ImageData[..., Automatic] to take original values out. Otherwise, you can use ImageData[..., "Byte"] to enforce it to be in byte range. data = Developer`ToPackedArray[Map[ImageData[#, Automatic] &, slices]]; Here is a slight problem. Apparently there is a bug. To render $d \times h \times w$ voxel data, you need to partition it again, so that the data would have $h \times w \times d$ dimension. We are not talking of transposing it, instead, literally we just need to change dimension, without touching data order. It is hard to explain and no need to understand, so I will just provide a conversion function here: Clear[prepareCUDAVolumeData]; prepareCUDAVolumeData::arg = "The argument should be an integer array of depth 3."; prepareCUDAVolumeData[array_] /; ArrayQ[array, 3, IntegerQ] := Module[{x, y, z}, {x, y, z} = Dimensions[array]; Developer`ToPackedArray[ Partition[#, x] & /@ Partition[Flatten[array], x*z]]]; prepareCUDAVolumeData[___] /; (Message[prepareCUDAVolumeData::arg]; False) := Null; Step 3 Now, we are ready. Let's try this: CUDAVolumetricRender[prepareCUDAVolumeData[data]] Here is the result (with some parameter tweak): The problem with this approach is that you don't have much flexibility except what is given by the interface. Note: The volume rendering support in Mathematica 8 is quite limited (without CUDALink ). Technically, it is not really volumetric rendering in traditional sense. A proper volumetric rendering requires a transfer function which converts accumulation of density values into certain color per each pixel. Here, we are mimicking the effect by using false coloring and alpha blending. The CUDALink volume rendering is a real deal, but you don't really need CUDA as long as graphics cards supports shader language (which is mostly true nowadays). Note 2: You can expect much improved (and proper) volumetric support in the future... ;)
{ "source": [ "https://mathematica.stackexchange.com/questions/6247", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/12/" ] }
6,338
The question is simple, but I will elaborate on the background as well for those interested in the idea: How to define a new operator with specified precedence value? Background Mathematica was design to facilitate functional programming. I definitely find it easy to write code continuously: the output of a function becomes immediately the input of the next function. One thing I really miss though is a low-precedence prefix operator that applies to all things following it (up to e.g. CompoundExpression ( ; )). Consider the following example: Log@N@Accumulate@# & /@ Partition[Range@300, 100] // Flatten // ListPlot It partitions a dataset to multiple subparts, threads functions to each subpart, and then plots the joined datasets. I write such code a lot, as I find it easy that it can be written from the inside to the outside, from argument to head (right to left). The problem is that the extension of the above one might come up with intuitively does not behave like that: ListPlot@Flatten@ Log@N@Accumulate@# & /@ Partition[Range@300, 100] Operator precedences cause ListPlot@Flatten to be applied to each subpart of the partitioned list instead of the list as a whole. Now since I successively build up my calculations from the argument to the wrapping functions, I want to use a prefix operator. My concerns are: One can use matchfix forms like f@(...) or f[...] to wrap around the Map , though it requires the matching of parentheses, which can be a PITA when multiple such functions are applied with prefix notation. Using postfix // both breaks my cognitive process of writing from right-to-left, and (more importantly) breaks the principle of head-precedes-argument, which is very emphasized in Mathematica (and in $\lambda$-calculus). The operator must be a free symbol. Modifying the built in @ operator should be avoided! Also it must be simple enough to be used effectively. Postfix apply // is 2 keystrokes, while for example $\oplus$ requires 4 ( esc c + esc ), making it worse than hitting end / / . So, how to define a new operator, e.g. \\ that has low precedence (perhaps 70) so that this: ListPlot \\ Flatten \\ Log@N@Accumulate@# & /@ Partition[Range@300, 100] equals this: ListPlot[Flatten[Log@N@Accumulate@# & /@ Partition[Range@300, 100]]] Frankly, I just started to wonder why this operator is not present at all in Mathematica , though WRI always emphasizes functional programming as a native style of the language. I know I can apply Log or N to the partitioned list as a whole. I only used them here for demonstrating my case.
As explained by Michael Pilat you cannot create your own compound operators* with custom precedence. (You could conceivably write your own parser as Leonid has worked on, or attempt to coerce the Box form with CellEvaluationFunction .) You can however use an existing operator with the desired precedence. Looking at the table Colon appears to be a good choice. The operator is entered with Esc : Esc . Example: SetAttributes[Colon, HoldAll] Colon[f__, x_] := Composition[f][Unevaluated@x] ListPlot \[Colon] Flatten \[Colon] Log@N@Accumulate@# & /@ Partition[Range@300, 100] Which appears as, and produces: Since raw colon is already used for Pattern this may be confusing. However, if you are willing to edit your UnicodeFontMapping.tr file you can assign any symbol you like. Here I mapped \[Colon] to Klingon A: This was done by changing the line starting with 0x2236 in UnicodeFontMapping.tr . * Rojo demonstrated that one can create two-dimensional compound operators, meaning use of SubscriptBox , SuperscriptBox , OverscriptBox , etc. See: Is it possible to define custom compound assignment operators like ⊕= similar to built-ins +=, *= etc?
{ "source": [ "https://mathematica.stackexchange.com/questions/6338", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/89/" ] }
6,346
I was always assuming that the only difference between Set ( = ) and SetDelayed ( := ) is that SetDelayed holds the right argument, so that a := b is effectively the same as a = Unevaluated[b] . Especially I assumed that after the assignment is done, there's no further difference for variables or functions assigned with Set and variables assigned with SetDelayed . Looking at OwnValues resp. DownValues seems to support that assumption. However I now noticed that when writing ?a , Mathematica displays the type of assignment used for the definition, which means it has to store it somewhere. And I somehow doubt that it only stores it in order to show it with ? . Therefore my question is: Is there any difference in the behaviour of values assigned with = and with := (apart from the different output of ? ), assuming the actual assigned expression is the same (i,e, OwnValues / DownValues have the same value after both assignments)?
Yes, at least in one place. x = {1, 2, 3} x[[2]] = 8; All right there, but y := {1, 2, 3} y[[2]] = 8 gives Set::noval: Symbol y in part assignment does not have an immediate value Credit to this old comment by Leonid . Also note the point on memory usage: [...] I'd guess that delayed definitions may use some intermediate internal variables, while immediate ones point straight to the memory where the data is stored.
{ "source": [ "https://mathematica.stackexchange.com/questions/6346", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/129/" ] }
6,355
You can setup "UsefulFunction[a, b]" to use custom infix notation "a ↔ b" as follows: Needs["Notation`"]; AddInputAlias["4" -> ParsedBoxWrapper["↔"]]; InfixNotation[ParsedBoxWrapper["↔"], FlatJoin]; But using a unicode character that does not have a mathematica definition (e.g. "\[name]") such as ":27d7" gives you an error: Now the syntax highlighting is broken, and that is really my question: how can you tell mathematica to correctly syntax highlight new unicode infix operators? (Note: the messages can by avoided by adding internal information on the character as follows: Notation`Private`internalCharacterInformation["⋗"] = {"0x2295", "Infix", "450", "None", "3", "3", "MyOp"}; InfixNotation[ParsedBoxWrapper["⋗"], FlatJoin] Edit: I'm now pretty sure that the answer will involve editing /Applications/Mathematica.app/SystemFiles/FrontEnd/TextResources/UnicodeCharacters.tr and adding something like 0x22D7 \[FlatJoin] ( $fj$ $&FlatJoin;$ $\oplus$ ) Infix 320 None 4 4 and then using the Notations package...
You can get the syntax highlighting that you desire by modifying your UnicodeCharacters.tr file (path given by System`Dump`unicodeCharactersTR ), though I don't know how advisable this practice is. For example, adding: 0x20B0 \[PennyOp] ($penny$) Infix 155 None 5 5 I can use Esc penny Esc to enter: I am not aware of documentation of the format of this file but as best I can tell the columns are: the Unicode address in hex the FullForm String representation input aliases separated by tabs the use or type of the symbol parsing precedence Left , Right or None -- I assume an associativity control left whitespace padding to place around the character (in StandardForm) right whitespace padding Completing the operator Additional code is required to turn such a character into a valid operator. Please see these additional questions for the rest of the story: How is + as an infix operator associated with Plus? How to define a number of infix operators with predefined relative precedences
{ "source": [ "https://mathematica.stackexchange.com/questions/6355", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/403/" ] }
6,421
Coming from Maple I do not understand how the precision for numerical computations in Mathematica is specified. I understand that there are various options to commands such as WorkingPrecision and PrecisionGoal . But I would like to use the same precision (above machine precision) for a number of computations including matrix operations and the FindRoot command outside and inside of routines. Also I would like to specify the precision of the output.
How do I tell mathematica that all numbers e.g. 1.5 are actually 20 Digits precision? SetPrecision on all numbers or add the `20 everywhere? You could force this with $PreRead . This naive definition is likely inefficient and probably breaks a number of corner cases I have not considered, but here is a rough demonstration: $PreRead = (# /. s_String /; StringMatchQ[s, NumberString] && Precision@ToExpression@s == MachinePrecision :> s <> "`20." &); 3/1.5 + Pi/7 Precision[%] 2.4487989505128276055 20.0879 As Alexey notes this breaks if the machine number string already has a "NumberMark" after it e.g. 1.23` . One could use a more precise string replacement to avoid this. A different approach is to process at the expression rather than box level, though this simple first attempt probably fails in some cases as well: $Pre = Function[Null, Unevaluated[#] /. r_Real?MachineNumberQ :> RuleCondition@SetPrecision[r, 25], HoldAllComplete] Now: MachineNumberQ[2.2] ToString[3.14] False "3.140000000000000124344979"
{ "source": [ "https://mathematica.stackexchange.com/questions/6421", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1353/" ] }
6,502
Is there any way to have the functions from a mathematica file be loaded on startup? For example, in this excellent answer, Jens helps me out and gives me some functions for creating legends for plots. Instead of loading a file with those functions in it every time I load mathematica, can I instead put all the functions in a file and have them load every time I load mathematica?
There are several configuration files that you can use to load functionality at startup. They have the form ($BaseDirectory | $UserBaseDirectory)/(Kernel | FrontEnd)/init.m where $BaseDirectory is for every user on the system and $UserBaseDirectory is for you along and Kernel or FrontEnd specifies what you are configuring. In fact, a lot of the settings under the Preferences menu automatically write to $UserBaseDirectory/FrontEnd/init.m . In your case, you are looking to add to $UserBaseDirctory/Kernel/init.m .
{ "source": [ "https://mathematica.stackexchange.com/questions/6502", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/54/" ] }
6,511
As part of a calculation I need to do something like this Evaluate[{aaa, bbb, ccc}[[ index]]] = {1, 2, 3, 4, 5} so if index is 1 then {1, 2, 3, 4, 5} will be stored into the variable aaa . But if I re-evaluate this it does not work because aaa is now a list and not a variable. I tried various options with Hold[] etc but did not manage to solve this.
This is a fairly natural question and I feel it is worthy of attention. I am going to answer in two parts. First, I am going to show a method that is more appropriate for Mathematica programming and which I recommend you use instead. Then I will show how to force the action you are attempting. Better Alternatives The common way to accomplish programmatically selected assignments is to use indexed variables . This allows you to assemble a "variable" from inert parts. For example, one would use a single variable var and simply make assignments ( SeedRandom[1] for a consistent result): SeedRandom[1] Do[ var[i] = RandomInteger[9], {i, {1, 2, 3, 2, 3, 1, 3}} ] Or recall them: var /@ {1, 2, 3} {0, 7, 8} If you desire a certain name be attached to a value you can index with Strings. names = {"aaa", "bbb", "ccc"}; i = 1; var[ names[[i]] ] = Sqrt[2]; (* dummy first assignment *) var[ names[[i]] ] = {1, 2, 3, 4, 5}; var["aaa"] {1, 2, 3, 4, 5} In passing, depending on your application you may find Rules applicable. Associations Mathematica 10 introduced Associations which are like self-contained "indexed variables." Use is similar but you need to start with an (optionally empty) Association before you make assignments. Example: SeedRandom[1] asc = <||>; Do[asc[i] = RandomInteger[9], {i, {1, 2, 3, 2, 3, 1, 3}}] asc <|1 -> 0, 2 -> 7, 3 -> 8|> Values may be recalled using Map , Replace , or Lookup ; for a comparison see: Is there a faster way to Map an Association? For some ideas of when and why one might use associations over "indexed variables" see: How to make use of Associations? Forcing the behavior Suppose you need the behavior you asked for to keep a large program working without extensive modification. Method #1 This works because Part preserves the head of the expression , here Unevaluated . Ignore the syntax highlighting in Unevaluated : this is a nonstandard but safe use. This could easily use the same syntax as Method #2 : assign[symbols_, idx_, val_] := ClearAll[aaa, bbb, ccc, assign] assign[idx_, val_] := (# = val) & @ symbols[[1, {idx}]] symbols = Hold @ Unevaluated[aaa, bbb, ccc]; assign[1, "dummy"]; assign[1, Range@5]; aaa {1, 2, 3, 4, 5} Method #2 This uses the injector pattern in preference to Unevaluated . ClearAll[aaa, bbb, ccc, f1, assign] assign[symbols_, idx_, val_] := symbols[[{idx}]] /. _[x_] :> (x = val) symbols = Hold[aaa, bbb, ccc]; assign[symbols, 1, "dummy"]; assign[symbols, 1, Range@5]; aaa {1, 2, 3, 4, 5}
{ "source": [ "https://mathematica.stackexchange.com/questions/6511", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1143/" ] }
6,588
I have a function that takes two inputs and processes them for a single output. What I need is one that can take a varying number of inputs. and process them to a single output. Is this possible in Mathematica? DatasetAverage[inputData_, inputData2_] := Block[{dataAvg, v, w}, v = Length[inputData]; w = Length[inputData2]; If [v != w, Print["DatasetAverage: Data sample sizes do not match"]]; dataAvg = Table[Mean[{inputData[[i]], inputData2[[i]]}], {i, 1, Length[inputData2]}] ]
Yes, for both named patterns and pure functions. Pure functions You can see that inherently they accept multiple arguments but discard those that are not used: {#} &[1, 2, 3] (* out: {1} *) The object ## , ( SlotSequence ), represents all arguments wrapped in Sequence , e.g. Sequence[1, 2, 3] . (Internally it doesn't use Sequence but it behaves similarly in most places.) {##} &[1, 2, 3] (* out: {1, 2, 3} *) You can combine # and ## , including their numbered forms: {"first" -> #, "rest" -> {##2}, "all" -> {##}} &[1, 2, 3] {"first" -> 1, "rest" -> {2, 3}, "all" -> {1, 2, 3}} Named patterns Using Blank* : _ ( Blank ) __ ( BlankSequence ) ___ ( BlankNullSequence ): f[a_, b__] := {"first" -> a, "rest" -> {b}} f[1, 2, 3] (* out: {"first" -> 1, "rest" -> {2, 3}} *) __ requires an argument to be present while ___ does not: f[1] (* out: f[1] *) g[a_, b___] := {"first" -> a, "rest" -> {b}} g[1] (* out: {"first" -> 1, "rest" -> {}} *) Multiple variable length named patterns can be given and will by default be matched shortest first: h[a_, b__, c__] := {"a" -> a, "b" -> {b}, "c" -> {c}} h[1, 2, 3, 4, 5] (* out: {"a" -> 1, "b" -> {2}, "c" -> {3, 4, 5}} *) This can be controlled with Shortest and Longest : i[a_, Longest[b__], c__] := {"a" -> a, "b" -> {b}, "c" -> {c}} i[1, 2, 3, 4, 5] (* out: {"a" -> 1, "b" -> {2, 3, 4}, "c" -> {5}} *) See this answer for an advanced use of these functions. The Blank* functions are not the only way to create a variable length pattern. You can also use Repeated ( .. ) or RepeatedNull ( ... ): j[x : _Real ..] := {x} j[1.1, 1.2, 1.3] (* out: {1.1, 1.2, 1.3} *) These methods can be used in powerful ways such as destructuring . Optional arguments In addition to the variable length methods above one can make use of Optional parameters with or without the use of Default values. A basic example: k[a_, b_: 3, c_: 5] := {a, b, c} k[1] k[1, 2] k[1, 2, 3] {1, 3, 5} {1, 2, 5} {1, 2, 3} In the example above there are two optional parameters. By default they are filled in sequential order, meaning that in k[1, 2] the 2 is bound to b . This also can be controlled with Shortest and Longest as noted in the section above. In a limited way optional arguments can also be used for pure functions: Is there any way to define pure functions with optional arguments? Default can be used to set the default values for a given function, rather than specifying them as part of each function definition, but it must be used before they are defined, and it cannot be used to change them for existing definitions. ( Why does Default behave like this? ) Default[m, 1] = 1; Default[m, 2] = 3; Default[m, 3] = 5; m[a_., b_., c_.] := {a, b, c} m[] m[2] m[2, 4] m[2, 4, 6] {1, 3, 5} {2, 3, 5} {2, 4, 5} {2, 4, 6} Also see: f[arg1, arg2,...,argN] vs. f[{arg1, arg2,...,argN}] A function that accepts a pair or a list of pairs Related Q&A's of a more advanced nature: How can I create a function with "positional" or "named" optional arguments? How to Combine Pattern Constraints and Default Values for Function Arguments Can I make a default for an optional argument the value of another argument? Function argument to default under certain condition How can I define a Listable function only apply to a vector? A question about two ways to use Default Function with zero or one arguments
{ "source": [ "https://mathematica.stackexchange.com/questions/6588", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/686/" ] }
6,589
I recently learned that we can use Print as a monitoring tool. My favorite is Ted Ersek's example h[f1[a1], f2[e][a2]] /. (a_ /; Print[a] :> 0) which reveals the order in which ReplaceAll goes through parts of an expression. Clearly this is a very useful trick. On page 41 of his book , David Wagner gave the example FindRoot[Print[x]; Sin[x] - Cos[x], {x, .5}] which prints the sequence of iterates generated by FindRoot along the way. That code no longer works on Mathematica version 8: In[22]:= FindRoot[Print[x]; Sin[x] - Cos[x], {x, .5}] During evaluation of In[22]:= x Out[22]= {x -> 0.785398} At first I thought this is related to the fact that we now have the EvaluationMonitor option, and FindRoot somehow weeds out superfluous subexpressions like Print . Now I know this is probably false because Plot[Print[x]; Sin[x], {x, Pi/4, Pi/2}] still lists all the points considered during its evaluation. Why does FindRoot ignore Print ?
Try the Evaluated -> False option: FindRoot[Print[x]; Sin[x] - Cos[x], {x, .5}, Evaluated -> False] During evaluation of In[3]:= 0.5 During evaluation of In[3]:= 0.5 During evaluation of In[3]:= 0.5 During evaluation of In[3]:= 0.793408 During evaluation of In[3]:= 0.793408 During evaluation of In[3]:= 0.793408 During evaluation of In[3]:= 0.785398 During evaluation of In[3]:= 0.785398 During evaluation of In[3]:= 0.785398 During evaluation of In[3]:= 0.785398 During evaluation of In[3]:= 0.785398 During evaluation of In[3]:= 0.785398 Out[3]= {x -> 0.785398} As to the Plot , try Plot[Print[x]; Sin[x], {x, Pi/4, Pi/2}, Evaluated -> True]; During evaluation of In[5]:= x As you see, the behavior is exactly the same as it is for FindRoot by default. The difference in default behavior can be explained by default values of the Evaluated option: Options[#, Evaluated] & /@ {Plot, FindRoot} {{Evaluated -> Automatic}, {Evaluated -> True}} It seems that the Automatic value is equivalent to False in this case. Another approach As Albert Retey mentioned in the comment, the "standard" (and documented) way to monitor evaluations is to define objective function as black-box function by restricting its argument to numerical values only: In[1]:= f[x_?NumericQ] := (Print[x]; Sin[x] - Cos[x]) FindRoot[f[x], {x, .5}] During evaluation of In[1]:= 0.5 During evaluation of In[1]:= 0.5 During evaluation of In[1]:= 0.5 During evaluation of In[1]:= 0.793408 During evaluation of In[1]:= 0.793408 During evaluation of In[1]:= 0.793408 During evaluation of In[1]:= 0.785398 During evaluation of In[1]:= 0.785398 During evaluation of In[1]:= 0.785398 During evaluation of In[1]:= 0.785398 During evaluation of In[1]:= 0.785398 During evaluation of In[1]:= 0.785398 Out[2]= {x -> 0.785398} Additional comparisons Here I switch off autocompilation for not loading the corresponding package (it affects output of Trace ): In[1]:= ClearAll[f, x]; f[x_] := x - 1; Trace[FindRoot[f[x], {x, .5}, Evaluated -> False, Compiled -> False], TraceInternal -> True] // LeafCount Trace[FindRoot[f[x], {x, .5}, Evaluated -> True, Compiled -> False], TraceInternal -> True] // LeafCount Out[2]= 181 Out[3]= 111 In[4]:= ClearAll[f, x]; f[x_?NumericQ] := x - 1; Trace[FindRoot[f[x], {x, .5}, Evaluated -> False, Compiled -> False], TraceInternal -> True] // LeafCount Trace[FindRoot[f[x], {x, .5}, Evaluated -> True, Compiled -> False], TraceInternal -> True] // LeafCount Out[5]= 217 Out[6]= 261 One can see that in simple cases the option Evaluated -> True reduces number of evaluations but in more complicated cases (black-box function) it cannot help.
{ "source": [ "https://mathematica.stackexchange.com/questions/6589", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/281/" ] }
6,635
I'm trying to use baseform to convert numbers in base 10 to base n, how can I make the convertion between, say base 2 to base n? Baseform seems to always think that the base in expr BaseForm[Expr, n] is always 10.
It should be possible to use notation of the form base^^number inside the BaseForm expression like this: BaseForm[2^^10101,14] There are some similar examples under Properties and Relations in the documentation for BaseForm .
{ "source": [ "https://mathematica.stackexchange.com/questions/6635", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/603/" ] }
6,669
I understand Mathematica can't assign the results of a Solve to the unknowns because there may be more than 1 solution. How can I assign the 4 values of following result to variables? Solve[y^2 == 13 x + 17 && y == 193 x + 29, {x, y}]
You can do this : s = Solve[y^2 == 13 x + 17 && y == 193 x + 29, {x, y}]; xx = s[[All, 1, 2]]; yy = s[[All, 2, 2]]; Now you can access solutions, this way xx[[1]] , yy[[2]] . If you prefer to collect solutions in Array , there is another way : X = Array[ x, {Length@s}]; Y = Array[ y, {Length@s}]; x[k_] /; MemberQ[ Range[ Length @ s], k] := s[[k, 1, 2]] y[k_] /; MemberQ[ Range[ Length @ s], k] := s[[k, 2, 2]] now X is equivalent to s[[All, 1, 2]] , while Y to s[[All, 2, 2]] , e.g. : X[[1]] == x[1] Y == s[[All, 2, 2]] True True You do not have to use or even to define X and Y arrays, e.g. {x[1], y[1]} {(-11181 - Sqrt[2242057])/74498, 1/386 (13 - Sqrt[2242057])} We've used Condition i.e. /; to assure definitions of x[i], y[i] only for i in an appropriate range determined by Length @ s , i.e. number of solutions.
{ "source": [ "https://mathematica.stackexchange.com/questions/6669", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1450/" ] }
6,704
There's a game I saw at a friend's yesterday, that I often see at people's homes, but never for enough time to think on it too hard. It's called peg solitaire (thanks @R.M). So I came home and I wanted to find a solution in Mathematica, so I did the following First, some visual functions. The game consists of a board with some slots that can either have a piece on it (black dot in this visual representation) or be empty (white dot) empty=Circle[{0,0},0.3]; filled=Disk[{0, 0}, 0.3]; plotBoard[tab_]:=Graphics[GeometricTransformation[#1,TranslationTransform/@ Position[tab, #2]]&@@@{{empty, 0},{filled, 1}}, ImageSize->Small] The starting board is the following. tableroStart=({ {-1, -1, 1, 1, 1, -1, -1}, {-1, -1, 1, 1, 1, -1, -1}, {1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 0, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1}, {-1, -1, 1, 1, 1, -1, -1}, {-1, -1, 1, 1, 1, -1, -1} }); -1 is used to represent places where there can't be any pieces. 0 for empty slots. 1 for slots with a piece on it. So, plotBoard[tableroStart] // Framed Rules: Given a board such as the previous one, you can only move by "taking" a single piece, jumping over it. So, you take a piece, you choose one of the 4 straight directions, you jump over the adjacent piece and fall in an empty slot. The game is won by having only one last piece on the board. So, in the starting board, there are 4 possible moves, all symmetrical. In this code, moves are represented by rules, so, {3, 4}->{3, 6} represents a move of the piece in coordinates {3, 4} , to coordinates {3, 6} , jumping over the piece at {3, 5} and taking it out of the board. So, let's start programming. This finds the possible moves towards some specified zero position findMovesZero[tab_,pos_List]:=pos+#&/@(Join[#, Reverse/@#]&[Thread@{{0, 1, 3, 4}, 2}])// Extract[ArrayPad[tab, 2],#]&// Pick[{pos-{2, 0}, pos+{2, 0}, pos-{0, 2}, pos+{0, 2}},UnitStep[Total/@Partition[ #, 2]-2], 1]->pos&//Thread[#, List, 1]& Lists all the possible moves given a board tab i:findMoves[tab_]:=i=Flatten[#, 1]&[findMovesZero[tab, #]&/@Position[tab, 0]] Given the board tab , makes the move makeMove[tab_, posFrom_->posTo_]:=ReplacePart[tab , {posFrom->0, Mean[{posFrom, posTo}]->0,posTo->1}]; Now, the solving function (* solve, given a board tab, returns a list of subsequent moves to win, or $Failed *) (* markTab is recursive. If a board is a success, marks it with $Success and makes all subsequent markTab calls return $NotNecessary *) (* If a board is not a success and doesn't have any more moves, returns $Failed. If it has moves, it just calls itself on every board, saving the move made in the head of the new boards. I know, weird *) Module[{$Success,$NotNecessary, parseSol, $guard, markTab}, markTab[tab_/;Count[tab, 1, {2}]===1]:=$Success/;!($guard=False)/;$guard; i:markTab[tab_]:=With[{moves=findMoves[tab]},(i=If[moves==={}, $Failed,(#[markTab@makeMove[tab, #]]&/@moves)])]/;$guard; markTab[tab_]/;!$guard:=$NotNecessary; (* parseSol converts the tree returned by markTab into the list of moves until $Success, or in $Failed *) parseSol[sol_]/;FreeQ[{sol}, $Success]:=$Failed; parseSol[sol_]:=sol[[Apply[Sequence,#;;#&/@First@Position[sol, $Success]]]]//#/.r_Rule:>Null/;(Sow[r];False)&//Reap//#[[2, 1]]&; solve[tab_]:=Block[{$guard=True},parseSol@markTab@tab]; ] Solution visualization function plotSolution[tablero_, moves_]:= MapIndexed[Show[plotBoard[#1], Epilog->{Red,Dashed,Arrow[List@@First@moves[[#2]]]}]&, Rest@FoldList[makeMove[#, #2]&,tablero,moves]]// Prepend[#, plotBoard[tablero]]&//Grid[Partition[#, 4, 4, 1, Null], Frame->All]& (* Solves and plots *) solveNplot = With[{sol=solve[#]},If[sol===$Failed, $Failed, plotSolution[#, sol]]]&; In action: solveNplot[( { {-1, -1, 1, 1, 0, -1, -1}, {-1, -1, 1, 1, 1, -1, -1}, {1, 1, 0, 0, 0, 0, 0}, {1, 1, 0, 0, 0, 0, 0}, {1, 1, 0, 0, 0, 0, 0}, {-1, -1, 1, 1, 1, -1, -1}, {-1, -1, 1, 1, 1, -1, -1} } )] returns, after about a min's though, So, the question is. How can we make it efficient enough so it can do the trick for an almost filled board like tableroStart ? The first move is actually always the same let alone symmetries so we could start a move ahead
Preamble Here is my first stab at it. This will not be the fastest possible solution (I hope to add some faster ones later), but even it will have no problems with your boards, including the full one you started with. Before we dive into code, I will list the prerequisites for fast code in this case: Right choice of data structures Avoiding symbolic Mathematica overhead, which, sorry to say it, is just huge Avoiding copying in favor of direct modifications Code Reproducing @Rojo's visualization functions to make this self-contained: empty = Circle[{0, 0}, 0.3]; filled = Disk[{0, 0}, 0.3]; plotBoard[tab_] := Graphics[GeometricTransformation[#1, TranslationTransform /@ Position[tab, #2]] & @@@ {{empty, 0}, {filled, 1}}, ImageSize -> Small] I will start with your test board: start = { {-1, -1, 1, 1, 0, -1, -1}, {-1, -1, 1, 1, 1, -1, -1}, {1, 1, 0, 0, 0, 0, 0}, {1, 1, 0, 0, 0, 0, 0}, {1, 1, 0, 0, 0, 0, 0}, {-1, -1, 1, 1, 1, -1, -1}, {-1, -1, 1, 1, 1, -1, -1} } First comes the optimized compiled function to find all possible steps for a given board: getStepsC = Compile[{{board, _Integer, 2}}, Module[{black = Table[{0, 0}, {Length[board]^2}], bctr = 0, i, j, steps = Table[{{0, 0}, {0, 0}}, {Length[board]^2}], stepCtr = 0, next, nnext }, Do[ If[board[[i, j]] == 1, black[[++bctr]] = {i, j}], {i, 1,Length[board]}, {j, 1, Length[board]} ]; black = Take[black, bctr]; Do[ Do[ next = pos + st; nnext = pos + 2*st; If[board[[next[[1]], next[[2]]]] == 1 && board[[nnext[[1]], nnext[[2]]]] == 0, steps[[++stepCtr]] = {pos, nnext} ], {st, {{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1,0}, {-1, -1}, {0, -1}, {1, -1}}} ], {pos, black} ]; Take[steps, stepCtr]], CompilationTarget -> "C", RuntimeOptions -> "Speed" ]; This function is expecting the board padded with -1 -s, so that we don't have to check that the point belongs to the board. It will therefore also return cooridinates shifted by 1. It returns a list of sublists of starting and ending points for possible steps. Here is an example: getStepsC[ArrayPad[start, 1, -1]] {{{2, 4}, {4, 4}}, {{2, 4}, {4, 6}}, {{2, 4}, {2, 6}}, {{2, 5}, {4, 5}}, {{2, 5}, {4, 7}}, {{4, 2}, {6, 4}}, {{4, 2}, {4, 4}}, {{5, 2}, {5, 4}}, {{6, 2}, {6, 4}}, {{6, 2}, {4, 4}}, {{8,4}, {6, 6}}, {{8, 4}, {6, 4}}, {{8, 5}, {6, 7}}, {{8, 5}, {6, 5}}, {{8, 6}, {6, 6}}, {{8, 6}, {6, 4}}} Here is a function which helps to visualize all possible steps: ClearAll[showPossibleSteps]; showPossibleSteps[brd_] := Show[plotBoard[brd], Epilog -> Map[{Red, Dashed, Arrow[# - {1, 1}]} &, getStepsC[ArrayPad[brd, 1, -1]]]] It pads the board with -1 -s and subtracts 1 from both coordinates for the resulting steps. Using it, we get: showPossibleSteps[start] Next comes the main recursive function: Clear[makeStep]; makeStep[steps : {step : {st_, end_}, prev_}, memoQ : (True | False) : False] := Module[{nblacks}, nblacks := Total@Clip[Flatten@board, {0, 1}]; If[nblacks == 1, Throw[steps, "Win"]]; If[memoQ && visited[board], Return[] ]; board[[st[[1]], st[[2]]]] = board[[(st[[1]] + end[[1]])/2, (st[[2]] + end[[2]])/2]] = 0; board[[end[[1]], end[[2]]]] = 1; If[nblacks == 1, Throw[steps, "Win"]]; Do[makeStep[{new, steps}, memoQ], {new, getStepsC[board]}]; If[memoQ, visited[board] = True]; board[[st[[1]], st[[2]]]] = board[[(st[[1]] + end[[1]])/2, (st[[2]] + end[[2]])/2]] = 1; board[[end[[1]], end[[2]]]] = 0; ]; makeStep[___] := Throw[$Failed]; Few notes here: first, the board variable is not local to the body of makeStep (it is a global variable). Second, memoization can be switched on and off by the memoQ flag, and the related hash-table visited is also global. The above function is intended to be driven by the main one, not to be used in isolation. Last, note that the history of the previous steps is recorded in the linked list, which is an efficient way of doing this. The way the function works is similarly to the @Rojo's code, but instead of collecting entire tree and then traversing it, it throws an exception at run-time as soon as the solution is found, and communicates the collected list of previous step via this exception. This allows the code to be memory-efficient. Now, the main function: Clear[getSolution]; getSolution[brd_, memoQ : (True | False) : False] := Block[{board = Developer`ToPackedArray@ArrayPad[brd, 1, -1], visited}, visited[_] = False; Catch[ Do[makeStep[{new, {}}, memoQ], {new, getStepsC[board]}], "Win" ] ]; Here are functions used for visualization: ClearAll[showBoardStep]; showBoardStep[brd_, step_] := Show[plotBoard[brd], Epilog -> {Red, Dashed, Arrow[step]}]; ClearAll[toPlainListOfSteps]; toPlainListOfSteps[stepsLinkedList_] := Reverse@ Reap[ NestWhile[(Sow[First@# - {1, 1}]; Last[#]) &, stepsLinkedList, # =!= {} &] ][[2, 1]]; ClearAll[showSolution]; showSolution[startBoard_, stepsLinkedList_] := Module[{b = startBoard}, Grid[Partition[#, 4, 4, 1, Null], Frame -> All] &@ MapAt[plotBoard, #, 1] &@ FoldList[ With[{st = #2[[1]], end = #2[[2]]}, b[[st[[1]], st[[2]]]] = b[[(st[[1]] + end[[1]])/2, (st[[2]] + end[[2]])/2]] = 0; b[[end[[1]], end[[2]]]] = 1; showBoardStep[b, #2]] &, b, toPlainListOfSteps[stepsLinkedList]]]; What happens here is that I convert the linked list of steps to a plain list, and perform the relevant transformations on the board. Results and benchmarks First, the test board, with and without the memoization: getSolution[start]//Short//AbsoluteTiming {0.0585938, {{{4,2},{4,4}},{{{4,5},{4,3}},{{{6,3},{4,5}},{{{7,4},{5,4}}, {{{8,6},{6,4}},<<1>>}}}}} } (stepList = getSolution[start,True])//Short//AbsoluteTiming {0.0419922, {{{4,2},{4,4}},{{{4,5},{4,3}},{{{6,3},{4,5}},{{{7,4},{5,4}}, {{{8,6},{6,4}},<<1>>}}}}} } Note that the steps are reversed (last steps are shown first), and coordinates are shifted by 1. If you use showSolution[start, stepList] you get a sequence similar to what is displayed in the question. Note that it only took a small fraction of a second to get the result (as opposed to a minute cited by @Rojo). Note also that memoization helped, but not dramatically so. Now, the real deal: (stepList0 = getSolution[tableroStart]);//AbsoluteTiming {18.7744141,Null} (stepList = getSolution[tableroStart,True])//Short//AbsoluteTiming {2.0517578,{{{6,2},{6,4}},{{{6,5},{6,3}},{{{6,7},{6,5}}, {{{8,6},{6,6}},{{{8,4},{8,6}},<<1>>}}}}}} Here memoization helps a great deal - we get an order of magnitude speedup. And here are the steps: showSolution[tableroStart, stepList] Conclusions This problem makes for a great case study, and is a very nice vehicle to study and analyze various performance issues as they reflect themselves in Mathematica. I have presented a straightforward (conceptually) implementation, whose main merit is not that the algorithm is particularly clever, but that it avoids some (but not all) serious performance pitfalls. Some other performance hits seem to be unavoidable, particularly those related to the top-level code being slow ( makeStep function). This would have been different had Compile supported pass-by-reference and hash-tables (so that makeStep could be efficiently compiled). As I said, this is not the fastest method, and I intend to add faster code later, but it illustrates main points. Note that the solution is essentially the same (conceptually) as what @Rojo did (except that I don't construct the full tree). What is really different is that frequent operations such as search for next steps are heavily optimized here (they take the most time), and also, I win big by mutating the board in place rather than copy it in the recursive invocations of makeStep . The result is a 3 orders of magnitude speed-up, and perhaps the solution has different computational complexity in general (although this is not yet clear to me). Coming soon : Java port of this solution, prototyped entirely in Mathematica, which is another 20-30 times faster (according to my benchmarks).
{ "source": [ "https://mathematica.stackexchange.com/questions/6704", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/109/" ] }
6,706
I want to generate a path to cut an arbitrary shape into a set of jigsaw puzzle pieces. All pieces must be unique to preclude placing a piece in the wrong spot. Pieces must be interlocking such that each piece is held by adjacent pieces. It must be possible to generate different paths (sets) for a specific shape that are not merely rotations or reflections of the first. Since jigsaw puzzles are mass produced there must be a known solution. However, my interest is not in simply implementing this solution, rather I am curious to know how one might approach this task, aided by Mathematica . I am also interested in alternatives to the standard puzzle piece such as these (even if pieces are not 100% interlocking):
======= Update ========= Great question! It inspired this Wolfram Blog article and includes most of the code below plus some apps and fractal layouts like this: I think it make sense to keep the older code blow for archival and historic purposes. ======= Older implementation ========= Excellent motivating creativity question. This is a bit big for a comment, so here are a few thoughts. There is an obvious relation to tiling problems which are well represented in the Wolfram Demonstration Project . One approach could be to morph some non-interlocking tilling pieces to have interlocking parts (if interlocking is important) Perhaps some twist to a puzzle can come from a-periodic tilling large piece set tilling Not all tilings are appropriate, because of, for example, presence of gaps. So here are some candidates: Robinson Tiling Penrose Tiles Pinwheel Tiling Ammann Tiles Pentagon Tilings Voronoi Image Neat Alternating Tilings of the Plane Nowhere-Neat Tilings of the Plane, Part 2 ==== Voronoi practical implementation ==== Let's start from writing the following function: bsc[p1_, p2_] := With[{rc = RandomChoice[{-1, 1}], d = EuclideanDistance[p1, p2], pm = (p1 + p2)/2, dp = (p2 - p1)/5}, If[d < .1, Line[{p1, p2}], BSplineCurve[{p1, pm, pm - dp + rc {1, -1} Reverse[dp], pm + dp + rc {1, -1} Reverse[dp], pm, p2}, SplineWeights -> {1, 5, 5, 5, 5, 1}/22] ]] which will morph a long enoug line into a line with a "tongue". It will put the tongue in a random direction for more random generation of puzzle pieces. And some comparison function that will show what points we are adding to wrap BSplineCurve around. f[p1_, p2_] := With[{d = EuclideanDistance[p1, p2], pm = (p1 + p2)/2, dp = (p2 - p1)/5}, If[d < .1, Line[{p1, p2}], Line[{p1, pm, pm - dp + {1, -1} Reverse[dp], pm + dp + {1, -1} Reverse[dp], pm, p2}] ]] Here is a Manipulate to test it out: Manipulate[ Graphics[{f @@ pt, {Red, Thick, bsc @@ pt}}, ImageSize -> {300, 300}, Axes -> True, Frame -> True, AspectRatio -> 1, PlotRange -> {{0, 1}, {0, 1}}], {{pt, {{0, 0}, {1, 1}}}, Locator}, FrameMargins -> 0] Now this will create a simple Voronoi diagram: gr = ListDensityPlot[RandomReal[{}, {35, 3}], InterpolationOrder -> 0, Mesh -> All, Frame -> False] And this will extract lines out of it and replace long enoug lines with our tongues function: Graphics[bsc @@@ Union[Sort /@ Flatten[Partition[#, 2, 1] & /@ Map[gr[[1, 1, #]] &, Flatten[Cases[gr, Polygon[_], Infinity][[All, 1]], 1]], 1]]] This can be superimposed on an image or simply colorized (with added outer frame): MorphologicalComponents[ Binarize@Graphics[{Thick, bsc @@@ Union[ Sort /@ Flatten[ Partition[#, 2, 1] & /@ Map[gr[[1, 1, #]] &, Flatten[Cases[gr, Polygon[_], Infinity][[All, 1]], 1]], 1]]}, Frame -> True, FrameTicks -> False, PlotRangePadding -> 0, FrameStyle -> Thick]] // Colorize You have to execute code a few times to find best random colorization - it is based on random tongue orientation. === Yet another way - Hilbert & Moore curves==== I slightly modified this Demonstration and cut resulting curves with grid lines: LSystem[axiom_, rules_List, n_Integer?NonNegative, False] := LSystem[axiom, rules, n, False] = Nest[StringReplace[#, rules] &, axiom, n]; LSystem[axiom_, rules_List, n_Integer?NonNegative, True] := LSystem[axiom, rules, n, True] = NestList[StringReplace[#, rules] &, axiom, n]; LSeed["Hilbert curve"] = "+RF-LFL-FR+"; LSeed["Moore curve"] = "+LFL+F+LFL-"; LRules["Hilbert curve"] = {"L" -> "+RF-LFL-FR+", "R" -> "-LF+RFR+FL-"}; LRules["Moore curve"] = {"L" -> "-RF+LFL+FR-", "R" -> "+LF-RFR-FL+"}; LPoints[lstring_String] := LPoints[lstring] = Map[First, Split[Chop[Map[First, FoldList[Function[{pta, c}, Switch[c, "+", {pta[[1]], pta[[2]] + 90 Degree}, "-", {pta[[1]], pta[[2]] - 90 Degree}, "F", {{pta[[1]][[1]] + Cos[pta[[2]]], pta[[1]][[2]] + Sin[pta[[2]]]}, pta[[2]]}, _, pta]], {{0, 0}, 0.}, Characters[lstring]]]]]]; LPoints[lstring_String, level_Integer?NonNegative] := Map[(2^(5 - level)*# + ((2^(5 - level) - 1)/2)) &, LPoints[lstring]]; LLine[lstring_String, level_Integer?NonNegative] := {AbsoluteThickness[2*(5 - level)], BSplineCurve[LPoints[lstring, level]]}; Manipulate[ MorphologicalComponents[ Binarize@Graphics[If[showPreviousLevels == False, LLine[ LSystem[LSeed[whichcurve], LRules[whichcurve], n - 1, showPreviousLevels], n], MapIndexed[LLine[#1, First[#2]] &, LSystem[LSeed[whichcurve], LRules[whichcurve], n - 1, True]]], GridLinesStyle -> Directive[Thick, Black], FrameStyle -> Thick, GridLines -> {None, Table[x, {x, 4, 30, 4}]}, Frame -> True, FrameTicks -> False, PlotRangePadding -> 0]] // Colorize , {{n, 4}, ControlType -> None}, {{whichcurve, "Hilbert curve", ""}, {"Hilbert curve", "Moore curve"}, ControlType -> RadioButtonBar}, {{showPreviousLevels, False}, ControlType -> None}, SaveDefinitions -> True]
{ "source": [ "https://mathematica.stackexchange.com/questions/6706", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/121/" ] }
6,727
Please consider the following list: data={1, 0, 0, 0, 2, 5, 2, 3, 0, 0, 3}; Now I would like to split the list into 0-sequences and Not-0-sequences as following: {{1}, {0, 0, 0}, {2, 5, 2, 3}, {0, 0}, {3}} All numbers are non-negative Integer s, if that helps.
Split[{1, 0, 0, 0, 2, 5, 2, 3, 0, 0, 3}, Xor[#1 != 0, #2 == 0] &] or more compactly Split[{1, 0, 0, 0, 2, 5, 2, 3, 0, 0, 3}, Xnor[#1 == 0, #2 == 0] &] works nicely here. Another way is: SplitBy[{1, 0, 0, 0, 2, 5, 2, 3, 0, 0, 3}, Unitize] or SplitBy[{1, 0, 0, 0, 2, 5, 2, 3, 0, 0, 3}, Sign] or, as Szabolcs suggests: SplitBy[{1, 0, 0, 0, 2, 5, 2, 3, 0, 0, 3}, # == 0 &]
{ "source": [ "https://mathematica.stackexchange.com/questions/6727", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/508/" ] }
6,822
I wondered if there was a way to automate the process of finding a way to tile a tile into a square. The idea is to represent the tile with a matrix of $0$s for blank space and $1$s for filled spaces like in $\{\{0,1,1\}, \{1,0,0\}\}$. The square (or a general rectangular area) is represented by an array as well. The function should then have as arguments two lists (representing the tile and the area) and should find the ways (if they exist) to do the tiling. This is quite an hard problem for me, I have tried playing with Plus , so that if the result matrix has $2$ it means that the tile overlaps while if it is $0$ there is a gap but I can't find a way to tell Mathematica that they should fit the area.
In this article the author solves the problem of tiling a rectangle by using pieces taken from a set of polyominoes, which are plane geometric figures formed by joining one or more equal squares edge to edge. For example, these are the pentaminoes, polyominoes formed by joining 5 squares: Of course this problem is more difficult than the one you asked for, but it is also more interesting and ... there is Mathematica code in the article!
{ "source": [ "https://mathematica.stackexchange.com/questions/6822", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1463/" ] }
6,862
I've got another plotting problem. I want to plot Sin[z] where z is complex. So, I've tried the following: Plot3D[ Sin[ x + I y], {x, -1, 1}, {y, -1, 1}] I wanted to see how the sine function looks like on the unit circle. But... I get no output. Am I doing something wrong or is the kernel stuck?
Well, you have to treat the real and imaginary parts separately. You can't really have a complex $z$ value in these plots. Here's one way to visualize complex sine: Table[Plot3D[f[Sin[x + I y]], {x, -1, 1}, {y, -1, 1}, PlotLabel -> TraditionalForm[f[Sin[z]]], RegionFunction -> Function[{x, y, z}, x^2 + y^2 < 1]], {f, {Re, Im, Abs}}] // GraphicsRow One further visualization aid would be to color these functions by the argument (adapting a scheme by Roman Maeder): Table[Plot3D[f[Sin[x + I y]], {x, -5, 5}, {y, -5, 5}, ColorFunction -> Function[{x, y, z}, Hue[(Pi + If[z == 0, 0, Arg[Sin[x + I y]]])/(2Pi)]], ColorFunctionScaling -> False, PlotLabel -> TraditionalForm[f[Sin[z]]], RegionFunction -> Function[{x, y, z}, x^2 + y^2 < 25]], {f, {Re, Im, Abs}}] // GraphicsRow As Artes notes, one could have used ParametricPlot3D[] so that you are directly working with polar coordinates: Table[ParametricPlot3D[{r Cos[t], r Sin[t], f[Sin[r Exp[I t]]]}, {r, 0, 5}, {t, -Pi, Pi}, BoxRatios -> OptionValue[Plot3D, BoxRatios], ColorFunction -> Function[{x, y, z}, Hue[(Pi + If[z == 0, 0, Arg[Sin[x + I y]]])/(2 Pi)]], ColorFunctionScaling -> False, PlotLabel -> TraditionalForm[f[Sin[z]]]], {f, {Re, Im, Abs}}] // GraphicsRow Yet another visualization possibility: Table[ParametricPlot3D[{r Cos[t], r Sin[t], f[Sin[r Exp[I t]]]}, {r, 0, 5}, {t, -Pi, Pi}, BoxRatios -> OptionValue[Plot3D, BoxRatios], ColorFunction -> Function[{x, y, z}, Hue[(Pi + If[z == 0, 0, Arg[Sin[x + I y]]])/(2Pi)]], ColorFunctionScaling -> False, MeshFunctions -> (#4 &), MeshShading -> {Automatic, None}, MeshStyle -> Transparent, PlotLabel -> TraditionalForm[f[Sin[z]]], PlotRange -> All], {f, {Re, Im, Abs}}] // GraphicsRow
{ "source": [ "https://mathematica.stackexchange.com/questions/6862", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1148/" ] }
6,876
I'm playing around with some code that's calling external command-line commands on a windows platform, and when doing this, the command prompt will pop up quickly and then disappear. This is not a huge bother, if you are calling something once, however if you have a loop running and each call takes some time, it becomes a major annoyance. Consider the following code: Table[Pause[1/2]; Run[ "dir" ];, {3}]; Is there any way to avoid this behavior, or calling an external program though other methods then by Run[] .
On Windows 7 using ReadList instead of Run suppresses the window: Table[Pause[1/2]; ReadList["!dir", String], {3}]; This use of "!command" in place of a file is at least partially documented under OpenRead : On systems that support pipes, OpenRead["!command"] runs the external program specified by command , and opens a pipe to get input from it. As Albert Retey notes in the comments, running a command without returning output would therefore best be done with: Close @ OpenRead @ "!command" And stated in Joel Klein's answer streams should always be closed. ReadList does this automatically; when using OpenRead we must manually Close the stream.
{ "source": [ "https://mathematica.stackexchange.com/questions/6876", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1194/" ] }
6,877
I have written some custom functions to draw multi-panel graphs like this one: It's done by passing a matrix of (custom) plotting functions to a MultiPanelGraph function, which pulls apart the head, argument and options of those plots, adds a few of its own, and then puts it all together. There is also some funkiness to deal with plot labels and footnotes, but I've removed these from the code below for simplicity. The PanelHeightFactor type options are custom options to the custom functions for the individual plots. Likewise the MultiPanel option tells the custom functions for the individual plots to, for example, turn off ticks and tick marks on particular sub-plots so that they all fit together neatly as shown in the picture above, and to turn the PlotLabel into a panel label inside the plot frame using Prolog . Attributes[MultiPanelGraph]={HoldFirst}; MultiPanelGraph[{{l_[largs__,lopts___Rule], r_[rargs__,ropts___Rule]}}, mpopts:OptionsPattern[{MultiPanelGraph,myLineGraph}]] := Module[{ (* there was some stuff here *)},With[{ wl = PanelWidthFactor /.{lopts}/.{PanelWidthFactor->1/2}, wr = PanelWidthFactor /.{ropts}/.{PanelWidthFactor->1/2}, Grid[{{l @@ Join[{largs},{lopts}, {MultiPanel-> {All,Left},PanelHeightFactor->1,PanelWidthFactor->wl, ImageMargins->0}], r @@ Join[{rargs},{ropts}, {MultiPanel->{All,Right},PanelHeightFactor->1, PanelWidthFactor->wr,ImageMargins->0}]}}, Sequence @@ FilterRules[Join[{mpopts},{lopts},{ropts}],Grid], Spacings -> {0,0} , ItemSize -> {{4.8+42.*wl, 4.+42.*wr},Full}, Alignment -> Left] It works fine (aside from some issues to do with ImageSize being measured in points and ItemSize being measured in x-heights or some silly thing - a topic for another question), but I would have to code every single case - 2 by 1, 2 by 2, 3 by 4, whatever else some manager decides he or she wants - separately. Doable, but tedious. I can imagine capturing the dimensions of the grid to get the appropriate default PanelWidthFactor and PanelHeightFactor , but beyond that I don’t know if there is a neat way to capture all the possible cases in one definition of the function. Does anyone have any suggestions for coding this in a way that doesn’t require each separate case to be coded to match separately? It would have to handle telling the subplot which ticks to use depending on its position. EDIT: A couple of additional business requirements that might be useful to know: It's essential for the plot frame to be the same width and height, regardless of how many panels there are, unless this is explicitly overridden (in my code, by having an explicit PanelHeightFactor or PanelWidthFactor option in the code for the subgraph). Panels can be of dated data ( DateListPlot or a custom DateListBarChart ) or undated data ( ListPlot , BarChart ), but never both in the same chart. The subplots will have some options (namely footnotes and source notes) that need to be captured and merged to be shown down the bottom of the main plot.
Of course I can't know all the details of what you really want, but here is a simple starting point, plotGrid , that takes care of the relative sizing and the tick label display automatically. Instead of using panels or grids, I'm placing everything into a single Graphics by using a separate Inset for each plot in the list l . The dimensions of this list l fully determine the layout of the result, under the constraints of the total width and height of the "grid" which are specified as the second and third arguments to the function. The plots that are passed to the function in l must have the frame ticks enabled in all directions in which they could potentially be displayed. That is, you coud for example, prepare all the plots with FrameTicks -> All , or do the analogous thing manually. Here is the code for the function: Options[plotGrid] = {ImagePadding -> 40}; plotGrid[l_List, w_, h_, opts : OptionsPattern[]] := Module[{nx, ny, sidePadding = OptionValue[plotGrid, ImagePadding], topPadding = 0, widths, heights, dimensions, positions, frameOptions = FilterRules[{opts}, FilterRules[Options[Graphics], Except[{ImagePadding, Frame, FrameTicks}]]]}, {ny, nx} = Dimensions[l]; widths = (w - 2 sidePadding)/nx Table[1, {nx}]; widths[[1]] = widths[[1]] + sidePadding; widths[[-1]] = widths[[-1]] + sidePadding; heights = (h - 2 sidePadding)/ny Table[1, {ny}]; heights[[1]] = heights[[1]] + sidePadding; heights[[-1]] = heights[[-1]] + sidePadding; positions = Transpose@ Partition[ Tuples[Prepend[Accumulate[Most[#]], 0] & /@ {widths, heights}], ny]; Graphics[ Table[ Inset[ Show[ l[[ny-j+1, i]], ImagePadding -> { {If[i == 1, sidePadding, 0], If[i == nx, sidePadding, 0]}, {If[j == 1, sidePadding, 0], If[j == ny, sidePadding, topPadding]} }, AspectRatio -> Full ], positions[[j, i]], {Left, Bottom}, {widths[[i]], heights[[j]]}], {i, 1, nx}, {j, 1, ny} ], PlotRange -> {{0, w}, {0, h}}, ImageSize -> {w, h}, Evaluate@Apply[Sequence, frameOptions] ] ] The Inset takes care of the relative sizing and the correct placement of the individual plots. To do this most easily, I set the PlotRange of the enclosing Graphics in which the Inset s live to {w, h} , identical to the desired ImageSize of the result. To illustrate what it does, there is a bit of algebra to make the Insets containing displayed tick labels wide enough so that the plot frames appear equally sized everywhere. The showing and hiding of the frame tick labels is simply accomplished by setting ImagePadding -> 0 on the interior-facing edges of each plot. For the exterior-facing edges, the option value of ImagePadding is used. That value has to be set large enough to show all labels without cutting them off. One could combine this with the solutions in this answer to improve this a little, but for the purposes of this answer I don't think that's the crucial point. To show how the function works, here is a grid of example plots (I chose simple sine functions - economics data are not my thing): pt = Table[ Plot[Cos[2 Pi m x + Pi/4] Sin[2 Pi n x], {x, -1, 1}, Frame -> True, FrameTicks -> All, PlotRangePadding -> .1, PlotRange -> {-1.1, 1.1}, Background -> Hue[m n/7]], {m, 1, 3}, {n, 1, 2}]; Here I intentionally added a Background color even though it looks weird - the goal is to show more clearly how my function works: plotGrid[pt, 500, 300, ImagePadding -> 40] What the colors show is where the ImagePadding has been set to zero, and where it extends beyond the plot frame to reveal the labels (which are actually present around all plots). The function takes the option ImagePadding as shown above. Here is another example with a larger matrix of plots, using the default ImagePadding : pt = Table[ Plot[Cos[2 Pi m x + Pi/4] Sin[2 Pi n x], {x, -1, 1}, Frame -> True, FrameTicks -> All, PlotRangePadding -> .1, PlotRange -> {-1.1, 1.1}, Background -> Hue[m n/7]], {m, 1, 3}, {n, 1, 4}]; plotGrid[pt, 500, 400] I've focused only on the logic to arrange the plots, and that still leaves you to figure out how to make the plots look good when they are placed in the grid. For example, one has to take care to avoid tick labels at the very extreme ends of the frame because they tend to get too close to the edge and get cut off when facing a neighboring plot. Also, one could add If statements to suppress the FrameTicks at certain edges. That's pretty easy to add to the framework above, but I'll leave it out for now. Also, if you don't like the labels appearing at the top of the grid, you could just set your individual plots to FrameTicksStyle -> {{Black, Black}, {Black, Transparent}} .
{ "source": [ "https://mathematica.stackexchange.com/questions/6877", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/8/" ] }
6,931
One of the key steps in merge sort is the merging step. Given two sorted lists sorted1={2,6,10,13,16,17,19}; sorted2={1,3,4,5,7,8,9,11,12,14,15,18,20}; of integers, we want to produce a new list as follows: Start with an empty list acc . Compare the first elements of sorted1 and sorted2 . Append the smaller one to acc . Remove the element used in step 2 from either sorted1 or sorted2 . If neither sorted1 nor sorted2 is empty, go to step 2. Otherwise append the remaining list to acc and output the value of acc . Applying this process to sorted1 and sorted2 , we get acc={1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20} Added in response to Rojo's question: We can carry out this procedure even if the two lists are not pre-sorted. So list1 and list2 below are not assumed to be sorted. If there were a built-in function MergeList which carries out this process, it would probably take three arguments list1 , list2 , and f . Here f is a Boolean function of two arguments used to decide which element to pick. In the case of merge sort, f = LessEqual . I feel that MergeList is a fundamental list operation, so Question 1: Is there such a built-in function or one very close to that? If I were to write such a function in Scheme, I would use a recursive definition equivalent to the following: MergeList[list1_,{},f_,acc_:{}]:=Join[acc,list1]; MergeList[{},list2_,f_,acc_:{}]:=Join[acc,list2]; MergeList[list1_,list2_,f_,acc_:{}]:= If[ f@@First/@{list1,list2}, MergeList[Rest[list1],list2,f,Append[acc,First[list1]]], MergeList[list1,Rest[list2],f,Append[acc,First[list2]]] ] Sample output with unsorted lists: In[2]:= MergeList[{2,5,1},{3,6,4},LessEqual] Out[2]= {2,3,5,1,6,4} My impression is that recursive solutions tend to be inefficient in Mathematica, so Question 2: What would be a better way to implement MergeList ? If you have tips about converting loops into their functional equivalents, feel free to mention them as well.
Preamble Since I agree that it would be nice to have a generic function of this type, I will provide a general implementation. First, I will give a generic one based on linked lists, then I will add a JIT-compiled one for special numeric types, and lastly, I will bring it all together. Top-level implementation based on linked lists Here is a reasonably efficient implementation based on linked lists: ClearAll[toLinkedList, ll]; SetAttributes[ll, HoldAllComplete]; toLinkedList[s_List] := Fold[ll[#2, #1] &, ll[], Reverse[s]]; and the main function: ClearAll[merge]; merge[a_ll, ll[], s_, _] := List @@ Flatten[ll[s, a], Infinity, ll]; merge[ll[], b_ll, s_, _] := List @@ Flatten[ll[s, b], Infinity, ll]; merge[ll[a1_, atail_], b : ll[b1_, _], s_, f_: LessEqual] /;f[a1, b1] := merge[atail, b, ll[s, a1], f]; merge[a : ll[a1_, _], ll[b1_, brest_], s_, f_: LessEqual] := merge[a, brest, ll[s, b1], f]; merge[a_List, b_List, f_: LessEqual] := merge[toLinkedList@a, toLinkedList@b, ll[], f]; For example: merge[{2,5,1},{3,6,4},LessEqual] {2,3,5,1,6,4} merge[{2,5,1},{3,6,4},Greater] {3,6,4,2,5,1} And also for large lists: large1 = RandomInteger[100, 10000]; large2 = RandomInteger[100, 10000]; Block[{$IterationLimit = Infinity}, merge[large1,large2,LessEqual]]//Short//AbsoluteTiming {0.0751953,{70,54,78,84,11,21,41,49,78,93,90,70,19, <<19975>>,42,2,10,40,53,12,2,47,89,40,2,80}} For a complete implementation of merge sort algorithm based on linked lists, see this post (the difference there is that I used repeated rule application instead of recursion. Originally, the goal of that example was to show that ReplaceRepeated is not necessarily slow if the patterns are constructed efficiently). Full implementation including JIT-compilation I'd like to show here how one could implement a fairly complete function which would automatically dispatch to an efficient JIT-compiled code when the arguments are appropriate. Compilation will work not just for numeric lists, but for lists of tensors in general, as long as they are of the same shape. JIT - compilation First comes the JIT-compiled version, done along the lines discussed in this answer , section "Making JIT-compiled functions" ClearAll[mergeJIT]; mergeJIT[pred_, listType_, target : ("MVM" | "C") : "MVM"] := mergeJIT[pred, Verbatim[listType], target] = Block[{fst, sec}, With[{decl = {Prepend[listType, fst], Prepend[listType, sec]}}, Compile @@ Hold[decl, Module[{result = Table[0, {Length[fst] + Length[sec]}], i = 0, fctr = 1, sctr = 1}, While[fctr <= Length[fst] && sctr <= Length[sec], If[pred[fst[[fctr]], sec[[sctr]]], result[[++i]] = fst[[fctr++]], (* else *) result[[++i]] = sec[[sctr++]] ] ]; If[fctr > Length[fst], result[[i + 1 ;; -1]] = sec[[sctr ;; -1]], (* else *) result[[i + 1 ;; -1]] = fst[[fctr ;; -1]] ]; result ], CompilationTarget -> target ]]]; You can use this in isolation: mergeJIT[LessEqual,{_Integer,1},"MVM"][{2,5,1},{3,6,4}] {2,3,5,1,6,4} but it is much better to use as a part of the generic function, which would figure out the types for you automatically. Generic function implementation This is a function to find the type of our lists: Clear[getType, $useCompile]; getType[arg_List] /; $useCompile && ArrayQ[arg, _, IntegerQ] := {_Integer, Length@Dimensions@arg}; getType[arg_List] /; $useCompile && ArrayQ[arg, _, NumericQ] && Re[arg] == arg := {_Real, Length@Dimensions@arg}; getType[_] := General; This is a function to dispatch to a right type: Clear[mergeDispatch]; SetAttributes[mergeDispatch, Orderless]; mergeDispatch[{Verbatim[_Integer], n_}, {Verbatim[_Real], n_}, pred_] := mergeDispatch[{Verbatim[_Real], n}, {Verbatim[_Real], n}, pred]; mergeDispatch[f : {Verbatim[_Real], n_}, {Verbatim[_Real], n_}, pred_] := mergeJIT[pred, f, $target]; mergeDispatch[f : {Verbatim[_Integer], n_}, {Verbatim[_Integer], n_}, pred_] := mergeJIT[pred, f, $target]; mergeDispatch[_, _, pred_] := Function[{fst, sec}, Block[{$IterationLimit = Infinity}, merge[fst, sec, pred]]]; and this is a function to bring it all together: ClearAll[mergeList]; Options[mergeList] = { CompileToC -> False, Compiled -> True }; mergeList[f_, s_, pred_, opts : OptionsPattern[]] := Block[{ $target = If[TrueQ[OptionValue[CompileToC]], "C", "MVM"], $useCompile = TrueQ[OptionValue[Compiled]] }, mergeDispatch[getType@f, getType@s, pred][f, s] ]; Finally, a helper function to clear the cache of mergeJIT , if that would be desired: ClearAll[clearMergeJITCache]; clearMergeJITCache[] := DownValues[mergeJIT] = {Last@DownValues[mergeJIT]}; Benchmarks and tests First, create test data: clearMergeJITCache[]; huge1 = RandomInteger[1000,1000000]; huge2 = RandomInteger[1000,1000000]; A first call to the function with C compilation target is expensive: mergeList[huge1,huge2,Less,CompileToC -> True]//Short//AbsoluteTiming {3.8652344,{267,461,66,607,797,116,197,474,852,805,135, <<1999978>>,266,667,799,280,261,930,241,83,594,904,894}} But then, for the same types of lists, it will pay off for huge lists: mergeList[huge1,huge2,Less,CompileToC -> True]//Short//AbsoluteTiming {0.0468750,{267,461,66,607,797,116,197,474,852,805,135, <<1999978>>,266,667,799,280,261,930,241,83,594,904,894}} On the other hand, the call with MVM target is fast out of the box, but not as fast as the one with the C target after the "warm-up": mergeList[huge1,huge2,Less]//Short//AbsoluteTiming {0.2138672,{267,461,66,607,797,116,197,474,852,805,135, <<1999978>>,266,667,799,280,261,930,241,83,594,904,894}} The call to generic one is general but comparatively very slow: mergeList[huge1,huge2,Less,Compiled->False]//Short//AbsoluteTiming {5.015,{267,461,66,607,797,116,197,474,852,805,135, <<1999978>>,266,667,799,280,261,930,241,83,594,904,894}}
{ "source": [ "https://mathematica.stackexchange.com/questions/6931", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/281/" ] }
6,961
Is it possible to set a notebook's background to a nonscrolling image?
In version 9 there is a new option called BackgroundAppearance that can be used to set the notebook's background. The picture below was made by setting this option in the option inspector to FrontEnd`FileName[{"SlideShow"}, "WaterTitleBackground.png"]
{ "source": [ "https://mathematica.stackexchange.com/questions/6961", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/403/" ] }
6,994
I have a function for which 0 is a special case: f[A___, 0, B___] := 0 But since I am doing numerics, sometimes in the course of things f gets called with 0. instead of 0 . Of course I can add the line f[A___, 0., B___] := 0 But I don't understand why I need to because I don't understand the difference between 0 and 0. . Can anyone illuminate this for me? (In addition to saving a line of code, or as Jens points out, a couple of characters, I also want to know the difference between them so I don't run into hard-to-debug problems in the future because of something I didn't know about.)
0. is an approximate real number that is very close to zero, while 0 is exactly zero. They aren't the same object, as 0 === 0. is False , and 0. has a head of Real , while 0 has a head of Integer . If you want to turn 0. into 0 , you can use Chop , although that will replace all approximate numbers within some tolerance (by default 10^(-10) ) of zero with 0 .
{ "source": [ "https://mathematica.stackexchange.com/questions/6994", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1167/" ] }
6,998
What are, and how do I use Mathematica's string matching and replacement tools?
There are three different mechanisms provided for matching string patterns in Mathematica . Each of these must be used within functions that are equipped to handle strings. You cannot, for instance, use: {"abc", "def", "ghi"} /. "a*" -> 1 Replace["downwind", "downw" -> "resc"] to any effect. Instead you would use: {"abc", "def", "ghi"} /. x_String /; StringMatchQ[x, "a*"] -> 1 StringReplace["downwind", "downw" -> "resc"] Simple wildcard matching: Example: StringMatchQ["abcde", "ab*"] yields True . Wildcards (or "metacharacters") do not work natively in functions such as StringReplace and StringCases and are usually used with StringMatchQ . They also work with and are useful for simple commands such as Names["Pre*"] . Regular Expressions Since version 5.1 Mathematica supports regular expressions . I am not an expert on regular expression use, and detailed usage information is readily available in both the Mathematica documentation and elsewhere, so I leave it to the reader to explore. RegEx is powerful and popular with those doing a lot of string manipulation, especially for performance. StringExpression Also since version 5.1 there is a paradigm of using familiar Mathematica expression patterns for strings, along with a multitude of special named patterns, within a StringExpression object. It has the short infix form ~~ such that a ~~ b ~~ c has the long form StringExpression[a, b, c] . StringExpression also accepts patterns in the RegularExpression form making it the master method for Mathematica string patterns. A major advantage of this new paradigm is that you can use most of the Mathematica pattern elements you should already be familiar with, such as _ , __ , ___ , .. , ... , Except , Shortest , Longest etc. You can also name these patterns as you can in expression matching. Here is a contrived replacement on the start of Lorem ipsum using Blank , Repeated , Condition , and Pattern : sample = StringTake[ExampleData[{"Text", "LoremIpsum"}], 200]; Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer nunc augue, feugiat non, egestas ut, rutrum eu, purus. Vestibulum condimentum commodo pede. Nam in metus eu justo commodo posuere. Nun StringReplace[ sample, x_ ~~ y : Repeated[LetterCharacter, 5] ~~ " " /; UpperCaseQ[x] :> "X" <> y <> " " ] Xorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer nunc augue, feugiat non, egestas ut, rutrum eu, purus. Vestibulum condimentum commodo pede. Xam in metus eu justo commodo posuere. Nun
{ "source": [ "https://mathematica.stackexchange.com/questions/6998", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/121/" ] }
7,052
How do I control the shape of my arrow heads? LaTeX's TikZ package has a wide variety of predefined arrowhead styles, some of which I'd like to try to match for Mathematica figures I'm importing into a LaTeX document: But Mathematica's default arrowhead style comes nowhere near any of these. For example, Graphics[{Thick, Arrow[{{0, 0}, {-50, 0}}]}] yields Earlier versions of Mathematica had options for controlling arrowhead shape, but those seem to be gone in 8.0. How can I get the shape of my Mathematica arrowheads to match the LaTeX TikZ arrowhead styles?
Here is a Manipulate to design yourself an Arrow : DynamicModule[{top, baseMid, rightBase, outerMidRight, innerMidRight}, Manipulate[ top = {0, 0}; baseMid = {1, 0} baseMid; rightBase = {1, -1} leftBase; outerMidRight = {1, -1} outerMidLeft; innerMidRight = {1, -1} innerMidLeft; h = Graphics[ { Opacity[0.5], FilledCurve[ { BSplineCurve[{baseMid, innerMidLeft, leftBase}], BSplineCurve[{leftBase, outerMidLeft, top}], BSplineCurve[{top, outerMidRight, rightBase}], BSplineCurve[{rightBase, innerMidRight, baseMid}] } ] } ], {{baseMid, {-2, 0}}, Locator}, {{innerMidLeft, {-2, 0.5}}, Locator}, {{leftBase, {-2, 1}}, Locator}, {{outerMidLeft, {-1, 1}}, Locator} ] ] It is easy to add more control points if the need arises. The arrowhead graphics is put in the variable h . Note that it contains an Opacity function for better visibility of the control points. You need to remove that if you want to have a fully saturated arrow head. Some examples generated with this Manipulate using: Graphics[ { Arrowheads[{{Automatic, 1, h /. Opacity[_] :> Sequence[]}}], Arrow /@ Table[{{0, 0}, {Sin[t], Cos[t]}}, {t, 0, 2 \[Pi] - 2 \[Pi]/20, 2 \[Pi]/20}] }, PlotRangePadding -> 0.2 ] The code for the arrow heads can be found in h . Just copy the graphics or the FullForm to store it for later use. h /. Opacity[_] :> Sequence[] // FullForm (* ==> Graphics[{FilledCurve[{BSplineCurve[{{-0.496, 0.}, {-1., 0.48}, {-2,1}}], BSplineCurve[{{-2, 1}, {-0.548, 0.44999999999999996}, {0, 0}}], BSplineCurve[{{0, 0}, {-0.548, -0.44999999999999996}, {-2, -1}}], BSplineCurve[{{-2, -1}, {-1., -0.48}, {-0.496, 0.}}]}]} ] *) EDIT One more control point will cover most common shapes: DynamicModule[{top, baseMid, outerMidRight, innerMidRight, innerBaseRight, outerBaseRight}, Manipulate[ top = {0, 0}; baseMid = {1, 0} baseMid; innerBaseRight = {1, -1} innerBaseLeft; outerBaseRight = {1, -1} outerBaseLeft; outerMidRight = {1, -1} outerMidLeft; innerMidRight = {1, -1} innerMidLeft; h = Graphics[ { Opacity[0.5], FilledCurve[ { BSplineCurve[{baseMid, innerMidLeft, innerBaseLeft}], Line[{innerBaseLeft, outerBaseLeft}], BSplineCurve[{outerBaseLeft, outerMidLeft, top}], BSplineCurve[{top, outerMidRight, outerBaseRight}], Line[{outerBaseRight, innerBaseRight}], BSplineCurve[{innerBaseRight, innerMidRight, baseMid}] } ] } ], {{baseMid, {-2, 0}}, Locator}, {{innerMidLeft, {-2, 0.5}}, Locator}, {{innerBaseLeft, {-2, 1}}, Locator}, {{outerBaseLeft, {-2, 1.1}}, Locator}, {{outerMidLeft, {-1, 1}}, Locator} ] ]
{ "source": [ "https://mathematica.stackexchange.com/questions/7052", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/37/" ] }
7,125
It has been noticed on several occasions that DayOfWeek function is rather slow when applied to a large list of dates, e.g. in this recent question . What faster alternatives do we have in such situations?
Just a literal implementation of a formula for the day of the week: Clear[dow]; dow[{year_, month_, day_, _ : 0, _ : 0, _ : 0}] := Module[{Y = If[month == 1 || month == 2, year - 1, year], m = Mod[month + 9, 12] + 1, y, c, s = {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}}, y = Mod[Y, 100]; c = Quotient[Y, 100]; s[[Mod[day + Floor[2.6 m - 0.2] + y + Quotient[y, 4] + Quotient[c, 4] - 2 c, 7] + 1]]]; Seems to give a 5-fold speed increase: d = RandomDates[100000]; DayOfWeek /@ d // Short // AbsoluteTiming dow /@ d // Short // AbsoluteTiming {19.5781250,{Thursday,Thursday,Sunday,Friday,<<99992>>,Tuesday,Saturday,Saturday,Thursday}} {3.7968750,{Thursday,Thursday,Sunday,Friday,<<99992>>,Tuesday,Saturday,Saturday,Thursday}} Addition Your function is readily compilable: dowc = Compile[{{year, _Integer}, {month, _Integer}, {day, _Integer}}, Module[ {Y, m, y, c, s}, Y = If[month == 1 || month==2, year-1, year]; m = Mod[month + 9, 12] + 1; y = Mod[Y, 100]; c = Quotient[Y, 100]; Mod[day + Floor[2.6 m-0.2] + y + Quotient[y, 4] + Quotient[c, 4]-2 c,7]+1 ], CompilationTarget -> "C", RuntimeAttributes -> {Listable}, Parallelization -> True ]; In[286]:= dowc @@@ d[[All, 1 ;; 3]] // Short // AbsoluteTiming Out[286]= {0.136741,{6,4,5,2,4,5,3,7,<<99984>>,5,4,2,4,3,2,5,6}}
{ "source": [ "https://mathematica.stackexchange.com/questions/7125", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/81/" ] }
7,132
This being the Q number 2K in the site, and this being the day we got the confirmation of mathematica.se graduating soon, I think a celebration question is in order. So... What is the fastest way to compute the happy prime number 2000 in Mathematica? Edit Here are the Timing[ ] results so far: {"JM", {5.610, 137653}} {"Leonid", {5.109, {12814, 137653}}} {"wxffles", {4.11, {12814, 137653}}} {"Rojo", {0.765, {12814, 137653}}} {"Rojo1", {0.547, {12814, 137653}}}
This answer should be read upside down, since the last edit has the fastest, neatest and shortest answer Module[{$guard = True}, happyQ[i_] /; $guard := Block[{$guard = False, appeared}, appeared[_] = False; happyQ[i] ] ] e : happyQ[_?appeared] := e = False; happyQ[1] = True; e : happyQ[i_] := e = (appeared[i] = True; happyQ[#.#&@IntegerDigits[i]]) Now, taking this from @LeonidShiffrin happyPrimeN[n_] := Module[{m = 0, pctr = 0}, While[m < n, If[happyQ@Prime[++pctr], m++]]; {pctr, Prime[pctr]}]; EDIT Ok, this was cool, but if you don't mind wasting a little memory and not resetting appeared , it becomes simple and less cool appeared[_] = False; happyQ[1] = True; happyQ[_?appeared] = False; e : happyQ[i_] := e = (appeared[i] = True; happyQ[#.# &@IntegerDigits[i]]) EDIT2 Slightly faster but I like it twice as much happyQ[1] = True; e : happyQ[i_] := (e = False; e = happyQ[#.# &@IntegerDigits[i]]) or perhaps to make it slightly shorter and a little bit more memory efficient, reducing the recursion tree's height happyQ[1] = True; e : happyQ[i_] := e = happyQ[e = False; #.# &@IntegerDigits[i]]
{ "source": [ "https://mathematica.stackexchange.com/questions/7132", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/193/" ] }
7,142
When it comes to visual analysis, large datasets or data with intricate internal details often makes plotting in 2D useless, as the outcome is either just a fraction of the full dataset, or no details can be observed in the mess of datapoints. How can one make the process of changing the plot range and/or zooming, panning, etc. less tedious than doing it programmatically and iteratively, from time to time? I often meet with this issue, and developed various methods to deal with it ( like this ). Though I have now a working solution that I would like to share (see below), I also am highly interested in what kind of methods and tricks others invented to visualize and manipulate complex 2D data with ease.
Completely redesigned at 2015 12 19! Simplified interface, more functionality, robust performance. Plots can now be easily uploaded to StackExchange from within PlotExplorer thanks to halirutan ! Code is at end of post. Functionality: Works with any graphics object, plots, charts, etc. (e.g. Plot , ListPlot , ArrayPlot , RegionPlot , GeoGraphics , BarChart , you name it). Can handle graphics with legend, if legend is within the frame of the graphics object. Compatible with Manipulate , DynamicModule and similar functions. Click anywhere + drag the mouse zooms in/out on the point where the mouse was clicked. Ctrl + drag toggles zooming rectangle (from Szabolcs ). Shift + drag pans the plot (from Heike ). Alt shows coordinates (only when over the plot so that other global Alt -functionality (like Alt + C + L to remove output) can be still used). *) Double click anywhere resets the plot (from kguler ). Resize handler at bottom right corner to manipulate ImageSize (does not change aspect ratio). Ctrl + resize also changes aspect ratio . Menu button appears in upper right corner when mouse is over. Some functionality is only available for certain graphics. Replot : updates the iterator(s) of an iterator-based plot to comply with the current plot range. Only available for iterator-based plots holding their first argument where the iterator structure can be corresponded with the plot range, like Plot , DensityPlot , StreamPlot . DiscretePlot , ParametricPlot , PolarPlot and similar cannot be replotted as the iterator values for these functions cannot be deduced from plot ranges. Linear , Log , LogLog , LogLinear : changes the scaling function for the plot. Only available for plots that accept the option ScalingFunctions . Note, that logarithmic scale cannot handle nonpositive plot ranges. Copy actual PlotRange , ImageSize , AspectRatio to clipboard. Copying , pasting , saving graphics expression or rasterized image version. Upload image to StackExchange! Thanks to halirutan's help, it is now possible to directly call some SETools functions from under PlotExplorer , so you don't even have to open the SEUploader palette! Open in external application : first exports rasterized image as TIFF to the system temporary directory and then calls SystemOpen to call for the default image-viewer application. Extra functionality can be easily added to the Menu button, by adding to GraphicsButton in the code. Some functions that require a dynamically manipulable structure instead of the final graphics ojects (like Replot ) are inserted into the button from within the DynamicModule of PlotExplorer . Full set of commands in the context menu: Limitations Graphics editing functionality (i.e. when double-clicked) is suppressed. If legend is positioned off the plot range (e.g. Placed[leg, After] ), it cannot be displayed within the dynamic pane range. Workaround: supply legend that is positioned within the plot range (e.g. Placed[leg, Center] ). Replotting is only applicable when the plot is passed unevaluated (i.e. as PlotExplorer[Plot[...]] instead of PlotExplorer[plot] or PlotExplorer[Show[Plot[...], ...]] ), as in the latter cases the iterator structure (and new iterator value(s)) cannot be deduced. Replotting a non-deterministic plot yields different results every time. A zoomed-in/out plot might look undersampled due to fixed sampling frequency. Workaround: use Replot. A zoomed-in plot can be replotted, but it results in a smaller-than-original plot range. Zooming out does not revert to the original range automatically. Workaround: use Replot. When using Manipulate/Dynamic/DynamicModule[PlotExplorer[Plot[...], ...], changes made by PlotExplorer` are discarded whenever the wrapper triggers a dynamic update (e.g. a slider is moved), and thus the plot reverts to the original. When a plot is requested to be replotted in a domain where it is not defined, expect unwanted result, even error messages (e.g. extrapolation is used when InterpolatingFunction is plotted outside of its domain). Known issues BUG: In DensityPlot and GeoGraphics , any button object appears with a white background. Could not find a workaround. MouseAppearance is not always displayed correctly. Examples Zoomin in-out by dragging plot. Double click to reset. PlotExplorer@Plot[{Sin@x, Cos@x}, {x, 0, 100}] Replotting. PlotExplorer@ContourPlot[Sin[x y], {x, 0, 3}, {y, 0, 3}, ColorFunction -> "BlueGreenYellow", PlotPoints -> 3] Zooming rectangle ( Ctrl + drag) and double click to reset. PlotExplorer@ListLinePlot[Table[Accumulate[ RandomReal[{-1, 1}, 250]], {3}], Filling -> Axis] Accessing coordinates ( Alt ). Resize and Ctrl + resize. PlotExplorer@PlotExplorer@Graphics[ {Red, Disk[], Green, Rectangle[{0, 0}, {2, 2}], Blue, Disk[{2, 2}]}] Panning the plotted area using Shift + drag: PlotExplorer@ Plot[Evaluate@Table[BesselJ[n, x/50]*4, {n, 4}], {x, 0, 10000}, Filling -> Axis, PlotRange -> {{0, 1000}, {-1, 1}}] Code GetPlotRange::usage = "GetPlotRange[gr] returns the actual unpadded plot range of \ graphics gr. GetPlotRange[gr, True] returns the actual padded plot \ range of gr. GetPlotRange can handle Graphics, Graphics3D and Graph \ objects."; GetPlotRange[_[gr : (_Graphics | _Graphics3D | _Graph | _GeoGraphics), ___], pad_] := GetPlotRange[gr, pad];(*Handle Legended[\[Ellipsis]] and similar.*) GetPlotRange[gr_GeoGraphics, False] := (PlotRange /. Quiet@AbsoluteOptions@gr);(*TODO:does not handle PlotRangePadding.*) GetPlotRange[gr_Graph, pad_: False] := Charting`get2DPlotRange[gr, pad]; GetPlotRange[gr : (_Graphics | _Graphics3D), pad_: False] := Module[{r = PlotRange /. Options@gr}, If[MatrixQ[r, NumericQ], (*TODO:does not handle PlotRangePadding*)r, Last@Last@ Reap@Rasterize[ Show[gr, If[pad === False, PlotRangePadding -> None, {}], Axes -> True, Frame -> False, Ticks -> ((Sow@{##}; Automatic) &), DisplayFunction -> Identity, ImageSize -> 0], ImageResolution -> 1]]]; (* Joins and filters options, keeping the righmost if there are \ multiple instances of the same option. *) filter[opts_List, head_] := Reverse@DeleteDuplicatesBy[ Reverse@FilterRules[Flatten@opts, First /@ Options@head], First]; (* Find and use SETools of Szabolcs & Halirutan *) $SEToolsExist = FileExistsQ@ FileNameJoin@{$UserBaseDirectory, "Applications", "SETools", "Java", "SETools.jar"}; (* If SETools exist, initiate JLink and include some functions *) If[$SEToolsExist, Needs@"JLink`"; JLink`InstallJava[]; copyToClipboard[text_] := Module[{nb}, nb = NotebookCreate[Visible -> False]; NotebookWrite[nb, Cell[text, "Input"]]; SelectionMove[nb, All, Notebook]; FrontEndTokenExecute[nb, "Copy"]; NotebookClose@nb; ]; uploadButtonAction[img_] := uploadButtonAction[img, "![Mathematica graphics](", ")"]; uploadButtonAction[img_, wrapStart_String, wrapEnd_String] := Module[{url}, Check[url = stackImage@img, Return[]]; copyToClipboard@(wrapStart <> url <> wrapEnd); ]; stackImage::httperr = "Server returned respose code: `1`"; stackImage::err = "Server returner error: `1`"; stackImage::parseErr = "Could not parse the answer of the server."; stackImage[g_] := Module[{url, client, method, data, partSource, part, entity, code, response, error, result, parseXMLOutput}, parseXMLOutput[str_String] := Block[{xml = ImportString[str, {"HTML", "XMLObject"}], result}, result = Cases[xml, XMLElement["script", _, res_] :> StringTrim[res], Infinity] /. {{s_String}} :> s; If[result =!= {} && StringMatchQ[result, "window.parent" ~~ __], Flatten@ StringCases[result, "window.parent." ~~ func__ ~~ "(" ~~ arg__ ~~ ");" :> {StringMatchQ[func, "closeDialog"], StringTrim[arg, "\""]}], $Failed]]; parseXMLOutput[___] := $Failed; data = ExportString[g, "PNG"]; JLink`JavaBlock[ JLink`LoadJavaClass["de.halirutan.se.tools.SEUploader", StaticsVisible -> True]; response = Check[SEUploader`sendImage@ToCharacterCode@data, Return@$Failed]]; If[response === $Failed, Return@$Failed]; result = parseXMLOutput@response; If[result =!= $Failed, If[TrueQ@First@result, Last@result, Message[stackImage::err, Last@result]; $Failed], Message[stackImage::parseErr]; $Failed] ]; ]; GraphicsButton::usage = "GraphicsButton[lbl, gr] represent a button that is labeled with \ lbl and offers functionality for the static graphics object gr. \ GraphicsButton[gr] uses a tiny version of gr as label."; MenuItems::usage = "MenuItems is an option for GraphicsButton that specifies \ additional label \[RuleDelayed] command pairs as a list to be \ included at the top of the action menu of GraphicsButton."; Options[GraphicsButton] = DeleteDuplicatesBy[ Flatten@{MenuItems -> {}, RasterSize -> Automatic, ColorSpace -> Automatic, ImageResolution -> 300, Options@ActionMenu}, First]; GraphicsButton[expr_, opts : OptionsPattern[]] := GraphicsButton[ Pane[expr, ImageSize -> Small, ImageSizeAction -> "ShrinkToFit"], expr, opts]; GraphicsButton[lbl_, expr_, opts : OptionsPattern[]] := Module[{head, save, items = OptionValue@MenuItems, rasterizeOpts, dir = $UserDocumentsDirectory, file = ""}, rasterizeOpts = filter[{Options@GraphicsButton, opts}, Options@Rasterize]; save[format_] := (file = SystemDialogInput["FileSave", FileNameJoin@{dir, "." <> ToLowerCase@format}]; If[file =!= $Failed && file =!= $Canceled, dir = DirectoryName@file; Quiet@ Export[file, If[format === "NB", expr, Rasterize[expr, "Image", rasterizeOpts]], format]]); head = Head@Unevaluated@expr; ActionMenu[lbl, Flatten@{ If[items =!= {}, items, Nothing], "Copy expression" :> CopyToClipboard@expr, "Copy image" :> CopyToClipboard@Rasterize@expr, "Copy high-res image" :> CopyToClipboard@Rasterize[expr, "Image", rasterizeOpts], "Paste expression" :> Paste@expr, "Paste image" :> Paste@Rasterize@expr, "Paste high-res image" :> Paste@Rasterize[expr, "Image", rasterizeOpts], Delimiter, "Save as notebook\[Ellipsis]" :> save@"NB", "Save as JPEG\[Ellipsis]" :> save@"JPEG", "Save as TIFF\[Ellipsis]" :> save@"TIFF", "Save as BMP\[Ellipsis]" :> save@"BMP", Delimiter, Style["Upload image to StackExchange", If[$SEToolsExist, Black, Gray]] :> If[$SEToolsExist, uploadButtonAction@Rasterize@expr], "Open image in external application" :> Module[{f = Export[FileNameJoin@{$TemporaryDirectory, "temp_img.tiff"}, Rasterize@expr, "TIFF"]}, If[StringQ@f && FileExistsQ@f, SystemOpen@f]] }, filter[{Options@GraphicsButton, opts, {Method -> "Queued"}}, Options@ActionMenu]]]; PlotExplorer::usage = "PlotExplorer[plot] returns a manipulable version of plot. \ PlotExplorer can handle Graph and Graphics objects and plotting \ functions like Plot, LogPlot, ListPlot, DensityPlot, Streamplot, etc. \ PlotExplorer allows the modification of the plot range, image size \ and aspect ratio. If the supplied argument is a full specification of \ a plotting function holding its first argument (e.g. Plot) the result \ offers functionality to replot the function to the modified plot \ range. PlotExplorer has attribute HoldFirst."; AppearanceFunction::usage = "AppearanceFunction is an option for PlotExplorer that specifies \ the appearance function of the menu button. Use Automatic for the \ default appearance, Identity to display a classic button or None to \ omit the menu button."; MenuPosition::usage = "MenuPosition is an option for PlotExplorer that specifies the \ position of the (upper right corner of the) menu button within the \ graphics object."; Attributes[PlotExplorer] = {HoldFirst}; Options[PlotExplorer] = {AppearanceFunction -> (Mouseover[ Invisible@#, #] &@ Framed[#, Background -> GrayLevel[.5, .5], RoundingRadius -> 5, FrameStyle -> None, Alignment -> {Center, Center}, BaseStyle -> {FontFamily -> "Helvetica"}] &), MenuPosition -> Scaled@{1, 1}}; PlotExplorer[expr_, rangeArg_: Automatic, sizeArg_: Automatic, ratioArg_: Automatic, opts : OptionsPattern[]] := Module[{plot = expr, held = Hold@expr, head, holdQ = True, legQ = False, appearance, position, $1Dplots = Plot | LogPlot | LogLinearPlot | LogLogPlot, $2Dplots = DensityPlot | ContourPlot | RegionPlot | StreamPlot | StreamDensityPlot | VectorPlot | VectorDensityPlot | LineIntegralConvolutionPlot | GeoGraphics}, head = held[[1, 0]]; If[head === Symbol, holdQ = False; head = Head@expr]; If[head === Legended, legQ = True; If[holdQ, held = held /. Legended[x_, ___] :> x; head = held[[1, 0]], head = Head@First@expr]]; holdQ = holdQ && MatchQ[head, $1Dplots | $2Dplots]; If[! holdQ, legQ = Head@expr === Legended; head = If[legQ, Head@First@expr, Head@expr]]; If[Not@MatchQ[head, $1Dplots | $2Dplots | Graphics | Graph], expr, DynamicModule[{dyn, gr, leg, replot, rescale, new, mid, len, min = 0.1, f = {1, 1}, set, d, epilog, over = False, defRange, range, size, ratio, pt1, pt1sc = None, pt2 = None, pt2sc = None, rect, button}, {gr, leg} = If[legQ, List @@ plot, {plot, None}]; size = If[sizeArg === Automatic, Rasterize[gr, "RasterSize"], Setting@sizeArg]; defRange = If[rangeArg === Automatic, GetPlotRange[gr, False], Setting@rangeArg]; ratio = If[ratioArg === Automatic, Divide @@ Reverse@size, Setting@ratioArg]; epilog = Epilog /. Quiet@AbsoluteOptions@plot; gr = plot; (*When r1 or r2 is e.g.{1,1} (scale region has zero width), EuclideanDistance by defult returns Infinity which is fine.*) d[p1_, p2_, {r1_, r2_}] := Quiet@N@EuclideanDistance[Rescale[p1, r1], Rescale[p2, r2]]; set[r_] := (range = new = r; mid = Mean /@ range; len = Abs[Subtract @@@ range]; pt1 = None; rect = {};); set@defRange; (*Replace plot range or insert if nonexistent*) replot[h_, hold_, r_] := Module[{temp}, ReleaseHold@ Switch[h, $1Dplots, temp = ReplacePart[ hold, {{1, 2, 2} -> r[[1, 1]], {1, 2, 3} -> r[[1, 2]]}]; If[MemberQ[temp, PlotRange, Infinity], temp /. {_[PlotRange, _] -> (PlotRange -> r)}, Insert[temp, PlotRange -> r, {1, -1}]], $2Dplots, temp = ReplacePart[ hold, {{1, 2, 2} -> r[[1, 1]], {1, 2, 3} -> r[[1, 2]], {1, 3, 2} -> r[[2, 1]], {1, 3, 3} -> r[[2, 2]]}]; If[MemberQ[temp, PlotRange, Infinity], temp /. {_[PlotRange, _] -> (PlotRange -> r)}, Insert[temp, PlotRange -> r, {1, -1}]], _, hold]]; rescale[h_, hold_, sc_] := ReleaseHold@ Switch[h, $1Dplots | $2Dplots, If[MemberQ[hold, ScalingFunctions, Infinity], hold /. {_[ScalingFunctions, _] -> (ScalingFunctions -> sc)}, Insert[hold, ScalingFunctions -> sc, {1, -1}]], _, hold]; appearance = OptionValue@ AppearanceFunction /. {Automatic :> (AppearanceFunction /. Options@PlotExplorer)}; position = OptionValue@MenuPosition /. Automatic -> Scaled@{1, 1}; (*Print@Column@{rangeArg,sizeArg,ratioArg,appearance,position};*) button = If[appearance === None, {}, Inset[appearance@ Dynamic@GraphicsButton["Menu", dyn, Appearance -> If[appearance === Identity, Automatic, None], MenuItems -> Flatten@{{Row@{"Copy PlotRange \[Rule] ", TextForm /@ range} :> (CopyToClipboard[ PlotRange -> range]), Row@{"Copy ImageSize \[Rule] ", InputForm@size} :> (CopyToClipboard[ ImageSize -> size]), Row@{"Copy AspectRatio \[Rule] ", InputForm@ratio} :> (CopyToClipboard[ AspectRatio -> ratio])}, If[MatchQ[head, $1Dplots | $2Dplots], {Delimiter, "Replot at current PlotRange" :> (gr = replot[head, held, range];), "Linear" :> {gr = rescale[head, held, {Identity, Identity}];}, "Log" :> {gr = rescale[head, held, {Identity, "Log"}]}, "LogLinear" :> {gr = rescale[head, held, {"Log", Identity}]}, "LogLog" :> {gr = rescale[head, held, {"Log", "Log"}]}}, {}], Delimiter}], position, Scaled@{1, 1}, Background -> None]]; Deploy@Pane[EventHandler[Dynamic[MouseAppearance[Show[ (*`dyn` is kept as the original expression with only \ updating `range`,`size` and `ratio`.*) dyn = Show[gr, PlotRange -> Dynamic@range, ImageSize -> Dynamic@size, AspectRatio -> Dynamic@ratio], Epilog -> {epilog, button, {FaceForm@{Blue, [email protected]}, EdgeForm@{Thin, Dotted, [email protected]}, Dynamic@rect}, {Dynamic@ If[over && CurrentValue@"AltKey" && pt2 =!= None, {Antialiasing -> False, [email protected], GrayLevel[.5, .5], Dashing@{}, InfiniteLine@{pt2, pt2 + {1, 0}}, InfiniteLine@{pt2, pt2 + {0, 1}}}, {}]}}], Which[over && CurrentValue@"AltKey" && pt2 =!= None, Graphics@{Text[pt2, pt2, -{1.1, 1}, Background -> GrayLevel[1, .7]]}, CurrentValue@"ShiftKey", "LinkHand", CurrentValue@"ControlKey", "ZoomView", True, Automatic]], TrackedSymbols :> {gr}], {"MouseEntered" :> (over = True), "MouseExited" :> (over = False), "MouseMoved" :> (pt2 = MousePosition@"Graphics";), "MouseClicked" :> (If[CurrentValue@"MouseClickCount" == 2, set@defRange];), "MouseDown" :> (pt1 = MousePosition@"Graphics"; pt1sc = MousePosition@"GraphicsScaled";), "MouseUp" :> (If[ CurrentValue@"ControlKey" && d[pt1, pt2, new] > min, range = Transpose@Sort@{pt1, pt2};]; set@range;), "MouseDragged" :> (pt2 = MousePosition@"Graphics"; pt2sc = MousePosition@"GraphicsScaled"; Which[CurrentValue@"ShiftKey", pt2 = MapThread[ Rescale, {MousePosition@ "GraphicsScaled", {{0, 1}, {0, 1}}, new}] - pt1; range = new - pt2;,(*Panning*)CurrentValue@"ControlKey", rect = If[pt1 === None || pt2 === None, {}, Rectangle[pt1, pt2]];,(*Zooming rectangle*)True, f = 10^(pt1sc - pt2sc); range = (mid + (1 - f) (pt1 - mid)) + f/2 {-len, len}\[Transpose](*Zofom on `pt1`*)])}, PassEventsDown -> True, PassEventsUp -> True], Dynamic[size, (size = #; If[CurrentValue@"ControlKey", ratio = Divide @@ Reverse@#]) &], AppearanceElements -> "ResizeArea", ImageMargins -> 0, FrameMargins -> 0]]]];
{ "source": [ "https://mathematica.stackexchange.com/questions/7142", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/89/" ] }
7,149
I'm using some iterative arithmetics to calculate wave propagation with the help of NestList. I have to use a small step size for iteration to guarantee the accuracy, which lead to too much data (e.g, 10^6 points) for further plotting, and the results consumes too much memories. Is there any clever way to cope with it? I didn't intend to use loops. This is a simplified example: NestList[Sin, 1, 10^6] One of my idea is to use Sow and Reap . But I've no idea to integrate them with NestList or Nest Any idea???
Due to insistent public demand: If, in a sequence of iterates $\{x,f(x),f(f(x)),\dots\}$, one only needs every $k$-th iterate (say, for $k=3$, you want $\{x,f(f(f(x))),f(f(f(f(f(f(x)))))),\dots\}$), then one can cleverly combine Nest[] and NestList[] like so: NestList[Nest[f, #, k] &, start, n] which yields a list containing the zeroth, $k$-th, $2k$-th, ... $nk$-th iterates.
{ "source": [ "https://mathematica.stackexchange.com/questions/7149", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/978/" ] }
7,275
I found this plot on Wikipedia: Domain coloring of $\sin(z)$ over $(-\pi,\pi)$ on $x$ and $y$ axes. Brightness indicates absolute magnitude, saturation represents imaginary and real magnitude. Despite following the link and reading the page nothing I have tried is giving me the result shown. How should this be done?
Building on Heike's ColorFunction , I came up with this: The white bits are the trickiest - you need to make sure the brightness is high where the saturation is low, otherwise the black lines appear on top of the white ones. The code is below. The functions defined are: complexGrid[max,n] simply generates an $n\times n$ grid of complex numbers ranging from $-max$ to $+max$ in both axes. complexHSB[Z] takes an array $Z$ of complex numbers and returns an array of $\{h,s,b\}$ values. I've tweaked the colour functions slightly. The initial $\{h,s,b\}$ values are calculated using Heike's formulas, except I don't square $s$. The brightness is then adjusted so that it is high when the saturation is low. The formula is almost the same as $b2=\max (1-s,b)$ but written in a way that makes it Listable . domainImage[func,max,n] calls the previous two functions to create an image. func is the function to be plotted. The image is generated at twice the desired size and then resized back down to provide a degree of antialiasing. domainPlot[func,max,n] is the end user function which embeds the image in a graphics frame. complexGrid = Compile[{{max, _Real}, {n, _Integer}}, Block[{r}, r = Range[-max, max, 2 max/(n - 1)]; Outer[Plus, -I r, r]]]; complexHSB = Compile[{{Z, _Complex, 2}}, Block[{h, s, b, b2}, h = Arg[Z]/(2 Pi); s = Abs[Sin[2 Pi Abs[Z]]]; b = Sqrt[Sqrt[Abs[Sin[2 Pi Im[Z]] Sin[2 Pi Re[Z]]]]]; b2 = 0.5 ((1 - s) + b + Sqrt[(1 - s - b)^2 + 0.01]); Transpose[{h, Sqrt[s], b2}, {3, 1, 2}]]]; domainImage[func_, max_, n_] := ImageResize[ColorConvert[ Image[complexHSB@func@complexGrid[max, 2 n], ColorSpace -> "HSB"], "RGB"], n, Resampling -> "Gaussian"]; domainPlot[func_: Identity, max_: Pi, n_: 500] := Graphics[{}, Frame -> True, PlotRange -> max, RotateLabel -> False, FrameLabel -> {"Re[z]", "Im[z]", "Domain Colouring of " <> ToString@StandardForm@func@"z"}, BaseStyle -> {FontFamily -> "Calibri", 12}, Prolog -> Inset[domainImage[func, max, n], {0, 0}, {Center, Center}, 2` max]]; domainPlot[Sin, Pi] Other examples follow: It's informative to plot the untransformed complex plane to understand what the colours indicate: domainPlot[] A simple example: domainPlot[Sqrt] Plotting a pure function: domainPlot[(# + 2 I)/(# - 1) &] I think this one is very pretty: domainPlot[Log]
{ "source": [ "https://mathematica.stackexchange.com/questions/7275", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/121/" ] }
7,414
The task is: Image shadow removal is an important topic in image processing. If you feel curious about it, you may take a look here , or just google for it image shadow removal There are also a few questions on SE around it. For example: https://dsp.stackexchange.com/questions/2247/how-can-i-remove-shadows-from-an-image https://stackoverflow.com/questions/9081930/how-to-remove-the-shadow-in-image-by-using-opencv However, I did not find any Mma implementations out there, and I don't want to reinvent the wheel if it is already rolling. Does anybody know of some Mma codebase for using it as a starter? Note: I have to do this for a few images, so I may go the manual way better than spend many hours in developing a full blown algorithm.
EDIT : I found a version of the source image with fewer jpeg artifacts. My idea would be to extract pixels along the border of the shadow, inside and outside of the shadow. Then I have a list of pairs of RGB values, and I can find a suitable transformation from "shadowed" pixels to "non-shadowed" pixels. But first, I must find the shadow area. I would apply a mean shift filter to remove the texture: im = Import["http://www.cs.sfu.ca/~mark/ftp/Eccv04/path.jpg"] ms = ms = MeanShiftFilter[GaussianFilter[im, 2], 10, 0.1, MaxIterations -> 5] I can simply binarize this with default thresholds: bin = DeleteSmallComponents[ColorNegate[DeleteSmallComponents[Binarize[ms]]]] Next step: Extract edges and normal directions: edges = EdgeDetect[bin]; dx = GaussianFilter[ImageData[bin], 5, {0, 1}]; dy = GaussianFilter[ImageData[bin], 5, {1, 0}]; edgePixels = Position[ImageData[edges], 1]; normalDirection = Transpose[{Extract[dy, edgePixels], Extract[dx, edgePixels]}]; Now edgePixels contains a list of edge pixel indices and normalDirection contains a list of normal vectors for each of these edge pixels. Next step: for each border pixel, go 40 pixels in the normal direction, and get the RGB value at that point. Go 40 pixels the other way, and pick up that RGB value, too: pixels = ImageData[GaussianFilter[im, 5]]; colorsInsideShadow = Extract[pixels, Round[edgePixels + normalDirection*40]]; colorsOutsideShadow = Extract[pixels, Round[edgePixels - normalDirection*40]]; Just to illustrate, the colors picked up look like this: ImageAssemble[{{Image[ConstantArray[colorsInsideShadow, 10]]}, {Image[ConstantArray[colorsOutsideShadow, 10]]}}] I would simply try a linear model from colors "inside the shadow" to colors "outside the shadow": rgbToModel[{r_, g_, b_}] := {1, r, g, b} colorTransform = LeastSquares[rgbToModel/@colorsInsideShadow, colorsOutsideShadow] Now I can apply this linear model to the shadow area: applyColorTransform = ImageApply[rgbToModel[#].colorTransform &, im, Masking -> DeleteSmallComponents@ColorNegate[Binarize[ms]]] As a last step, I'll use inpainting to remove the artifacts at the border of the shadow area: result = Inpaint[applyColorTransform, Dilation[EdgeDetect[Binarize[ms]], DiskMatrix[1]]] The whole algorithm is still quite ad-hoc (no camera calibration, I didn't even try to model the illumination invariants described in the linked papers), but considering it's simplicity (less than 15 lines of code), I'd say the result isn't that bad.
{ "source": [ "https://mathematica.stackexchange.com/questions/7414", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/193/" ] }
7,441
In MATLAB, there is a command kmeans() that divides an array into $k$ clusters and calculates the centroid of each cluster. Is there any command in Mathematica to perform the same action? For example: x = {{1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15}, {16,17,18,19,20}, {21,22,23,24,25}} The MATLAB kmeans command does this: [b, c] = kmeans(x, 2) It divides x into two clusters and calculates the centroids of these two clusters, and indicates for each element in the array which cluster it is a member of b = {1,1,2,2,2} and c={{3.5000,4.5000,5.5000,6.5000,7.5000},{16.0000,17.0000,18.0000,19.0000,20.0000}}
ClusteringComponents is indeed the function to go for. To get the same results as MATLAB you need to do the following: x = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}}; cc = ClusteringComponents[x, 2, 1, Method -> "KMeans", "DistanceFunction" -> SquaredEuclideanDistance, "RandomSeed" -> 1] {1, 1, 2, 2, 2} The arguments x and 2 are the same as with MATLAB. The '1' is used to indicate the level of the nested array to consider the data points. In this case we're looking at the top level, so we're considering 5D points. Mathematica can use various methods. "KMeans" is default, so it isn't necessary to provide it here. The default "DistanceFunction" is EuclideanDistance . MATLAB's is SquaredEuclideanDistance , so we have to explicitly use that. Since clustering uses a process with random initializations the results may differ depending on the RNG state. I used "RandomSeed" -> 1 to initialize the RNG to a state that yields the results you showed. {1,1,1,2,2} is a possible output too. Now to the centroids: Mean /@ {Pick[x, cc, 1], Pick[x, cc, 2]} // N {{3.5, 4.5, 5.5, 6.5, 7.5}, {16., 17., 18., 19., 20.}} I added //N since you seemed to want machine precision results. Leave it away for exact results. On a side note: KMeans may sometimes yield disastrous results. It's a well-known property of this algorithm. x1 = RandomVariate[MultinormalDistribution[{0, 0}, {{1, 0}, {0, 20}}],500]; x2 = RandomVariate[MultinormalDistribution[{6, 0}, {{1, 0}, {0, 20}}],500]; Graphics@{Red, Point@x1, Green, Point@x2} xx = Join[x1, x2]; cc = ClusteringComponents[xx, 2, 1, Method -> "KMeans", "DistanceFunction" -> SquaredEuclideanDistance, "RandomSeed" -> 1]; {c1, c2} = {Pick[xx, cc, 1], Pick[xx, cc, 2]}; Graphics@{Red, Point@c1, Green, Point@c2} In this case, one of the additional three clustering methods that Mathematica knows ( Method -> "PAM" ) works wonders.
{ "source": [ "https://mathematica.stackexchange.com/questions/7441", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1465/" ] }
7,473
Say I have two trigonometric expressions which are a bit complicated. Is there a quick way to check if they reduce to the same thing (that they are equal) using Mathematica? I was solving this: $y'' + y = \cos 4x,$ $y(0) = 6, y'(0) = 11$ using Laplace transformation technique, and I get this: $y = \frac{-1}{15}\cos(4x) + \left(\frac{1}{15} + 6\right) \cos(x) + 11 \sin(x)$. I wanted to check if my answer is correct and Mathematica gave me this: 1/30 (182 Cos[x] - 5 Cos[x] Cos[3 x] + 3 Cos[x] Cos[5 x] + 330 Sin[x] + 5 Sin[x] Sin[3 x] + 3 Sin[x] Sin[5 x])
Try using FullSimplify : FullSimplify[Sin[x] == Tan[x] Cos[x]] This returns True if Sin[x] == Tan[x] Cos[x] (which it does). Please note that == ( Equal ) should be used instead of a single equal sign ( Set ). More complicated trig identities can be difficult to reason about. Mathematica may not be able to properly determine whether they are true or not. You can still ask for Mathematica 's opinion in these cases however. If the identity is very difficult, you may consider using PossibleZeroQ : PossibleZeroQ[Sin[x] - Tan[x] Cos[x]] Instead of equating the left hand side with the right hand side, subtract them. Then give these expression to PossibleZeroQ . PossibleZeroQ tests whether it is likely that a given expression is equal to 0. If you believe the identity is false but would like an example, you can get this using FindInstance . Here, we ask Mathematica to find an instance where Sin[x] does not equal ( != ) Tan[x] Cos[x] : FindInstance[Sin[x] != Tan[x] Cos[x], x] Mathematica doesn't return any answer. This makes sense because both sides are equal.
{ "source": [ "https://mathematica.stackexchange.com/questions/7473", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1184/" ] }
7,511
How can I partition a list into partitions whose sizes vary? The length of the $k$ 'th partition is a function $f(k)$ . For example: if $l = \{1, 2, 3, 4, 5, 6\}$ and $f(k) = k$ . Then the partitioning $p$ would look like $p = \{\{1\},\{2, 3\},\{4,5,6\}\}$ In Mathematica 11.2, the builtin TakeList will do this.
The core solution If I understand your question I previously wrote a function for this purpose. The core of that function is: dynP[l_, p_] := MapThread[l[[# ;; #2]] &, {{0} ~Join~ Most@# + 1, #} & @ Accumulate @ p] Version 8 users have Internal`PartitionRagged which has the same syntax for the basic case. dynP[Range@6, {1, 2, 3}] {{1}, {2, 3}, {4, 5, 6}} dynP[Range@8, {3, 1, 2, 1}] {{1, 2, 3}, {4}, {5, 6}, {7}} Extended version Since this answer proved popular I decided to do a full rewrite of dynamicPartition : Shorter code with less duplication Better performance and lower argument testing overhead Partitioning of expressions with heads other than List dynamicPartition[ list , runs ] splits list into lengths runs . dynamicPartition[ list , runs , All] appends all remaining elements in a single partition. dynamicPartition[ list , runs , spec 1 , spec 2 , ...] passes specifications spec n to Partition for the remaining elements. dPcore[L_, p : {q___, _}] := Inner[L[[# ;; #2]] &, {0, q} + 1, p, Head@L] dPcore[L_, p_, All] := dPcore[L, p] ~Append~ Drop[L, Last@p] dPcore[L_, p_, n__] := dPcore[L, p] ~Join~ Partition[L ~Drop~ Last@p, n] dynamicPartition[L_, p : {__Integer}, x___] := dPcore[L, Accumulate@p, x] /; ! Negative@Min@p && Length@L >= Tr@p (This code no longer uses dynP shown above.) Usage Examples: dynamicPartition[Range@12, {4, 3}, All] {{1, 2, 3, 4}, {5, 6, 7}, {8, 9, 10, 11, 12}} dynamicPartition[Range@12, {4, 3}, 2] {{1, 2, 3, 4}, {5, 6, 7}, {8, 9}, {10, 11}} dynamicPartition[h[1, 2, 3, 4, 5, 6, 7], {3, 1}, 2, 1, 1, "x"] h[h[1, 2, 3], h[4], h[5, 6], h[6, 7], h[7, "x"]] Packed arrays Please note that one special but practically important case is when the list you want to split is a packed array , or can be converted into one. Here is an illustration. First, we create a large (and apparently unpacked) test list: (test = Flatten[Range/@Range[5000]])//Developer`PackedArrayQ (* False *) We now split it: (res = dynP[test,Range[5000]]);//AbsoluteTiming (* {0.2939453,Null} *) We can see that the sublists are, or course, unpacked as well: Developer`PackedArrayQ/@res//Short (* {False,False,False,False,False,False,False,False, <<4984>>,False,False,False,False,False,False,False,False} *) Converting to a packed array admittedly takes some time: test1 = Developer`ToPackedArray[test]; // AbsoluteTiming (* {0.1660157, Null} *) But if you do some manipulations with this list many times, this will pay off. Also, often you end up with a packed list from the start. Anyway, now splitting this list is several times faster: (res1 = dynP[test1,Range[5000]]);//AbsoluteTiming (* {0.0644531,Null} *) and all the sublists are now also packed: Developer`PackedArrayQ/@res1//Short (* {True,True,True,True,True,True,True,True,True, <<4982>>,True,True,True,True,True,True,True,True,True} *) which has a large impact on the total memory consumption as well: ByteCount/@{res,res1} (* {400320040,50900040} *) The technique of converting sub-lists of a ragged lists to packed form was already discussed a few times here on SE, e.g. here . In this particular case, dynP will do that automatically when the initial list is packed, but it is still good to keep in mind, for example to avoid accidental unpacking of sublists during whatever further processing you want to perform on the resulting ragged list.
{ "source": [ "https://mathematica.stackexchange.com/questions/7511", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/515/" ] }
7,545
I recently came across this video: Mathematically correct breakfast , which shows how a bagel can be neatly sliced into two identical linked halves. I'd like to try this with Mathematica. Here's a torus bagel and a Möbius strip cut overlaid. How can I slice the bagel along this cut to create the two halves and pry it open? With[{opts = {Mesh -> False, Boxed -> False, Axes -> False}}, bagel = ParametricPlot3D[{Cos[t] (3 + Cos[u]), Sin[t] (3 + Cos[u]), Sin[u]}, {t, 0, 2 Pi}, {u, 0, 2 Pi}, opts, PlotStyle -> Directive[Opacity[0.3], FaceForm[Orange], Lighting -> "Neutral"]]; cut = ParametricPlot3D[{Cos[t] (3 + r Cos[t/2]), Sin[t] (3 + r Cos[t/2]), r Sin[t/2]}, {r, -1, 1}, {t, 0, 2 Pi}, opts, PlotStyle -> Directive[Opacity[0.9], FaceForm[Gray], Lighting -> "Neutral"]]; ] bagel ~Show~ cut Although I've used a Möbius strip for the cut, I have a feeling it is a 2-twist strip because of the two sides — I haven't been able to fit this correctly inside a torus...
Here's one way to slice the donut. To draw one half of the sliced donut I'm using a parameterisation of a torus similar to the one on wikipedia , but with v replaced with u + v and v running from 0 to Pi instead of 2 Pi . This means that the cut is actually a double twist loop. pl = ParametricPlot3D[{{Sin[u] (2 + Cos[u + v]), Cos[u] (2 + Cos[u + v]), Sin[u + v]}, {Sin[u] (2 + (2 v/Pi - 1) Cos[u]), Cos[u] (2 + (2 v/Pi - 1) Cos[u]), (2 v/Pi - 1) Sin[u]}}, {u, 0, 2 Pi}, {v, 0, Pi}, Mesh -> False, Boxed -> False, Axes -> False] We could plot the other half in a similar way but to show that the two halves are identical, you can take pl and rotate it over 180 degrees around the z-axis: Graphics3D[{pl[[1]], Rotate[pl[[1]], Pi, {0, 0, 1}]}, Boxed -> False] To pry the two halves open, we need to simultaneously rotate and translate one of the halves, for example Manipulate[Graphics3D[{pl[[1]], Translate[Rotate[Rotate[pl[[1]], 180 Degree, {0, 0, 1}], -a Degree, {1, 0, 0}], {1.8 a/90, 0, 0}]}, Boxed -> False], {{a, 0}, 0, 90}] Here's an animation of the process:
{ "source": [ "https://mathematica.stackexchange.com/questions/7545", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5/" ] }
7,552
I have a lot of data (e.g., 64x8192), to plot and it consumes too much memory (more than 2 GB) causing Mathematica to return "no memory available". For example, lst = Table[Sin[x^2 + y^2], {x, 2^7}, {y, 2^13}]; ListDensityPlot[lst] Is there any way to cope with it?
Scroll to the end for the latest edit. If you really want all the points in a large data set, I'd use a more basic display method: Let's say the matrix of data is m , then do this (assuming the entries m[[i, j]] are real numbers): Image[Rescale[m]] This will make one pixel for each data point without trying to do any interpolation as is the default in density plots. Edit As suggested in the comment, here is a comparison of the timings: (* A test matrix with random entries between 0 and 1: *) m = RandomReal[1, {300, 300}]; Timing@Image[m] Timing@ListDensityPlot[m, MaxPlotPoints -> 1000] So the ListDensityPlot is several orders of magnitude slower than my Image suggestion. This conclusion seems to be almost independent of the choice for MaxPlotPoints . With the Image approach, it is no problem to create extremely large images (say $5000\times 5000$). I would not advise using ListDensityPlot for anything like this. If you want a colored output, just use Colorize as follows: m = RandomReal[1, {300, 300}]; Timing[plot = Colorize[Image[m], ColorFunction -> "LakeColors"]] Edit 2 The final question would be, how to re-create the frame and ticks that you get from ListDensityPlot and its relatives. Let's assume that the range of x and y values corresponding to the matrix dimensions of m are $x \in [0, 2]$ and $y\in[0, 3]$, respectively. Then you get the standard display for the plot we just created as follows: xmin = 0; ymin = 0; xmax = 2; ymax = 3; Graphics[Inset[ Show[plot, AspectRatio -> Full], {xmin, ymin}, {0, 0}, {xmax - xmin, ymax - ymin}], PlotRange -> {{xmin, xmax}, {ymin, ymax}}, Frame -> True] The trick here is to align the bottom left corner {0,0} of the Image to the lower coordinate limits of the PlotRange I chose for the Graphics , and then (using the fourth argument of Inset ) to stretch the image to fit exactly into that PlotRange . The content is only stretchable this way if you show it with the option AspectRatio -> Full . Edit 3 For completeness, here is the example matrix given in the question, constructed in a slightly modified way to make its entries lie between 0 and 1 . Here, Rescale turns out to be very slow when applied to an array of exact numbers, so I speed things up by adding N[] during the construction of the matrix. Thanks to MichaelE2 for pointing this out in the comment. The matrix construction uses Outer and automatically threads Sin over lists in its argument. In this construction, the x coordinate is represented by Range[2^7] and the y coordinate by Range[2^13] - if you switch these then the plot will have the axes switched. The Reverse below is needed to have the vertical axis pointing up: s = Sin[Outer[Plus, N[Reverse[Range[2^13]]^2], N[Range[2^7]^2]] ]; plot = Colorize[Image[s], ColorFunction -> "LakeColors"]; xmin = 1; ymin = 1; xmax = 2^7; ymax = 2^13; Graphics[Inset[ Show[plot, AspectRatio -> Full], {xmin, ymin}, {0, 0}, {xmax - xmin, ymax - ymin}], PlotRange -> {{xmin, xmax}, {ymin, ymax}}, Frame -> True, AspectRatio -> 1] The point of this example is to show how much more detail we get with this approach, compared to the slower ListDensityPlot . Alternative: ArrayPlot I mentioned using Rescale earlier because the arguments to Image have to be in the unit interval to be mapped onto the grayscale range from white to black. This grayscale can later be colorized too. It's important to keep this fact in mind: matrix entries that fall outside the interval $[0, 1]$ will not lie in the range where the grayscale varies and will therefore appear at the same extreme grayscale (or color afte using Colorize ). Once we add the rescaling and the frame ticks, the Image approach de-facto converges to the built-in function ArrayPlot . This is another easy-to-use way of getting a fast plot of a large matrix. You would use it like this: ArrayPlot[m, ColorFunction -> "LakeColors", DataReversed -> True] . I just tried this with the last example matrix, and it works nicely. One more observation According to this linked answer , when using ColorFunction , ArrayPlot isn't as fast as the direct creation of a Raster image. The solution proposed there is not Image as I used here, but instead something like this: Graphics[Raster[Rescale[...], ColorFunction -> "LakeColors"]] To try this with my frame construction, you would have to write it like this (where s is the same as defined in Edit 3 ): xmin = 1; ymin = 1; xmax = 2^7; ymax = 2^13; Graphics[Inset[ Show[ Graphics[Raster[s, ColorFunction -> "LakeColors"]], AspectRatio -> Full, PlotRangePadding -> 0], {xmin, ymin}, {0, 0}, {xmax - xmin, ymax - ymin} ], PlotRange -> {{xmin, xmax}, {ymin, ymax}}, Frame -> True, AspectRatio -> 1 ] When I wrap this in Timing or AbsoluteTiming , I indeed get even lower values. However , I don't really believe those values because the actual time it takes for the plot to appear in the notebook is noticeably slower with this last approach. Nevertheless, I think it's worth including this here. More timing results To test these display methods with the Mandelbrot set of this linked answer , I did a different timing measurement based on recording the absolute time before and after the image/graphic has been displayed. Here is the code to prepare the pictures: mandelComp = Compile[{{c, _Complex}}, Module[{num = 1}, FixedPoint[(num++; #^2 + c) &, 0, 99, SameTest -> (Re[#]^2 + Im[#]^2 >= 4 &)]; num], CompilationTarget -> "C", RuntimeAttributes -> {Listable}, Parallelization -> True]; data = ParallelTable[ a + I b, {a, -.715, -.61, .0001}, {b, -.5, -.4, .0001}]; rc = Rescale[mandelComp[data]]; Now the timing tests (not showing the images that are generated): a1 = AbsoluteTime[]; Graphics[ Raster[rc, ColorFunction -> "TemperatureMap"], ImageSize -> 800, PlotRangePadding -> 0] a2 = AbsoluteTime[] a2 - a1 (* ==> 6.878487 *) This is pretty slow. Compare this to the Image approach: a1 = AbsoluteTime[]; Colorize[Image[rc, ImageSize -> 800], ColorFunction -> "TemperatureMap"] a2 = AbsoluteTime[] a2 - a1 (* ==> 1.119959 *) This is much faster. The ArrayPlot method is twice as slow as the last result, but still faster than the Raster method: a1 = AbsoluteTime[]; ArrayPlot[rc, ImageSize -> 800, ColorFunction -> "TemperatureMap"] a2 = AbsoluteTime[] a2 - a1 (* ==> 2.089126 *) Therefore, my conclusion is: when in doubt, go with Image . Edit (19 June 2014) It seems useful to wrap the conclusion of this answer in a general-purpose function that works similarly to ListDensityPlot but is based on directly creating an Image from the data: Clear[listPixelPlot] ; Options[listPixelPlot] = {Frame -> True, FrameLabel -> {}, ColorFunction -> "LakeColors" , AspectRatio -> 1, DataRange -> All , ImageSize -> Automatic, PlotRange -> All, PlotRangeClipping -> True}; listPixelPlot[array_, OptionsPattern[]] := Module [{field, plot, xmin, xmax, ymin, ymax, dataRange = OptionValue[DataRange], plotRange = Replace[OptionValue[PlotRange], Full | All | Automatic -> {Automatic, Automatic}], range}, field = Reverse@Transpose[array] ; {{xmin, xmax}, {ymin, ymax}} = range = If[ MatrixQ[dataRange] , Reverse[dataRange], Map [ {0 , #} &, Dimensions[array] ] ] ; plot = Colorize[Image[Rescale[N[field] ] ] , ColorFunction -> OptionValue[ColorFunction]] ; Graphics[ Inset[ Show [plot, AspectRatio -> Full] , {xmin, ymin} , {0, 0} , {xmax - xmin, ymax - ymin}], PlotRange -> Table[plotRange[[i]] /. Full | All | Automatic -> range[[i]], {i, 2}], Sequence @@ Map[# -> OptionValue[#] & , {Frame, FrameLabel, ImageSize, AspectRatio, PlotRangeClipping}]] ] This function takes some of the same options that ListDensityPlot or ArrayPlot accept (see Options[ ). With the Mandelbrot test data rc from above, you would call this function (and test its timing) as follows: a1 = AbsoluteTime[]; listPixelPlot[rc, ColorFunction -> "TemperatureMap", ImageSize -> 800] a2 = AbsoluteTime[]; a2 - a1 (* ==> 1.679611 *) This is only slightly slower than the fastest result above. The reason is simply that in this function the argument array is always processed by Rescale before converting it to an Image . To make sure Rescale sees a packed array of machine numbers, the core of the function reads Image[Rescale[N[field] ] ] . A lot of the code deals merely with option handling. It can be extended to provide additional options.
{ "source": [ "https://mathematica.stackexchange.com/questions/7552", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/978/" ] }
7,591
Background I've coded in C/Scheme for 10 years. I have a BS CS. I've recently become very interested in pattern-matching (lisp's match macro), and term rewriting systems, which brought me to Mathematica. I would like to read a book on Mathematica that will show me lots of cool term-rewriting as a programming style techniques. Question: What should I read?
OK, I will start with a few suggestions. I think, that what you really need is to understand Mathematica evaluator. Once you get this understanding, programming in Mathematica will become vastly easier for you, and you will be ready for the advanced examples showing the power of rules. So, here are the steps I'd take: Read the book of David Wagner, "Power programming with Mathematica, the kernel" (1996, Computing McGraw-Hill). This is the best book I know to explain the essence of Mathematica evaluation process, and it is full of nice examples. Although it is currently out of print, you can get a free, licensed PDF copy of the book here . While Wagner explains many things about evaluation process, some more details can be found in the WRI Technical Report by David Withoff titled "Mathematica internals" (thanks @Faysal for reminding me about it). It is a short and very interesting read, and even though it was published in 1992, it is mostly accurate to these days (which speaks well of Mathematica design consistency). Get and read as many books by Roman Maeder as you can :-). There are four I know of, and I would read them in this order: Programming in Mathematica Computer science with Mathematica Mathematica programmer Mathematica programmer II If you thoroughly read these, you will get more than enough background. They are not an easy read, but easily the best and most elegant exposition of Mathematica from the rule-based perspective, with plenty of non-trivial examples. I think his books are still unmatched, even though published way back. You should have no problems reading them after Wagner's book. After that, you can hunt for rule-based code in many places. There are many nice examples in the books of Michael Trott, and also "Mastering Mathematica" by John Gray, as was mentioned in comments. There are also lots of good and non-trivial rule-based code in the past MathGroup posts , StackOverflow discussions ( [mathematica] tag ) and here on Mathematica SE . I will try to collect links to some which I find representative and post them here in this answer. But, to summarize: first, understand the evaluation sequence and evaluation control (Wagner's book is IMO the best source for that, and I will add some links to evaluation-related SO and SE threads here soon). After that, the rest will follow. With your Scheme background, it will be much easier, since the recursive part of Mathematica evaluator is similar to what you know from Lisp / Scheme, so you will have to only grok the rule-based part (which is very substantial, and makes Mathematica evaluator really different).
{ "source": [ "https://mathematica.stackexchange.com/questions/7591", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/-1/" ] }
7,679
I have three parallel lists (i.e. the elements in position i of each list are related). I want to sort the first list using the function Sort and make the same changes to the other lists so that I still have parallel lists when finished. How can I do this? As an example: Given the lists {2, 3, 1} , {a, b, c} , and {alpha, beta, gamma} , sorting all lists according the first one gives {1, 2, 3} , {c, a, b} , and {gamma, alpha, beta} .
lists = {list1, list2, list3} = {{1, 3, 2}, {a, b, c}, {x, y, z}}; Another option SortBy[lists\[Transpose], First]\[Transpose] {{1, 2, 3}, {a, c, b}, {x, z, y}}
{ "source": [ "https://mathematica.stackexchange.com/questions/7679", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/738/" ] }
7,724
So I wanted to create a Histogram with a custom number of bins. Luckily there is a simple function for this in the form of Histogram[data, n] where n specifies the number of bins. There is even an example of using it in the documentation: data = RandomVariate[NormalDistribution[0, 1], 200]; Histogram[data, 5] Problem is that this doesn't produce a Histogram with five bins but with seven bins: Histogram[data, 6] still gives seven bins: Histogram[data, 7] also gives seven bins: But Histogram[data, 10] gives thirteen bins: Now I am utterly confused. Is this a bug or have I misunderstood something completely? How would I go about producing a Histogram with five bins?
Under mma 8 you can use the undocumented {"Raw", n} bin specification to get exactly the number of bins you would like. Otherwise the bin widths and boundaries are chosen to be "nice" numbers. Here is an example: data = RandomVariate[NormalDistribution[0, 1], 200]; Histogram[data, {"Raw", 5}] (I saw this first in a comment by Brett Champion to the answer here .)
{ "source": [ "https://mathematica.stackexchange.com/questions/7724", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/300/" ] }
7,756
I need a table with the elements made of pure functions and list elements. This is a simplified example: I need a list as: {a[[1]]*Sin[#]&,a[[2]]*Sin[#]&,a[[3]]*Sin[#]&} and, my failed try is : Table[a[[i]]*Sin[#]&,{i,3}] Why is the failure and how can I improve it?
Function has the attribute HoldAll , so the reference to i in the Table expression will not be expanded. However, you can use With to inject the value into the held expressions: Table[With[{i = i}, a[[i]]*Sin[#] &], {i, 3}] {a[[1]] Sin[#1] &, a[[2]] Sin[#1] &, a[[3]] Sin[#1] &} This issue will be present not only for Function but for all expressions that hold their arguments (via attributes like HoldFirst ) -- for example: Plot , Dynamic , RuleDelayed (:>) etc. The solution using With is mentioned in the tutorial " Introduction To Dynamic / A Good Trick to Know ".
{ "source": [ "https://mathematica.stackexchange.com/questions/7756", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/978/" ] }
7,768
I've always wished I could do some profiling like you get in Wolfram Workbench, but directly from Mathematica , without using or having Workbench. If it is possible, how can I do it?
You can put your Mathematica session in debug mode by going to Evaluation -> Debugger Then, make some definitions and wrap the profiled code in RuntimeTools`Profile For example, in debug mode, run f[x_] := x^2 Table[f[x], {100000}]; // RuntimeTools`Profile and you get a nice As @acl mentioned in the comments, clicking in the gray area in the output notebook's lines takes you to the related code
{ "source": [ "https://mathematica.stackexchange.com/questions/7768", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/109/" ] }
7,770
I'm trying to write a custom function but it isn't returning any output. Here's my code so far: Options[Alternate] = {AlternationType -> AlternationPlusMinus}; Alternate[Terms_, Exponent_, OptionsPattern[]] := ( tmpSet = {}; If[OptionValue[AlternationType] == AlternationPlusMinus, Do[If[Mod[counter, 2] != 0, AppendTo[tmpSet, (counter^Exponent) - 1] AppendTo[ tmpSet, (counter^Exponent) + 1]], {counter, Terms}], Do[If[Mod[counter, 2] != 0, AppendTo[tmpSet, (counter^Exponent) + 1] AppendTo[ tmpSet, (counter^Exponent) - 1]], {counter, Terms}]]; Return[Expand[InterpolatingPolynomial[tmpSet, x]]]; ); Alternate[20, 2] When I execute it, no output block is even generated, let alone any error messages or warnings, is there any way to fix it? Thanks.
You can put your Mathematica session in debug mode by going to Evaluation -> Debugger Then, make some definitions and wrap the profiled code in RuntimeTools`Profile For example, in debug mode, run f[x_] := x^2 Table[f[x], {100000}]; // RuntimeTools`Profile and you get a nice As @acl mentioned in the comments, clicking in the gray area in the output notebook's lines takes you to the related code
{ "source": [ "https://mathematica.stackexchange.com/questions/7770", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1637/" ] }
7,811
I've been struggling to create a DotPlot like the one shown in Cleveland's The Elements of Graphing Data. Using the following dataset data = Sort[{#, WolframAlpha[ StringJoin["Number of native speakers ", #], {{"Result", 1}, "ComputableData"}]} & /@ {"Mandarin", "French", "English", "Spanish", "German", "Hindi", "Malay", "Arabic", "Portuguese", "Russian", "Korean", "Italian", "Cantonese", "Telugu", "Urdu"}, #1[[2]] < #2[[2]] &] What is the best approach to replicate this chart with its two axis, dot, dashed lines , etc?
Something like this : data = Sort[{#, WolframAlpha[ StringJoin["Number of native speakers ", #], {{"Result", 1}, "ComputableData"}]} & /@ {"Mandarin", "French", "English", "Spanish", "German", "Hindi", "Malay", "Arabic", "Portuguese", "Russian", "Korean", "Italian", "Cantonese", "Telugu", "Urdu"}, #1[[2]] < #2[[2]] &] sorted = SortBy[data, #[[2]] &] ; len= Length[sorted] ; ListPlot[Transpose[{Log[2, sorted[[All, 2]]/10^6], Range[len]}], PlotRange -> {All, All}, Frame -> True, FrameTicks -> {{{#, sorted[[#, 1]]} & /@ Range[len], None}, {{#, 2^#} & /@ Range[len], {#, #} & /@ Range[len]}}, GridLines -> {None, {#, Dotted} & /@ Range[len]}, FrameLabel -> {"Number of Speakers (millions)", ""}, PlotLabel -> "Log Number of Speakers (\!\(\*SubscriptBox[\(log\), \(2\)]\) \ \ millions)", AxesOrigin -> {0, Log[2, 1.5]}]
{ "source": [ "https://mathematica.stackexchange.com/questions/7811", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1096/" ] }
7,871
I'm trying to make a demonstration of how rounding to different numbers of digits affects things but I can't find a way to round numbers to a specified number of digits. The Round function only round to the nearest whole integer, and that is not what I always want. Other ways seems to only change the way the numbers are displayed, not how they are internally stored. I want to throw away precision, but it seems Mathematica doesn't want to allow me to do this. As an example: I would like to round 3.4647 to just 3.5 or 3.46. There must be some way to do this, but I can't for the life of me find it.
Just specify the nearest multiple in the second argument. Round[123.456, 0.01] 123.46
{ "source": [ "https://mathematica.stackexchange.com/questions/7871", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/300/" ] }
7,924
While there are some cases where a For loop might be reasonable , it's a general mantra – one I subscribe to myself – that "if you are using a For loop in Mathematica, you are probably doing it wrong". But For and Do loops are familiar to people who already know other programming languages. It is common for new Mathematica users to rely on loop constructs, only to become frustrated with performance or code complexity. My question is: are there some general rules of thumb that would help new users select the appropriate alternative to a procedural For or Do loop, and are there other useful Mathematica constructs, aside from RandomVariate / Nest / Fold / Inner / Outer / Tuples that they should know about in order to avoid those loops? In particular, there are a number of ways of iterating over lists: The For loop: For[i = 1, i <= 10, i++, list[[i]] = func[ list[[i]]] The Table function operating over each part of a list in turn: Table[func[ list[[i]] ], {i, Length[list]}] The Do loop operating over each part of a list in turn: lst = {88, 42, 25, 75, 35, 97, 12}; t = 9; Do[ x = lst[[i]]; t += Mod[x, t], {i, 1, Length[lst]} ]; t Map ping a function onto each element of a list: (3 - #)/(7 * #) & /@ list And for nested lists, there are constructs like MapThread : f = Mod[#, #2] Floor[#3/#] &; a = {{18, 85, 22, 20, 39}, {17, 67, 76, 96, 58}, {40, 97, 56, 60, 53}}; MapThread[f, a] New users of Mathematica will usually pick options 1 or 3 and use C-style or Matlab approaches that involve the following multistep process: Defining an empty list Setting up a loop Optionally define a variable (usually not localised) to equal the iterator, which is then used in subsequent calculations within the loop Within each loop iteration, use the local variable defined to equal the iterator to redefine each element of that list in turn according to some function If the list is multidimensional, nest another loop inside that. What are some useful guides to help users coming from other languages to Mathematica to improve the conciseness and efficiency of their code by avoiding unnecessary loops?
Let's improve the specific cases given. Case #1 Explicit loops are often counterproductive in Mathematica, not only taking more keystrokes, but also more execution time. They are also, in my opinion, more prone to mistakes. Better ways are to use Do , Scan , or Map . Do and Scan are (typically) appropriate for operations that do not accumulate a list of results, while Map and Table (a variant of Do ) are (typically) used for ones that do. The third method uses Map (short form: /@ ) and accumulates a useless list of results; for this reason it is likely to be less memory efficient than the first two. Do[Print[i], {i, 10}] Scan[Print, Range@10] Print /@ Range@10; Average Timing , using PrimeQ in place of Print for 10^6 iterations: Case #2 Since version 6 this form of Table is not necessary! Instead, use: Table[func[i], {i, list}] One might ask why use Table here at all. Indeed, this simple example can be written: func /@ list which is preferred. However, there are more complex cases where Table is far more elegant than the alternatives. Average Timing for 10^6 real numbers using Sin for func: Case #3 This could be improved in the manner of case #2, but there is a far better method available: Fold . Any time you want to iterate through a list, using the result of the previous "loop" along the way, look to Fold , efficient in both syntax and computation. Fold[# + Mod[#2, #] &, 9, lst] Average Timing for 10^6 integers (big savings!): Case #4 There is nothing intrinsically wrong with this. However, all of the operations within the pure function have the Attribute Listable . Therefore, this function can directly accept a list without using Map , and this will be considerably more efficient. (3 - #)/(7 * #) & @ list Average Timing for a list of 10^6 real numbers: Case #5 This is similar to case #4, but a little more complicated. Once again, each subfunction in f is Listable but this is not being leveraged. One can use Apply to pass the sub-lists in a as arguments to f : f @@ a Suppose that not all of the functions are Listable . I create a dummy addition function g that only accepts integers, not lists. I then include this in f , and try to Apply it again: ClearAll[g, f] g[n_Integer, m_Integer] := n + m f = Mod[#, #2] Floor[#3/#] * g[#2, #] &; f @@ a But the result is incorrect. Once could go back to MapThread , but a better way, when possible, is to make g handle lists, which will usually be faster on large sets. Here are two ways of doing that. Give g the Listable attribute, and Mathematica will automatically thread over lists: ClearAll[g, f] SetAttributes[g, Listable] g[n_Integer, m_Integer] := n + m f = Mod[#, #2] Floor[#3/#] * g[#2, #] &; f @@ a Or, if the automatic threading via Listable breaks your function in some way, manually: ClearAll[g, f] g[n_Integer, m_Integer] := n + m g[n_List, m_List] := MapThread[Plus, {n, m}] f = Mod[#, #2] Floor[#3/#] * g[#2, #] &; f @@ a Average Timing for lists of 10^6 integers:
{ "source": [ "https://mathematica.stackexchange.com/questions/7924", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/121/" ] }
8,072
I apologize if this is a obvious question and answer, I don't often use Mathematica to display plots or graphics in general to be honest. So, I was tutoring my cousin yesterday in relation to Polar functions and decided to bring up Mathematica to illustrate some of the ideas we were discussing. I quickly typed a one line command into Mathematica 8 and got an odd result. When rendering a polar function, Mathematica took a few seconds to make it smooth. Prior to this it has too many lines (see picture, before is on left and after is on the right.) The code is: Manipulate[PolarPlot[Sin[nS*t], {t, -5 Pi, 5 Pi}], {nS, 1, 20, 1}] Does anyone know why this is happening and if there is a way to make Mathematica render smooth at first?
This is done intentionally to update the plot quickly as you move the slider. Manipulate changes the setting for PerformanceGoal (via $PerformanceGoal ) to "Speed" while you move the slider, then to "Quality" after you let go. This is seen in this simple demonstration: Manipulate[{n, $PerformanceGoal}, {n, 0, 1}] If you want the final quality while dragging at the expense of update speed you can give an explicit PerformanceGoal -> "Quality" : Manipulate[ PolarPlot[Sin[nS*t], {t, -5 π, 5 π}, PerformanceGoal -> "Quality"], {nS, 1, 20, 1}] Alternatively you can take manual control of this process with ControlActive , and specify the PlotPoints that are used while dragging and after release: Manipulate[ PolarPlot[Sin[nS*t], {t, -5 π, 5 π}, PlotPoints -> ControlActive[50, 150]], {nS, 1, 20, 1}] You can turn off updating while dragging altogether using ContinuousAction : Manipulate[PolarPlot[Sin[nS*t], {t, -5 π, 5 π}], {nS, 1, 20, 1}, ContinuousAction -> False] As belisarius comments you range for t is excessive: {t, -π, π} will not run multiple circuits. This will allow the plot to update much more quickly. I leave the original value in the examples above so that the effect is easier to observe.
{ "source": [ "https://mathematica.stackexchange.com/questions/8072", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1682/" ] }
8,109
I have a function doSomethingComplicated[...] that takes about 10s on average to evaluate. My list, listOfArgs has about 10000 elements. I'd like to monitor the progress of Map[doSomethingComplicated, listOfArgs] without having it ever occupying a big area of the screen. What's best way to do that?
Using MapIndexed , which also gives you the index of the element in the list instead of Map would be very convenient. That way, you can set up a Print or a PrintTemporary cell. For example: Clear[f] f = (Pause[0.2]; PrintTemporary[First@#2]; #^2) &; (* your complicated function *) MapIndexed[f, Range[10]] (* 1 2 ... ... {1, 4, 9, 16, 25, 36, 49, 64, 81, 100} *) With a PrintTemporary cell, it prints all the output, but the cell disappears when the evaluation is complete, saving you the trouble of cleaning the mess. You can also print directly to the messages notebook using the PrintToConsole function from my answer here . This keeps your current working notebook clean and you can always check in the other to see the progress. Another option is to use side-effects and increment a variable, which allows you to use Monitor . For example: Clear[g] g = (Pause[0.2]; i = First@#2 + 1; #^2) &; Block[{i = 1}, Monitor[MapIndexed[g, Range[10]], i]] See this answer by Brett Champion for the different ways in which you can create a progress bar to suit your needs.
{ "source": [ "https://mathematica.stackexchange.com/questions/8109", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/357/" ] }
8,122
I am confused by why Mathematica uses [[3]] to get the 3rd element, or [[i,j] to get the i,j-th element of a 2D array. This seems counter-intuitive. Is this main reason for this to separate array-indexing from function calls? i.e. where I see: f[3, 4] <-- this is currently function call f[[3, 4]] <-- f is a 2D array, and we're accessing 3,4-th element Question : Given that Mathematica knows the type of the arguments, can't it infer: if we're dealing with a function, apply arguments if the object is an array, index it? Thus, why do we need separate [[ ]] notation for array indexing?
In addition to Brett's counter-example, it might be helpful to view this from Mathematica 's philosophy, which is "everything is an expression". In this framework, you're not really indexing a 1D/2D array, but you're extracting a Part from an expression . Indeed, you can use the ⟦ ⟧ notation on any expression, not just lists/matrices. For example: Sin[x + y][[1]] (* x + y *) Graphics[{Red, Disk[]}][[1, 1]] (* RGBColor[1, 0, 0] *) The output of Part on any expression can be viewed as the argument of some function in the FullForm of the expression. For example, breaking down the second example above: Graphics[{Red, Disk[]}][[1]] (* {RGBColor[1, 0, 0], Disk[{0, 0}]} <-- argument of Graphics[] *) Graphics[{Red, Disk[]}][[1, 1]] (* RGBColor[1, 0, 0] <-- argument of List[] *) Graphics[{Red, Disk[]}][[1, 2, 1]] (* {0, 0} <-- argument of Disk[] *) The 0th part is the Head of the entire expression. Since none of the above constitute as being a function call, it makes sense to use a different notation to avoid any ambiguity.
{ "source": [ "https://mathematica.stackexchange.com/questions/8122", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/-1/" ] }
8,142
I have a separable function $f[x,y]$, and I would like to find two functions $g[x]$ and $h[y]$ with $f[x,y]=g[x] h[y]$ where $g[x]$ doesn't depend on $y$ and $h[y]$ doesn't depend on $x$. Ideally, $g$ and $h$ should have the same magnitude, to prevent overflows/underflows. I have a hackish approach that works, but involves a lot of manual labor. Background: $f[x,y]$ is a filter kernel I want to apply to an image, and using two separate 1d-filters is much more efficient. My first approach was to start with $g[x]=f[x,0]$. But that doesn't work for e.g. $f[x,y]=\frac{e^{-\frac{x^2+y^2}{2 \sigma ^2}} x y}{2 \pi \sigma ^6}$ Currently, I have a function that "removes" $x$ or $y$ from $f[x,y]$ using pattern matching: removeSymbol[f_, s_] := f //. {s^_ + a_ -> a, s^_.*a_ -> a} but that means I have to manually adjust this pattern for different f's. Is there a more elegant way to do this? $f[x,y]$ is usually a derivative of a gaussian, e.g. gaussian[x_,y_] := 1/(2 π σ^2) Exp[-((x^2 + y^2)/(2 σ^2))] f[x_,y_] := D[gaussian[x,y], x, y]
I would take a logarithmic derivative with respect to one variable - it should be then independent of the other one, then integrate it back over the first variable and exponentiate. The second function is found by plain division. Here is the code: ClearAll[getGX]; getGX[expr_, xvar_, yvar_] := With[{dlogg = D[Log[expr], xvar] // FullSimplify}, Exp[Integrate[dlogg, xvar]] /; FreeQ[dlogg, yvar]]; Clear[getHY]; getHY[expr_, xvar_, yvar_] := FullSimplify[(#/getGX[#, xvar, yvar]) &[expr]] A test function: ftest[x_, y_] := (x^2 + 1)*y^3 *Exp[-x - y] Now, getGX[ftest[x,y],x,y] (* E^-x (1+x^2) *) getHY[ftest[x,y],x,y] (* E^-y y^3 *) The integration constant ambiguity translates into an ambiguity of how you split the function, since this operation is only defined up to a multiplicative constant factor by which you can multiply one function, and divide the other one.
{ "source": [ "https://mathematica.stackexchange.com/questions/8142", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/242/" ] }
8,147
I'm a newbie who tries to be a good boy, and use Map instead of writing out a list of functions. I have a table I want to Map onto: ratios = Table[10^(n/10), {n, 0, 10}] and a function rp[x_, r_] := 1000 x (r + 1)/(r + x) which I want to Plot for the 11 ratios, for x in [0, 1] : Plot[Map[rp, ratios], {x, 0, 1}] This doesn't work, and I can guess why: rp requires two arguments, and MMA probably doesn't know which one is the ratio. And x also doesn't appear as a parameter. How do I fix this?
You can create a pure function that maps only on ratio as follows: Plot[Map[rp[x, #] &, ratios], {x, 0, 1}, Evaluated -> True] You will need the Evaluated -> True option in order for Plot to view the functions as several different ones and plot them in different colours. You can also bypass having to use Map by creating your function with the Listable attribute. For example: rp2[x_] := Function[{r}, 1000 x (r + 1)/(r + x), Listable] Plot[rp2[x][ratios], {x, 0, 1}, Evaluated -> True] This returns the same output as above, but automatically maps (threads) over lists.
{ "source": [ "https://mathematica.stackexchange.com/questions/8147", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1450/" ] }
8,154
I am a newbie, so please point me in the right direction if you feel this question has been answered somewhere else before. Here goes: Suppose I have a list like this: {{a, b}, {b, c}, {a, b, c}, {a, b, e}, {a, c, e}, {a, e, d, f}} I want to strip this list of all its non-minimal sublists, by which I mean that I want to check whether each set contains a subset that's already somewhere else in the set. So, in this case, the output would need to be: {{a,b},{b,c},{a,c,e},{a,e,d,f}} Where {a,b,c} is dropped either because it contains {a,b} or {b,c} and {a,b,e} is dropped because it contains because it contains {a,b} Edited to add: I have found one solution so far which works like this: list = {{a, b}, {b, c}, {a, b, c}, {a, b, e}, {a, c, e}, {a, e, d, f}} Intersection[DeleteDuplicates[Apply[Intersection, Tuples[list, 2], {1}]], list] which generates the desired result: {{a, b}, {b, c}, {a, b, c}, {a, b, e}, {a, c, e}} What this does: It generates all 2-tuple subsets of the list with itself. Then, the intersection of all these tuples are calculated and all duplicates are deleted. Finally, the resulting list is compared with the original list: the intersection is than the desired result. But: this list has length 6, so the tuple-list is 6^2 = 36. I would like this formula to also work on lists of lengths around 500 to 1000, which would mean the tuple-list is between 250 000 and 1 000 000. If anyone is able to point me to an easier way to do this calculation, I would be very much obliged.
You could do something like minSubsets[lst_] := DeleteDuplicates[SortBy[lst, Length], Intersection[#1, #2] === Sort[#1] &] Then for the example in the question you get lst = {{a, b}, {b, c}, {a, b, c}, {a, b, e}, {a, c, e}, {a, e, d, f}}; minSubsets[lst] (* out: {{a, b}, {b, c}, {a, c, e}, {a, e, d, f}} *)
{ "source": [ "https://mathematica.stackexchange.com/questions/8154", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1708/" ] }
8,199
I've got this code Plot[{(V^2/360)/0.4, ConditionalExpression[(V^2/860)/0.4, V < 12], ConditionalExpression[(V^2/860)/0.4, V > 12]}, {V, 8, 18}, PlotRange -> {0, 1.5}, PlotStyle -> {{AbsoluteThickness[3]}, {AbsoluteThickness[3], Dashed}, { AbsoluteThickness[3], ColorData[1, 2]}}, GridLines -> Automatic, Epilog -> {{Thick, Dashed, Black, Line[{{12, 0}, {12, 2}}]}, {Thick, Dashed, Black, Line[{{8, 1}, {18, 1}}]}}] to plot a function in two pieces, each in a different style: This works OK for me, though I didn't like it that I had to use ColorData[1, 2] to get the second part in the same color. Are there better ways to do this (possibly something with Piecewise )?
Note - this does not work since version 10 I've taken Mr. Wizard's clever trick of using Sequence and I to get both sections of the plot assigned to the same element of PlotStyle , and also used the ability of PlotStyle to take functions as well as graphics directives. First define the functions splitplot and splitstyle : SetAttributes[splitplot, HoldAll]; splitplot[pieces__] := Piecewise[{#}, I] & /@ Unevaluated @ pieces splitplot[{v_, c_}] := splitplot[{v, c}, {v, ! c}] splitstyle[styles__] := Module[{st = Directive /@ {styles}}, {{Last[st = RotateLeft @ st], #}} & ] Usage: splitplot takes pairs of {value, condition} like Piecewise , and is used as the function to be plotted. There can be any number of "pieces" to the plot. If only a single piece is specified, a second piece {value, Not[condition]} will be automatically added. splitstyle takes style directives, which are applied to those pieces. The styles are used cyclically. Each style directive can be a list like {Red, Thick} The splitstyle function can itself be a member of a list, for example {Thick, splitstyle[Red, Blue]} will split the plot into red and blue parts, both of which are thick. An empty list {} can be given to apply the default style with no alterations. Simple example - apply dashing for x<0.5 Plot[{x, splitplot[{x^2, x < 0.5}]}, {x, 0, 1}, PlotStyle -> {Thick, {Thick, splitstyle[Dashed, {}]}}] Note that if the condition describes multiple unconnected regions this will generate multiple "pieces". In the plot below the condition x<2||x>4 produces two pieces, which are assigned to the first two style directives in splitstyle . Plot[splitplot[{x, x < 2 || x > 4}, {13 x - 2 x^2 - 16, 2 < x < 4}], {x, 0, 6}, PlotStyle -> splitstyle[Dashed, Green, Red]] Multiple splitplot and splitstyle can be used in a single Plot Plot[{splitplot[{6 - 2 x, x < 2}, {2 x - 2, x > 2}], splitplot[{2 x, x < 3}, {12 - 2 x, x > 3}]}, {x, 0, 5}, PlotStyle -> {splitstyle[{}, Dashed], splitstyle[Dashed, {}]}]
{ "source": [ "https://mathematica.stackexchange.com/questions/8199", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1450/" ] }
8,215
I have a function running within a Do loop that sometimes issues a warning. I'd like to prepend the warning with the loop ctr so that I can go back and debug that instance later. Basically, I would like to modify the following line, Do[i^0, {i, -1, 1}] so that instead of displaying the warning: Power::indet: Indeterminate expression 0^0 encountered. >> it displays: i=0, Power::indet: Indeterminate expression 0^0 encountered. >> Where i==0 is the iteration that i^0 issues the warning. Thanks
Here is my proposal for tagging messages with (the value of) an arbitrary expression at the time of message generation. The tag is placed inside the the message itself. ClearAll[withTaggedMsg] SetAttributes[withTaggedMsg, HoldAll] withTaggedMsg[exp_, label_: "When"] := Function[, Internal`InheritedBlock[{MessagePacket}, Unprotect @ MessagePacket; mp : MessagePacket[__, _BoxData] /; !TrueQ[$tagMsg] := Block[{$tagMsg = True}, Style[Row[{label, HoldForm[exp], "=", exp, " "}, " "], "SBO"] /. tag_ :> MapAt[RowBox[{ToBoxes @ tag, #}] &, mp, {-1, 1}] // Identity ]; # ], HoldAll] Usage: Do[i^0, {i, -1, 1}] // withTaggedMsg[i] Do[i^0, {i, -1, 1}] // withTaggedMsg[i, "At iteration"] Note: this only works with variables that are either globally accessible or are scoped using Block . For example, f[x_] := Message[f::brains, x] f[5] // withTaggedMsg[x] (* At iteration x = x f::brains: -- Message text not found -- (5) *) Module[{x = 5}, Message[f::brains, x] ] // withTaggedMsg[x] (* At iteration x = x f::brains: -- Message text not found -- (5) *) With[{x = 5}, Message[f::brains, x] ] // withTaggedMsg[x] (* At iteration x = x f::brains: -- Message text not found -- (5) *) Block[{x = 5}, Message[f::brains, x] ] // withTaggedMsg[x] (* At iteration x = 5 f::brains: -- Message text not found -- (5) *) This means that any variable that is scoped using Block can be used to tag a message. So, loop variables from Do and Table are accessible via this method, in addition to any Block variable. This makes it indispensable as a debugging tool.
{ "source": [ "https://mathematica.stackexchange.com/questions/8215", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/803/" ] }
8,226
I was reading some code, in particular, recipe 4.13 on unification pattern-matching in Sal Mangano's Mathematica Cookbook, and there were many instances of Modules with no variables in them, such as Lookup[x_] := Module[{}, x /. $bindings] i didn't understand the point. Why not just write Lookup[x_] := x /. $bindings ? Sal uses such modules frequently, so I'm supposing there is some deep reason I'm missing, hence the question here.
For a single code statement, this is probably an overkill. If you have two or more of them, you have to group them in any case. CompoundExpression is one obvious choice, such as f[x_]:= ( Print[x]; x^2 ) Instead, you could also do f[x_]:= Module[{}, Print[x]; x^2 ] which is what I personally often prefer. Apart from some stylistic preferences, this may make sense if you anticipate that your function will grow in the future, and some local variables will be introduced. EDIT There is a more important point, which was escaping me for a while but which I had on the back of my mind. I will quote Paul Graham here (ANSI Common Lisp, 1996, p.19): When we are writing code without side effects, there is no point in defining functions with bodies of more than one expression. The value of the last expression is returned as the value of the function, but the values of any preceding expressions are thrown away. So, what Module really signals (since it is better recognizable than CompoundExpression ) is a piece of code where side effects are present or expected. And, at least for me, having an easy way to locate such parts in code when I look at it is important, since I try to minimize their presence and, generally, they tend to produce more bugs and problems than side-effects-free code. But, even when they are really necessary, it is good to isolate and clearly mark them, so that you can see which parts of your code are and are not side-effects free.
{ "source": [ "https://mathematica.stackexchange.com/questions/8226", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/387/" ] }
8,241
I have two data sets, data1 and data2 . For example: data1 = {{1, 1.1}, {2, 1.5}, {3, 0.9}, {4, 2.3}, {5, 1.1}}; data2 = {{1, 1001.1}, {2, 1001.5}, {3, 1000.9}, {4, 1002.3}, {5, 1001.1}}; ListPlot[data1, PlotRange -> All, Joined -> True, Mesh -> Full, PlotStyle -> Red] ListPlot[data2, PlotRange -> All, Joined -> True, Mesh -> Full, PlotStyle -> Blue] Their $y$- values are in vastly different regimes, but their oscillations in $y$ are comparable, and I'd like to compare them visually using ListPlot . But if I simply overlay them, it is nearly impossible to see and compare their oscillations, because of the scaling: Show[{ ListPlot[data1, PlotRange -> {{1, 5}, {-100, All}}, Joined -> True, Mesh -> Full, PlotStyle -> Red, AxesOrigin -> {1, -50}], ListPlot[data2, Joined -> True, Mesh -> Full, PlotStyle -> Blue] }] Is there a way to "break" or "snip" the $y$ axis so that I can compare data1 and data2 on the same plot? There is no data in the range ~3 to ~1000, so I would like to snip this $y$-range out, if possible, and perhaps include a jagged symbol to show that this has been done.
Here is a solution that uses a BezierCurve to indicate a "snipped" axes. The function snip[x] places the mark on the axes at relative position x (0 and 1 being the ends). The function getMaxPadding gets the maximum padding on all sides for both plots (based on this answer ). The two plots are then aligned one over the other, with the max padding applied for both. snip[pos_] := Arrowheads[{{Automatic, pos, Graphics[{BezierCurve[{{0, -(1/2)}, {1/2, 0}, {-(1/2), 0}, {0, 1/2}}]}]}}]; getMaxPadding[p_List] := Map[Max, (BorderDimensions@ Image[Show[#, LabelStyle -> White, Background -> White]] & /@ p)~Flatten~{{3}, {2}}, {2}] + 1 p1 = ListPlot[data1, PlotRange -> All, Joined -> True, Mesh -> Full, PlotStyle -> Red, AxesStyle -> {None, snip[1]}, PlotRangePadding -> None, ImagePadding -> 30]; p2 = ListPlot[data2, PlotRange -> All, Joined -> True, Mesh -> Full, PlotStyle -> Blue, Axes -> {False, True}, AxesStyle -> {None, snip[0]}, PlotRangePadding -> None, ImagePadding -> 30]; Column[{p2, p1} /. Graphics[x__] :> Graphics[x, ImagePadding -> getMaxPadding[{p1, p2}], ImageSize -> 400]]
{ "source": [ "https://mathematica.stackexchange.com/questions/8241", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1185/" ] }
8,267
Background My math background is strong by CS standards, probably normal by mathematica standards. (i.e. familiarity with real analysis, linear algebra, managed to read the proof of the prime number theorem :-) ) The goal here is NOT to start a hedge fund of sorts; it's mainly to pick up the basics of financial / stock market background (but it's much more fun when I'm playing with real data / writing programs rather than just reading a textbook.) I want to play around with learning the basics of finance (and writing some serious code in Mathematica). Ideally, I want to "learn by doing" -- i.e. rather than just read textbook formulas, I would like to: play with real world stock data implement the various definitions / algorithms / functions and see how they work Looking around, the best I have found is this book: Computational Financial Mathematics using MATHEMATICA®: Optimal Trading in Stocks and Options Seems like the most highly recommended However, since I'm clueless, I would like to get some feedback (and suggestions for other resources to use for learning.) Thanks!
I own a copy of Modelling Financial Derivatives with Mathematica by William Shaw. I think it was a ground-breaking book for its time. However, here are some issues you should be aware of: It was published in 1998 and is based on Mathematica version 3 . We are now at 8, anticipating 9. Much of the graphics code he uses is now obsolete (eg Graphics`Graphics ). Much of the functionality he builds in the book is now built-in to Mathematica itself. See the list of functions here . Chapter 3 is a nice intro to the mathematical preliminaries of derivatives, but there will be better ones in more recent introductory texts that are not specific to Mathematica. My general concern about both Shaw's book and the subsequent Mathematica implementations of these pricing algorithms is that they are, in the end as far as I can tell, based on an assumption of Gaussian noise in the differential equation defining the pricing equation. This is still the standard approach in many workplaces, but especially since the crisis, the deviation of reality from Gaussian-based models has generated some disquiet in the profession. (This has been directed more at Gaussian copulas than the underlying Black-Scholes model, but it is possible that the industry is going to start moving off in another direction away from the standard methods encapsulated in the Mathematica functionality.) I am not close enough to the recent literature on financial engineering specifically to know exactly how this is playing out yet. I do not own the book by Stojanovic you referenced in your question but looking at the contents pages online, I do not see anything there that is not now included directly in Mathematica with version 8. Again, this book came out in 2002, so it predates Mathematica's finance functionality as well as its dynamic functionality ( Manipulate and friends). And again, it is all based on Black-Scholes and Gaussian noise and doesn't go beyond that to include consideration of fat-tailed innovations. (NB: this is something that Mathestate.com, mentioned in comments, gets right - there is lots of discussion of Levy-stable and other heavy-tailed distributions. So perhaps you are better off starting there than with a book.) I think you will be better off getting a recent book on financial engineering and pricing, and practice implementing things in Mathematica from there, bearing in mind how much is already built in. I particularly admire Janet M Tavakoli on structured finance. To summarise, I don't think there is currently a good book on financial engineering that addresses Mathematica's current functionality, but I would be delighted to be proven wrong. Perhaps this is a market niche for someone. One place you might want to consider for thoughts and ideas is the "Cutting Edge" column in Risk magazine. That stuff is pretty advanced, but it gives you a sense of where practitioners, rather than academics, are going. Also have a look at the sister SE for Quantitative Finance , but note that software questions are offtopic there, at least last time I looked.
{ "source": [ "https://mathematica.stackexchange.com/questions/8267", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/-1/" ] }
8,287
If I have: Graphics[ {Red, EdgeForm[Directive[White, Thick]], Inset[Style[Text@"Hi!", 44], {0, 0}]}, Background -> Black ] I unfortunately get: Which as you can see does not have a thick white outline. Is there a way to get around this since EdgeForm clearly does not work? By the way, I would rather NOT delve into making a larger, white "Hi" and then putting the red one on top. That's just not elegant. MMA 8.0.1 for students OS Windows 7 64-bit
Import text as a FilledCurve in graphics, using PDF as an intermediate format. Below are modified examples from Documentation Center : text = First[First[ImportString[ExportString[Style["Hi", Italic, FontSize -> 24, FontFamily -> "Times"], "PDF"], "PDF", "TextMode" -> "Outlines"]]]; Outline fonts using different edge and face forms: Graphics[{EdgeForm[Directive[White, Thick]], Red, text}, Background -> Black, PlotRange -> {{-5, 25}, {-0, 20}}] 3D text effect: Graphics[{EdgeForm[Opacity[0.5]], Table[{ColorData["TemperatureMap"][t], Translate[text, 4 {-t, t}]}, {t, 0, 1, 1/10}]}, ImageSize -> Medium]
{ "source": [ "https://mathematica.stackexchange.com/questions/8287", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1611/" ] }
8,304
I can't get my email settings set properly such that I can use SendMail[] to email directly from Mathematica . I have opened "Preferences", clicked on the tab "Internet Connectivity" and filled in all the settings to match those in my Apple Mail accounts settings. These include: Server Port Number Encryption Protocol Username From Address Full Name Reply To Odd that no setting exists for "Password"? The "Preference" window's "Test Internet Connectivity" tells me "Test succeeded..." Apple Mail has a setting to "Use default ports (25, 465, 587)" so I thought this might confuse the Mathematica settings, so I've tried setting the Apple Mail settings to "Use Custom Port" and specified each of the the default ports specifically. None of those settings worked either. I have also attempted to specify all available options for SendMail[] specifically also trying each of the 3 possible "default" ports described above. SendMail[ "From" -> "[email protected]", "To" -> "[email protected]", "Subject" -> "Example Message", "Body" -> "Test", "Server" -> "smtpout.secureserver.net", "EncryptionProtocol" -> "SSL", "FullName" -> "MyUserName", "Password" -> "myPassword", "PortNumber" -> 25 (* I also tried 465, 587 *), "ReplyTo" -> None, "ServerAuthentication" -> Automatic, "UserName" -> "myUserName" ] Again SendMail[] gives me the same message: $Failed . Also, in the "Preferences" window under the "Proxy Settings" tab I have tried selecting both "User proxy settings from my system or browser" and "Direct connection to the Internet". The " Troubleshooting Internet Connectivity Problems " in the "Document Center" suggests checking proxy settings. Given what mine look like in Snow Leopard's "Preferences" ► "Network" ► "Proxies": I don't think I have much to help. I have no Firewall Setting on the computer. This has me stumped. Does anyone have an idea of what else I can try.
This might not work for you but is an example to use the Gmail mail server to send emails from a notebook. The example code overrides all settings in the MMa email preference settings and should work out of the box. NB I have tested this only on my Mac. SendMail[ "To" -> "[email protected]", "Subject" -> "Example Message", "Body" -> "My text", "From" -> "[email protected]", "Server" -> "smtp.gmail.com", "UserName" -> "[email protected]", "Password" -> Automatic, "PortNumber" -> 587, "EncryptionProtocol" -> "StartTLS" ]
{ "source": [ "https://mathematica.stackexchange.com/questions/8304", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/571/" ] }
8,310
Background: I have used Vim for 15+ years. There is a certain "one"-ness with the editor one achieves. Emacs users also experience this. Notepad users do not. My current interaction with the Mathematica notebook is at the Notepad level. This is very frustrating because: the Mathematica engine is very powerful I'm so slow that I'm thinking faster than I can type or move, which is weird Goal: I want to become much more efficient at interacting with Mathematica . Hitting a productive level in Vim took me 2 books + a month of internalizing key bindings and consciously developing habits. I am willing to invest similar efforts for Mathematica . However, I'd like to invest the effort into the right habits. Here's a bunch of simple things I can't do (not exhaustive list) % in Vim to move around () , {} [] pairs dw to delete a word / to search + jump around the file hjkl movement keys and much more I'm not even aware of Questions: How do I become more efficient at keyboard interaction with Mathematica ? Is using the notebook (I'm using Mathematica 8) the right interface, or should I be setting up some up some type of Mathematica-REPL + editing in Vim + sending it over to the Mathematica-REPL over tcp / unix socket? [Like SLIME for Lisp]. How do Mathematica wizards operate? My goal is NOT to make Mathematica feel like Vim. The goal is to learn how to master / communicate efficiently with Mathematica Any other tips for becoming more efficient at interacting with Mathematica
The first step would be to not think of Mathematica 's notebook editor as a full-fledged editor, but rather as an interactive interface with the kernel that has some editing capabilities, perhaps at par with notepad. If you don't, you'll always be disappointed. The Mathematica editor: As with all editors, you'll have to grok the editor before you can be productive in it (for various definitions of productive). Some shortcuts that will help you in writing code faster or in moving around faster are: Enter matching [] , () , {} with Command Option ] , Command Option ) , Command Option } respectively. Use the modifications in this answer for shortcuts to [enter Part brackets: 〚〛 . With these, matching 〚〛 are entered with Ctrl Command ] . Using Ctrl . to select groups of expressions. Starting at any point in the expression, repeatedly pressing this will select successive groups in the expression. This might be something that you'll end up using a lot, and it also helps you visualize the precedence, etc. As an example, try placing your cursor at foo in the following dummy example and repeatedly press the shortcut. You should see something like below: f[a_, b_, c_] := a ~foo~ b + c // bar Use Ctrl Shift → and Ctrl Shift ← to extend the selection token-wise right or left. Use Command K to autocomplete symbols (or show a list of possible symbols) and Command Shift K to autocomplete with placeholders for the possible arguments. For example, you'll get the following for Plot and you can press Tab to move through them. See this answer to change the shortcut key to something else. Use Command / to comment/uncomment a selection (that you selected either manually or with Ctrl . ) Avoid using subscripts, no matter how high the temptation to make your expressions look more "mathy". Apart from slowing you down, you'll run into several issues if you're not careful, and even then, all bets are off. Ctrl ↑ and Ctrl ↓ scrolls up/down in steps of 3 lines, but the cursor remains in the same position. This is helpful if you want to quickly look at a previous cell and continue typing (thanks to Halirutan for the tip). However, these keys are by default mapped to other exposé actions on a Mac, so this won't work. Shift ↑ and Shift ↓ when inside a cell, selects the cell contents to the left or to the right respectively, till it wraps up exactly a line above or below your current line. Shift ↑ and Shift ↓ when outside a cell, selects the cell up or down. Further pressing up/down selects the previous/next cell and holding Shift while you do that will select multiple cells. You can also select a cell by clicking on its cell-bracket on the right. I don't know of a simple way to exit cell editing mode to cell selection mode (using only the keyboard) other than by repeatedly pressing Shift ↑ (or down) till you reach the beginning/end of the cell, followed by up or down (this makes the cursor horizontal, which is cell selection/creation mode). The opposite is easy — you can go from a selected cell to editing it by simply pressing ← . Jens mentions that a few emacs shortcuts work out of the box. For example, Ctrl A/E for moving to the beginning/end of line, Ctrl P/N to move up/down a line (this also crosses from cell editing to cell selection mode) and Ctrl D to delete forward. You can divide cells at the cursor with Command Shift D and merge multiple cells with Command Shift M Learn the various styling shortcuts. See what the shortcuts Command 1—9 (1 through 9) do. This list could go on, so I'll stop here unless I think of something that is very essential to add to the list. If you also use the notebooks for taking notes, typesetting math, etc., you might also want to learn the various input aliases and other shortcuts, some of which are on this page . The simplest way to find an existing shortcut for a function is to go to the function's documentation page. You can also create your own input aliases ( Esc — Esc syntax) following my answer here . Also see this answer , especially the link to a PDF at the bottom, which shows how fast one can be if they master the formatting and typesetting shortcuts (those notes were taken in realtime). The Workbench editor: Compared to the Mathematica notebook, the Workbench editor is rather inert. There is no connection to a kernel and you cannot evaluate your expressions as you go. The familiar input aliases which were quite handy in your notebook interface cannot be entered here. So you will have to resort to a more verbose form of coding. The advantage is that the Workbench is based on the Eclipse IDE, and so you can use plugins that were designed for Eclipse with the Workbench. I was recently introduced to the viPlugin for the Workbench by Rolf Mertig, and it turns the Workbench into a modal editor (I haven't used it).
{ "source": [ "https://mathematica.stackexchange.com/questions/8310", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/-1/" ] }
8,315
I have a plot and I would like to annotate some mathematical text in it. Initially, Mathematica puts it in italics by using Drawing tools palette, but I want it all in plain text. How can I do it? Thanks for your time.
The first step would be to not think of Mathematica 's notebook editor as a full-fledged editor, but rather as an interactive interface with the kernel that has some editing capabilities, perhaps at par with notepad. If you don't, you'll always be disappointed. The Mathematica editor: As with all editors, you'll have to grok the editor before you can be productive in it (for various definitions of productive). Some shortcuts that will help you in writing code faster or in moving around faster are: Enter matching [] , () , {} with Command Option ] , Command Option ) , Command Option } respectively. Use the modifications in this answer for shortcuts to [enter Part brackets: 〚〛 . With these, matching 〚〛 are entered with Ctrl Command ] . Using Ctrl . to select groups of expressions. Starting at any point in the expression, repeatedly pressing this will select successive groups in the expression. This might be something that you'll end up using a lot, and it also helps you visualize the precedence, etc. As an example, try placing your cursor at foo in the following dummy example and repeatedly press the shortcut. You should see something like below: f[a_, b_, c_] := a ~foo~ b + c // bar Use Ctrl Shift → and Ctrl Shift ← to extend the selection token-wise right or left. Use Command K to autocomplete symbols (or show a list of possible symbols) and Command Shift K to autocomplete with placeholders for the possible arguments. For example, you'll get the following for Plot and you can press Tab to move through them. See this answer to change the shortcut key to something else. Use Command / to comment/uncomment a selection (that you selected either manually or with Ctrl . ) Avoid using subscripts, no matter how high the temptation to make your expressions look more "mathy". Apart from slowing you down, you'll run into several issues if you're not careful, and even then, all bets are off. Ctrl ↑ and Ctrl ↓ scrolls up/down in steps of 3 lines, but the cursor remains in the same position. This is helpful if you want to quickly look at a previous cell and continue typing (thanks to Halirutan for the tip). However, these keys are by default mapped to other exposé actions on a Mac, so this won't work. Shift ↑ and Shift ↓ when inside a cell, selects the cell contents to the left or to the right respectively, till it wraps up exactly a line above or below your current line. Shift ↑ and Shift ↓ when outside a cell, selects the cell up or down. Further pressing up/down selects the previous/next cell and holding Shift while you do that will select multiple cells. You can also select a cell by clicking on its cell-bracket on the right. I don't know of a simple way to exit cell editing mode to cell selection mode (using only the keyboard) other than by repeatedly pressing Shift ↑ (or down) till you reach the beginning/end of the cell, followed by up or down (this makes the cursor horizontal, which is cell selection/creation mode). The opposite is easy — you can go from a selected cell to editing it by simply pressing ← . Jens mentions that a few emacs shortcuts work out of the box. For example, Ctrl A/E for moving to the beginning/end of line, Ctrl P/N to move up/down a line (this also crosses from cell editing to cell selection mode) and Ctrl D to delete forward. You can divide cells at the cursor with Command Shift D and merge multiple cells with Command Shift M Learn the various styling shortcuts. See what the shortcuts Command 1—9 (1 through 9) do. This list could go on, so I'll stop here unless I think of something that is very essential to add to the list. If you also use the notebooks for taking notes, typesetting math, etc., you might also want to learn the various input aliases and other shortcuts, some of which are on this page . The simplest way to find an existing shortcut for a function is to go to the function's documentation page. You can also create your own input aliases ( Esc — Esc syntax) following my answer here . Also see this answer , especially the link to a PDF at the bottom, which shows how fast one can be if they master the formatting and typesetting shortcuts (those notes were taken in realtime). The Workbench editor: Compared to the Mathematica notebook, the Workbench editor is rather inert. There is no connection to a kernel and you cannot evaluate your expressions as you go. The familiar input aliases which were quite handy in your notebook interface cannot be entered here. So you will have to resort to a more verbose form of coding. The advantage is that the Workbench is based on the Eclipse IDE, and so you can use plugins that were designed for Eclipse with the Workbench. I was recently introduced to the viPlugin for the Workbench by Rolf Mertig, and it turns the Workbench into a modal editor (I haven't used it).
{ "source": [ "https://mathematica.stackexchange.com/questions/8315", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1309/" ] }
8,382
Context I'm writing a function that look something like: triDiagonalQ[mat_] := MapIndexed[ #1 == 0 || Abs[#2[[1]]-#2[[2]]] <= 1 &, mat, {2}] // Flatten // And @@ # & Now, things like #2[[1]] and #2[[2]] are somewhat hard to read. I'd prefer to do something like: triDiagonalQ[mat_] := MapIndexed[ #1 == 0 || Abs[i-j] <= 1 &, mat, {2}] // Flatten // And @@ # & (* with a {i, j} <- #2 somewhere *) Question Is there someway to do something like "destructuring" in Mathematica ? The following links convey what I mean by "destructuring": http://clojure.org/special_forms http://java.dzone.com/articles/clojure-destructuring http://blog.jayfields.com/2010/07/clojure-destructuring.html (These have nothing to do with Mathematica ; they're posted mainly to demonstrate what is meant by "destructuring")
You can use macros / code generation to be able to use the syntax you like. Here is one possibility: ClearAll[withLiteralIndices]; SetAttributes[withLiteralIndices, HoldAll]; withLiteralIndices[code_, inds : {__Symbol}] := Block[inds, Unevaluated[code] /. MapIndexed[ Function[{i, pos}, pos /. {p_} :> (i :> #2[[p]])], inds ] ] Now, you can pretty much literally use the code you would like to use: withLiteralIndices[ triDiagonalQ[mat_] := MapIndexed[#1 == 0 || Abs[i - j] <= 1 &, mat, {2}] // Flatten // And @@ # &, {i, j} ] When you look at the resulting definition, you can see that this is entirely equivalent to hand-written code using slots: ?triDiagonalQ (* Global`triDiagonalQ triDiagonalQ[mat_]:= (And@@#1&)[Flatten[MapIndexed[#1==0||Abs[#2[[1]]-#2[[2]]]<=1&,mat,{2}]]] *) EDIT Here is a simpler and perhaps more elegant version of the macro, which uses the injector pattern more explicitly: ClearAll[withLiteralIndices]; SetAttributes[withLiteralIndices, HoldAll]; withLiteralIndices[code_, inds : {__Symbol}] := Block[inds, Unevaluated[code] /. Replace[ Range[Length[inds]], p_ :> (inds[[p]] :> #2[[p]]), {1} ] ]
{ "source": [ "https://mathematica.stackexchange.com/questions/8382", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/-1/" ] }
8,438
Update: While at the time of writing the question loading DLLs with .NET/Link seemed easier, now I always use LibraryLink , which I recommend to anyone with a similar problem! As of Mathematica 8, what is the minimal effort way to integrate an existing C++ function into Mathematica? I think we have these: MathLink (it was quite long ago I used it last time) communication through pipes/files ( Import is slow, ReadList not so much) LibraryLink (??) Mathematica 8's C code generation features (??) (apparently this is not relevant) The keyword here is minimal effort . Which is the most convenient way, including the learning curve for the particular method? I'm mainly interested in doing it on Windows. My particular function computes a long list of real numbers. The function input consists only of a few scalars ( int & double ). An answer of the type "You'll likely spend the least time if you use technology X " is useful. A concrete example of how to do it using a small function is even better. Answers Each and every answer I got is great, and each demonstrates a different technology. It's impossible to choose a definitive one. Here's a small "table of contents" for them: MathLink Read result from pipes, pass arguments on command line to separate process LibraryLink Using .NETLink for loading functions from arbitrary DLLs A presentation about the topic from the Wolfram Technology Conference is here (CDF file). Experiences I used two of these methods: the .NETLink method and Library Link. These are my personal experiences: .NETLink This was easy to set up, however, I'd recommend it only for when you already have a compiled DLL from which you need to load functions ( e.g. do something like this ). If you compile your own DLL: once the DLL is loaded, it is locked and cannot be overwritten. A quick and dirty way to allow overwriting it is realoding NETLink with ReinstallNET[] . Advantages: Very quick and easy, only Mathematica code is needed if the functions are already compiled into a DLL. Disadvantages: Windows-only, does not parallelize from within Mathematica, and the calculation will not be interruptible. Library Link It's much easier to use this than what it looks like at first. Less setup is needed than in the case of MathLink, and compilation is automated from within Mathematica. Advantages: Also quite easy, but both Mathematica and C code are needed. It is parallelizable, and easily made interruptible . The library can be unloaded (for recompilation) using LibraryUnload .
Update: I posted a tutorial series on LibraryLink at Wolfram Community . Update: LibraryLink example code is also available on this GitHub repository . Here is my pitch to use LibraryLink , which is a really nice new technology in version 8. I am not going to pretend this is easy by any stretch of the imagination, because it involves a decent amount of knowledge of both Mathematica and C compilers. In this particular case I am using Visual Studio C++ Express plus the Microsoft Windows SDK 7.1 . For the record, I had quite a bit of help from Joel Klein with this answer. LibraryLink is set up to find most compilers on your system, but in my case I had to restart after installing the above tools (although looking back I think restarting my open frontend might have done the trick as well). There are several examples of how to use LibraryLink in the documentation, but this example I wrote from scratch. All LibraryLink C code is compiled with the CreateLibrary function (which is located in the CCompilerDriver package. Mathematica side I'll skip the source for now, and focus on the Mathematica commands. First we loads the package to run the library link utility functions: Needs["CCompilerDriver`"] Next, we load the source file and create a library (.dll) from it: myLibrary = CreateLibrary[{"c:\\users\\arnoudb\\myLibrary.c"}, "myLibrary", "Debug" -> False]; Next, we load the one function defined in this library: myFunction = LibraryFunctionLoad[myLibrary, "myFunction", {{Real, 2}}, {Real, 2}]; Next we use this function: myFunction[{{1, 2, 3, 4}, {5, 6, 7, 8}}] which returns the square of every matrix entry: {{1., 4., 9., 16.}, {25., 36., 49., 64.}} . Finally, we unload the library (needed if we make changes to the source file and reload everything above): LibraryUnload[myLibrary]; C side There is a lot of boiler plate magic, to make things 'work'. These first four line need to always be included: #include "WolframLibrary.h" DLLEXPORT mint WolframLibrary_getVersion(){return WolframLibraryVersion;} DLLEXPORT int WolframLibrary_initialize( WolframLibraryData libData) {return 0;} DLLEXPORT void WolframLibrary_uninitialize( WolframLibraryData libData) {} This is the actual function that you write. The function header is always the same, you get the actual function arguments from the MArgument_* api functions: DLLEXPORT int myFunction(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res){ int err; // error code MTensor m1; // input tensor MTensor m2; // output tensor mint const* dims; // dimensions of the tensor mreal *data1; // actual data of the input tensor mreal *data2; // data for the output tensor mint i; // bean counters mint j; This gets the input tensor and dimensions and sets up the output tensor and actual data: m1 = MArgument_getMTensor(Args[0]); dims = libData->MTensor_getDimensions(m1); err = libData->MTensor_new(MType_Real, 2, dims,&m2); data1 = libData->MTensor_getRealData(m1); data2 = libData->MTensor_getRealData(m2); The actual interesting stuff, this squares each element: for(i = 0; i < dims[0]; i++) { for(j = 0; j < dims[1]; j++) { data2[i*dims[1]+j] = data1[i*dims[1]+j]*data1[i*dims[1]+j]; } } This set the return value (and yes, you don't want to return the 'err' value here): MArgument_setMTensor(Res, m2); return LIBRARY_NO_ERROR; }
{ "source": [ "https://mathematica.stackexchange.com/questions/8438", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/12/" ] }
8,454
In the KnotData package a simple command such as points = Table[KnotData[{3, 1}, "SpaceCurve"][t], {t, 0, 2 Pi, 0.1}]; will generate a series of points that comprise a knot (here, a trefoil, if successive points are connected). However, the distance between points is not constant; is there a way to generate evenly spaced points? (I.e. evenly spaced arc lengths between points).
I'm going to brute force it numerically. First, let's define the function we're interested in: fun = KnotData[{3, 1}, "SpaceCurve"] Imagine that this function fun[t] describes the position of a moving point in time. The the magnitude of its velocity as a function of the time t is Sqrt[#.#] & [fun'[t]] I'm going to make an interpolating function out of this to speed up and simplify the numerical calculations: v = FunctionInterpolation[Sqrt[#.#] & [fun'[t]], {t, 0, 2 Pi}] The integral (antiderivative) of this function will give us the distance covered as a function of time. dist = Derivative[-1][v] This is a monotonically increasing function, so it can be inverted: invdist = InverseFunction[dist] Using the inverse we can generate the times at which the point passes through the equally spaced points. Let's divide the curve into 20 equal-length segments: times = Table[invdist[x], {x, 0, dist[2 Pi], dist[2 Pi]/20}] Now we can easily plot the equally spaced points: Show[ ParametricPlot3D[fun[t], {t, 0, 2 Pi}, PlotStyle -> Black], ListPointPlot3D[fun /@ times, PlotStyle -> Directive[PointSize[0.02], Red]] ]
{ "source": [ "https://mathematica.stackexchange.com/questions/8454", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1757/" ] }
8,482
I'm plotting gear curves , and I observe that for some parameter values ParametricPlot[] does not plot all the teeth: gearCurve[a_, b_, n_] := ParametricPlot[ { (a + 1/b Tanh[b Sin[n t]]) Cos[t], (a + 1/b Tanh[b Sin[n t]]) Sin[t] }, {t, 0, 2 Pi}, Axes -> False]; gearCurve[10, 5, 38] produces the following image: What is going on?
Yaroslav Bulatov posted a great answer addressing this problem on StackOverflow. Among several good illustrations the answer includes this undocumented option: Method -> {Refinement -> {ControlValue -> (*radians*) }} Alexey Popkov also gave an excellent analysis of the Plot algorithm. His answer includes the apparently equivalent but cleaner (in degrees rather than radians as above): Method-> {MaxBend -> (*degrees*) } Example: gearCurve[a_, b_, n_] := ParametricPlot[ {(a + 1/b Tanh[b Sin[n t]]) Cos[t], (a + 1/b Tanh[b Sin[n t]]) Sin[t]}, {t, 0, 2 Pi}, Axes -> False, Method-> {MaxBend -> 1} ]; gearCurve[10, 5, 38]
{ "source": [ "https://mathematica.stackexchange.com/questions/8482", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1351/" ] }
8,507
The question is how can we use Mathematica to create vectorized versions of low-resolution images? The goal is to get an image suitable for quality printing at any resolution. Since "true" vectorization performed by various specialized software is a tough problem, I suggest to consider "artistic" approaches, which produce inexact, but beautiful version of the original. Colored implementations are highly appreciated.
Let's get a low-res image: And put in in gray-scale mode: gimg = ColorConvert[ImageResize[ Import["http://i.stack.imgur.com/wtgxH.jpg"], 300], "Grayscale"]; Now extract the image data (pixel values) together with pixel indexes: data = MapIndexed[Append[#2, #1] &, ImageData[gimg], {2}]; I, of course, couldn't pass on Voronoi styling. We will add random noise to perfectly integer pixel coordinates and make a mosaic animation: Table[Rotate[ListDensityPlot[(MapThread[Append, {3 RandomReal[{-1, 1}, {Length[#], 2}], ConstantArray[0, Length[#]]}] + #) &@Flatten[Transpose@data, 1][[1 ;; -1 ;; 15]], InterpolationOrder -> 0, ColorFunction -> "GrayTones", BoundaryStyle -> Directive[Black, Opacity[.2]], Frame -> False, PlotRangePadding -> 0, AspectRatio -> Automatic, ImageSize -> 600], -Pi/2], {10}]; Export["test.gif", %] And various outlandish coloring Grid[Partition[Rotate[ListDensityPlot[(MapThread[ Append, {3 RandomReal[{-1, 1}, {Length[#], 2}], ConstantArray[0, Length[#]]}] + #) &@ Flatten[Transpose@data, 1][[1 ;; -1 ;; 45]], InterpolationOrder -> 0, ColorFunction -> #, BoundaryStyle -> Directive[Black, Opacity[.2]], Frame -> False, PlotRangePadding -> 0, AspectRatio -> Automatic, ImageSize -> 300], -Pi/2] & /@ {"CherryTones", "CoffeeTones", "DarkRainbow", "DeepSeaColors", "PlumColors", "Rainbow", "StarryNightColors", "SunsetColors", "ValentineTones"}, 3], Spacings -> 0] If we fix the noise sampling with SeedRandom and change only magnitude of the noise, we can create a sort of order-from-chaos appearance effect: id = ParallelTable[Rotate[ListDensityPlot[(MapThread[ Append, {SeedRandom[1]; 200 (1 - st^(1/8)) RandomReal[{-1, 1}, {Length[#], 2}], ConstantArray[0, Length[#]]}] + #) &@ Flatten[Transpose@data, 1][[1 ;; -1 ;; 15]], InterpolationOrder -> 0, ColorFunction -> GrayLevel, BoundaryStyle -> Opacity[.1], Frame -> False, PlotRangePadding -> 0, AspectRatio -> Automatic, ImageSize -> 350], -Pi/2], {st, 0.2, 1, .05}]; idd = id~Join~Table[id[[-1]], {7}]; Export["appear.gif", idd, ImageSize -> 350]
{ "source": [ "https://mathematica.stackexchange.com/questions/8507", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/219/" ] }
8,586
I am trying to use the Export command to convert a list of plots into a *.gif file, and the command runs and executes well, but I can't find the file! Where is it supposed to go? Did it even work? Here is my code : q[n_, x_] := x (1 + x)^n + x^n; points = Table[ Map[{Re[#], Im[#]} &, Flatten[NSolve[q[n, x] == 0, x][[All]] /. Rule -> (#2 &)]], {n, 1, 20}]; Export["domniationrootsstargraph.gif", Table[ListPlot[points[[i]], PlotRange -> {{-15, 4}, {-10, 10}}], {i, 1, 20, 1}] ] Thanks in advance =)
Easy to check: Directory[] Which in my case on Win7 gives: "C:\Users\vitaliyk\Documents" You can always specify a complete path to a destination you'd like to save with, for example, top menu Insert >> FilePath which will bring a standard browse-directory window: This would go instead of your "domniationrootsstargraph.gif" . A useful trick to know is command SetDirectory[NotebookDirectory[]] which will allow saving your files by default (without full-path specification) into the directory where your notebook is saved. Also to check files in the CurrentDirectory use FileNames[] or, for example, FileNames["*.gif"] for specific file types.
{ "source": [ "https://mathematica.stackexchange.com/questions/8586", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1785/" ] }
8,614
This past semester I taught an introductory electromagnetism course and had quite a nice time using Mathematica to draw all sorts of figures and diagrams (mostly for problems and etc.). However, I was unable to create a nice environment for the basic circuit elements such as resistors, capacitors, etc. A Resistor, for instance, was annoying to draw a single one by hand. But after that, ideally, I would have liked to have a function Resistor[{p1,p2}] which functions exactly like the Line function but gives a line with a resistor in it (labels are not necessary since they can easily be added latter with the Text function). This function could then be readily generalized to a function CircuitElement[{p1,p2},element] where "element" stands for any element one has previously drawn. I have had quite some difficulty with these kinds of functions, perhaps due to my lack of knowledge on computational geometry. I think this kind of functionality might be of interest to many people. So, any thoughts or tips on how to get started? Additionally I would like to have output that is similar to the following:
I dug up some simple analog circuit design definitions that I sometimes use to make diagrams for classes or problem sets. Mathematica is obviously very useful when you have to create iterative copies of circuit elements, as in this example (a chain of resistor-capacitor elements): Since this is for teaching purposes and not professional, you may forgive the slight deviations from engineering standards in the definitions that follow. First: to explain how I specify such circuits, here is the syntax that generated the above picture: display[ Table[ rcElement // at[{i, 0}], {i, 0, 17, 3}] ] To elaborate on this, first note the at statement. It is universally used to specify the 2D position and (optionally) orientation of the circuit element that precedes it. The circuit element can be a composite object, as it is here in the form of rcElement - the repeating unit of the example. To make a composite element, you need basic building blocks. Here are a few. The first two are the simplest possible: a connecting wire ( connect ) and a gap in a wire, i.e. an interruption where something else can be placed in the path of the wire: gap . connect[pointList_] := {Line[pointList], Map[Text[Style[ "\!\(\*AdjustmentBox[\(\[Bullet]\),\n\ BoxBaselineShift->0.24615384615384617`,\nBoxMargins->{{0., 0.}, \ {-0.24615384615384617`, 0.24615384615384617`}}]\)", FontSize -> 18], #] &, pointList[[{1, -1}]]]} gap[l_: 1] := Line[l {{{0, 0}, {1/3, 0}}, {{2/3, 0}, {1, 0}}}] The next definitions should be self-explanatory by their names: resistor[l_: 1, n_: 3] := Line[Table[{i l/(4 n), 1/3 Sin[i Pi/2]}, {i, 0, 4 n}]] coil[l_: 1, n_: 3] := Module[{ scale = l/(5/16 n + 1/2), pts = {{0, 0}, {0, 1}, {1/2, 1}, {1/2, 0}, {1/2, -1}, {5/ 16, -1}, {5/16, 0}} }, Append[ Table[BezierCurve[scale Map[{d 5/16, 0} + # &, pts]], {d, 0, n - 1}], BezierCurve[scale Map[{5/16 n, 0} + # &, pts[[1 ;; 4]]]] ] ] capacitor[l_: 1] := {gap[l], Line[l {{{1/3, -1}, {1/3, 1}}, {{2/3, -1}, {2/3, 1}}}]} battery[l_: 1] := {gap[ l], {Rectangle[l {1/3, -(2/3)}, l {1/3 + 1/9, 2/3}], Line[l {{2/3, -1}, {2/3, 1}}]}} contact[l_: 1] := {gap[l], Map[{EdgeForm[Directive[Thick, Black]], FaceForm[White], Disk[#, l/30]} &, l {{1/3, 0}, {2/3, 0}}]} These all create graphics directives which can receive an optional argument l that sets their length (and will cause them to scale if l is different from 1 ). Now I need some commands to glue things together and display them: Options[display] = {Frame -> True, FrameTicks -> None, PlotRange -> All, GridLines -> Automatic, GridLinesStyle -> Directive[Orange, Dashed], AspectRatio -> Automatic}; display[d_, opts : OptionsPattern[]] := Graphics[Style[d, Thick], Join[FilterRules[{opts}, Options[Graphics]], Options[display]]] at[position_, angle_: 0][obj_] := GeometricTransformation[obj, Composition[TranslationTransform[position], RotationTransform[angle]]] label[s_String, color_: RGBColor[.3, .5, .8]] := Text@Style[s, FontColor -> color, FontFamily -> "Geneva", FontSize -> Large]; If I haven't forgotten anything, this should now be sufficient to draw some basic circuits: display[{ battery[] // at[{0, 0}, Pi/2], connect[{{0, 1}, {0, 2}, {2, 2}}], resistor[] // at[{2, 2}], connect[{{3, 2}, {4, 2}, {4, 1}}], coil[] // at[{4, 0}, Pi/2], connect[{{4, 0}, {4, -1}, {3, -1}}], capacitor[] // at[{2, -1}], connect[{{2, -1}, {0, -1}, {0, 0}}] } ] I forgot the switch, but you get the idea. Try replacing the battery by a contact to see how it works. Coming back to the circuit at the beginning, what I did there is to repeat the following composite element several times: rcElement = {connect[{{0, 2}, {1, 2}}], resistor[] // at[{1, 2}], connect[{{2, 2}, {3, 2}, {3, 1}}], capacitor[] // at[{3, 0}, Pi/2], connect[{{3, 0}, {3, -1}, {0, -1}}] }; There is no limit as to the circuit elements you can define, of course. The main thing is that you need a convention for where their input and output terminals are. The placement with the at command defined above is very convenient for creating circuits textually, I think - at least once you get used to visualizing the coordinate system. That's why I draw the grid lines to help me visualize the correct placement. Edit I've updated the definition of display to accept all the options that are valid for Graphics . Also, here are some more definitions: a switch, ammeter and voltmeter. The illustration below also uses the label function that was already included in my original post: switch[l_: 1] := {Line[{{0, 0}, {1/10, 0}, {1/10, 0} + 4/5 {1/Sqrt[2], 1/Sqrt[2]}}], Line[{{9/10, 0}, {1, 0}}], Map[{EdgeForm[Directive[Thick, Black]], FaceForm[White], Disk[#, l/30]} &, l {{1/10, 0}, {9/10, 0}}]} meter[l_: 1] := {Line[{{0, 0}, {1/10, 0}}], Line[{{9/10, 0}, {1, 0}}], {EdgeForm[Directive[Black]], FaceForm[White], Disk[{l/2, 0}, 2/5 l]}} ammeter[l_: 1] := {meter[] // at[{0, 0}], label["A", Black] // at[{l/2, 0}]} voltmeter[l_: 1] := {meter[] // at[{0, 0}], label["V", Black] // at[{l/2, 0}]} display[{ switch[] // at[{0, 0}, Pi/2], connect[{{0, 1}, {0, 2}, {2, 2}}], resistor[] // at[{2, 2}], connect[{{3, 2}, {4, 2}, {4, 1}}], coil[] // at[{4, 0}, Pi/2], connect[{{4, 0}, {4, -1}, {3, -1}}], connect[{{0, 0}, {0, -1}, {1/2, -1}}], battery[] // at[{1/2, -1}], connect[{{3/2, -1}, {2, -1}}], ammeter[] // at[{2, -1}], connect[{{4, 2}, {6, 2}, {6, 1}}], connect[{{4, -1}, {6, -1}, {6, 0}}], capacitor[] // at[{6, 0}, 90 Degree], label["L"] // at[{4.5, 1.2}], label["C"] // at[{6.5, 1.2}], label["R"] // at[{1.5, 2.5}] }, GridLines -> None, Frame -> False, ImageSize -> 500 ]
{ "source": [ "https://mathematica.stackexchange.com/questions/8614", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/347/" ] }
8,637
Usually, when I plot multiple curves in Mathematica Plot[{x,x^2,x^3},{x,0,1}] they are given different colors. However, if I try to construct a list inside the Plot[] function, Plot[Table[x^n, {n, 1, 3}], {x, 0, 1}] this doesn't work and all the curves come out the same color. The standard advice (e.g. here , here and here ), which works but which I don't fully understand, is to wrap the Table[] with an Evaluate[] : Plot[Evaluate[Table[x^n, {n, 1, 3}]], {x, 0, 1}] or equivalently f[x_,n_]:=x^n; Plot[Evaluate[Table[f[x,n], {n, 1, 3}]], {x, 0, 1}] This work in this case, because f[x_]:=x^n is a simple function. However, suppose I have a complicated function g[y] which uses its argument y as a bound for an iterator: g[y_] := Total[Table[1, {z, 1, Round[y + 1]}]] Mathematica is not smart enough to recognize that this is equivalent to g[y_]:=Round[y]+1 , and usually such a simplification will not be possible anyways. g[y] cannot be evaluated symbolically, because of the iterator, although it's still plenty fast when given a machine number. Then trying to plot various curves using a table constructed with g[y] without Evaluate[] Plot[Table[g[x*n], {n, 1, 3}], {x, 0, 1}] will make all the curves the same color. Adding Evaluate[] Plot[Evaluate[Table[g[x*n], {n, 1, 3}]], {x, 0, 1}] causes Mathematica to throw an error message about using a bad iterator. ( Table::iterb: "Iterator {z,1,Round[1+x]} does not have appropriate bounds ). Why, exactly, is Evaluate[] necessary in the simple case? Is it true that Plot[] is interpreting the table as a multi-valued function? Why? How can we achieve the same result in the complicated case where the technique fails?
Evaluate is necessary in this simple case because Plot has attribute HoldAll, and evaluates f only after assigning specific numerical values to x and because Plot determines automatic styles based on the unevaluated form of f . When you call Plot[Table[ ... ], ...] , Plot looks at its first argument, Table[ ... ] , without evaluating it and notes that it has a length of 1, and it constructs style specifications based on that information. You can override this behavior of Plot by applying Evaluate to its first argument. A simple way to accomplish what you want is to redefine g so that it wraps its output with Hold : g[y_] := Hold@Total[Table[1, {z, 1, Round[y + 1]}]] Plot[Evaluate@Table[g[n*x], {n, 1, 3}], {x, 0, 1}] This works because the evaluated form of the first argument to Plot is now {Hold[Total[Table[1, {z, 1, Round[x + 1]}]]], Hold[Total[Table[1, {z, 1, Round[2 x + 1]}]]], Hold[Total[Table[1, {z, 1, Round[3 x + 1]}]]]} which does have a length of 3, and it doesn't produce an error because each of these three forms is held unevaluated until they are inside an environment that has a value bound to x . Note that this variation g[y_] := Total[Table[1, {z, 1, Round[y + 1]}]] Plot[Evaluate@Table[Hold@g[n*x], {n, 1, 3}], {x, 0, 1}] does not work, because it prevents g from being evaluated at all - we want g to be expanded with different values of n . Evaluate@Table[Hold@g[n*x], {n, 1, 3}] (* == {Hold[g[n x]], Hold[g[n x]], Hold[g[n x]]} *)
{ "source": [ "https://mathematica.stackexchange.com/questions/8637", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1806/" ] }
8,645
Suppose that I have two plots, plot1 and plot2 . The plots have different ranges and different axes. Here is a fictitious example that makes no scientific sense, but demonstrates my issue with the size of framed plots: imgSize = 475; plot1 = Plot[x^2, {x, 0, 1}, Frame -> True, FrameLabel -> {"x (nm)", "y (nm)"}, BaseStyle -> {FontFamily -> "Arial", 20}, ImageSize -> imgSize]; plot2 = Plot[x^2, {x, -10, 10}, PlotRange -> {-10, 1000}, Frame -> True, FrameLabel -> {"\!\(\*SuperscriptBox[SubscriptBox[\"x\", \"a\"], \ \"2\"]\) (\!\(\*SuperscriptBox[\"nm\", \"2\"]\))", "\!\(\*SuperscriptBox[SubscriptBox[\"y\", \"b\"], \"2\"]\) (\!\(\ \*SuperscriptBox[\"nm\", \"2\"]\))"}, BaseStyle -> {FontFamily -> "Arial", 20}, ImageSize -> imgSize]; Grid[{{plot1, plot2}}] I get this output: Notice that plot1 and plot2 are not really the same size -- in terms of the size of the outer frame of each. In particular, the outer frame of plot1 has greater height than that of plot2 . In addition, I think that the outer frame of plot1 has greater width than that of plot2 . I think this is because of the different ranges and different axis labels of the two plots. Observed separately, one probably could not discern a difference in size between plot1 and plot2 . But when they are next to each other, as in a Grid , plot1 looks noticeably "larger" than plot2 . This would look rather poor in a publication, like an article in a scientific journal. Is there any way that I can make the outer frames the same size, such that the plots look like they are the same size?
As Jagra said, the usual solution is to manually specify the ImagePadding values. The problem is that if the plot or frame labels are too large, a fixed ImagePadding may cut them off. But can we automate this? Ideally what we would do is: Create the two plots of fixed vertical size and retrieve their vertical ImagePadding Change the ImagePadding of both to use the larger value. This will ensure that they have the same size while no labels are cut off. So how do we measure the ImagePadding of an existing plot? This is unfortunately tricky as the value depends on the size of the plot . Since the plots will be stacked horizontally, we need to fix the vertical image size before trying to retrieve the padding. But here's a pretty useful solution (that I use regularly): Retrieving the ImagePadding in absolute units First note that I'm fixing the vertical size instead of the horizontal one. This allows the graphics to have differing horizontal sizes if necessary while still aligning perfectly when stacked in a row. verticalSize = 250; plot1 = Plot[x^2, {x, 0, 1}, Frame -> True, FrameLabel -> {"x (nm)", "y (nm)"}, BaseStyle -> {FontFamily -> "Arial", 20}, ImageSize -> {Automatic, verticalSize}]; plot2 = Plot[x^2, {x, -10, 10}, PlotRange -> {-10, 1000}, Frame -> True, FrameLabel -> {"\!\(\*SuperscriptBox[SubscriptBox[\"x\", \"a\"], \ \"2\"]\) (\!\(\*SuperscriptBox[\"nm\", \"2\"]\))", "\!\(\*SuperscriptBox[SubscriptBox[\"y\", \"b\"], \"2\"]\) \ (\!\(\*SuperscriptBox[\"nm\", \"2\"]\))"}, BaseStyle -> {FontFamily -> "Arial", 20}, ImageSize -> {Automatic, verticalSize}]; This function measures the padding (based on @Heike's code): getPadding[g_] := Module[{im}, im = Image[Show[g, LabelStyle -> White, Background -> White]]; BorderDimensions[im] ] Now let's choose the larger one of both the top and bottom paddings of the two figures. This will give us the minimum image padding that still does not cut off labels. {p1h, p1v} = getPadding[plot1]; {p2h, p2v} = getPadding[plot2]; verticalPadding = Max /@ Transpose[{p1v, p2v}] Row[{ Show[plot1, ImagePadding -> {p1h, verticalPadding}], Show[plot2, ImagePadding -> {p2h, verticalPadding}] }] The problem with this approach is that often one would wish to fix the horizontal size of the whole graphic (to fit the text width of the document). I admit that when I had the same problem I did this by iteratively refining the sizes, which is not very elegant, but produces good results automatically.
{ "source": [ "https://mathematica.stackexchange.com/questions/8645", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1185/" ] }
8,650
As a simple example of what I would like to do, suppose I have a list a of all real numbers. I would like to perform a simple check to see if some element of a is positive. Of course, I could do this with a simple loop, but I feel as if Mathematica would have a more efficient way of doing this, in the spirit of functional programming. Is there, or do I just have to do this with a clumsy loop: test=False; For[counter=1;counter<=Length[a];counter++;If[a[[counter]]>0,test=True;];];
If I understand you correctly, simply test if the maximum value in the list is Positive: Positive @ Max @ a Speed comparison with other methods that were posted: timeAvg = Function[func, Do[If[# > 0.3, Return[#/5^i]] & @@ Timing@Do[func, {5^i}], {i, 0, 15}], HoldFirst]; a = RandomInteger[{-1*^7, 2}, 1*^7]; MemberQ[a, _?Positive] // timeAvg Total@UnitStep[-a] =!= Length@a // timeAvg Positive@Max@a // timeAvg 0.593 0.0624 0.01148 Early-exit methods Although very fast, especially with packed lists, the method above does scan the entire list with no possibility for an early exit when a positive elements occurs near the front of the list. In that case a test that does not scan the entire list may be faster, such as the one that R.M posted. Exploring such methods I propose this: ! VectorQ[a, NonPositive] Unlike MemberQ , VectorQ does not unpack a packed list. Timings compared to MemberQ and Max , first with an early positive appearance: SeedRandom[1] a = RandomReal[{-1*^7, 1000}, 1*^7]; Positive @ Max @ a // timeAvg ! VectorQ[a, NonPositive] // timeAvg MemberQ[a, _?Positive] // timeAvg 0.008736 0.00013984 0.2528 (Most of the MemberQ time is spent unpacking the list.) Then no positive appearance (full scan): a = RandomInteger[{-1*^7, 0}, 1*^7]; Positive @ Max @ a // timeAvg ! VectorQ[a, NonPositive] // timeAvg MemberQ[a, _?Positive] // timeAvg 0.01148 1.544 2.528 Finally a mid-range appearance of a positive value in an unpacked list: a = RandomReal[{-50, 0}, 1*^7]; a[[5*^6]] = 1; Positive @ Max @ a // timeAvg ! VectorQ[a, NonPositive] // timeAvg MemberQ[a, _?Positive] // timeAvg 0.212 0.702 1.045
{ "source": [ "https://mathematica.stackexchange.com/questions/8650", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1543/" ] }
8,716
Yesterday the hedcut style was brought up in chat. How can we create a hedcut-like style automatically in Mathematica, using a photograph as a starting point? I am looking to create a similar artistic feel, not necessarily reproduce the hedcut style precisely. Relevant resources: Hedcut-like effect in Photoshop A blog showing illustrations of this style Halftone , spiral cut / engraving , and 'pointillism' effects from the recent image vectorization question. All of these re-compose the image out of dots of varying size or lines of varying width. Sample portraits to work with: @Silvia's idea from yesterday: ImageDeconvolve[Import["http://www.alleba.com/blog/wp-content/photos/put001.jpg"], GaussianMatrix[2.7], Method -> "TSVD"] My own failed first attempt (the part that detect line directions may be useful to people who work on answers): img = Import[ "http://www.stars-portraits.com/img/portraits/stars/j/jimi-hendrix/jimi-hendrix-by-BikerScout.jpg"] (* "Real" images support negative numbers---for convenience *) img = Image[ColorConvert[img, "GrayLevel"], "Real"]; img = ImageRotate[img, Right]; (* horizontal and vertical components of the gradient; the direction can be computed using ArcTan *) gv = ImageCorrelate[img, ( { {0, -1, 0}, {0, 0, 0}, {0, 1, 0} } )]; gh = ImageCorrelate[img, ( { {0, 0, 0}, {1, 0, -1}, {0, 0, 0} } )]; g = GradientFilter[img, 1]; (* verify the number of white pixels in Binarize[g] *) Count[ImageData@Binarize[g], 1, Infinity] (* create small strokes along the outlines *) outline = With[{point = RandomChoice[Position[ImageData@Binarize[g], 1], 1500]}, Graphics@MapThread[ Rotate[Disk[#1, {4, 1}], #2] &, {point, ArcTan @@@ Transpose[{Extract[ImageData[gh], point], Extract[ImageData[gv], point]}]} ] ] (* try to tone down plain grey/dark backgrounds *) detail = ImageAdjust@ ImageAdd[img, ImageMultiply[ColorNegate@ImageAdjust@EntropyFilter[img, 15], 2]] coords = Outer[List, #2, #1] & @@ Range /@ ImageDimensions[img]; fill = With[{point = RandomChoice[ Join @@ ImageData@ImageClip@ColorNegate[detail] -> Join @@ coords, 5000]}, Graphics@MapThread[ Rotate[Disk[#1, {3, 0.8}], #2] &, {point, ArcTan @@@ Transpose[{Extract[ImageData[gh] + 10 $MachineEpsilon, point], Extract[ImageData[gv], point]}]} ] ] Show[fill, outline] Note: I'm not fond of Putin, but his portrait I linked to seems to be easier to handle than some others. Update: Second attempt, based on @Silvia's suggestion to try ContourPlot and wxffles's image vectorization approach . It's better, but still not achieving that feel. img = Import["http://i.stack.imgur.com/YajUp.jpg"] baseimg = ColorConvert[ImageReflect@CurvatureFlowFilter[img], "GrayScale"]; (* Here we could simply use ct=Table[p,{p,0,1,0.02}]; but the following approach gives a better balanced image *) if = Interpolation[ImageLevels[baseimg]]; cif = Derivative[-1][if]; cifmax = cif[1]; f[x_] := cif[x]/cifmax ct = Block[{x}, Table[ x /. First@FindRoot[f[x] == p, {x, 0.5, 0, 1}], {p, 0, 1, 0.02}] ]; lcp = ListContourPlot[ImageData[baseimg], Frame -> False, Contours -> ct, ContourStyle -> (Dashing[{#, 1/50}] &) /@ ((1 - ct)/50), PlotRange -> {0, 1}, AspectRatio -> Automatic, ContourShading -> None]
In this answer I've tried to use different shading styles for different graylevels in the image. First load the image, convert to grayscale, and get its dimensions. img = ColorConvert[Import["UZg4t.jpg"], "Grayscale"]; dim = ImageDimensions[img]; The next step is to create different shading styles.The example hedcut image uses dots and lines for shading, so that's what we'll use. Here I've shamelessly stolen code from R.M's answer for the dot pattern. I use a set of black dots, and also a set of gray ones. I've also created sets of wavy horizontal and vertical lines in the same style. The parameter di controls the dot interval - larger values will result in more spaced out dots and lines. We will also need parts of the image in solid white and solid black, so the last two lines create graphics for those. di = 4; (* di is the dot interval *) gr[x__] := Graphics[x, ImageSize -> dim, PlotRangePadding -> 0]; dots = gr @ Table[{Disk[{Clip[i + 2 Sin[16 Pi j/#2], {1, #1}], Clip[j + 2 Sin[16 Pi i/#1], {1, #2}]}, 1]}, {i, 1., #1, di}, {j, 1., #2, di}] &@@ dim; paledots = gr @ {GrayLevel[0.7], dots[[1]]}; hlines = gr @ Table[Line[Table[{Clip[i + 2 Sin[16 Pi j/#2], {1, #1}], Clip[j + 2 Sin[16 Pi i/#1], {1, #2}]},{i, 1., #1, di}]], {j, 1., #2, di}] &@@ dim; vlines = gr @ Table[Line[Table[{Clip[j + 2 Sin[16 Pi i/#1], {1, #2}], Clip[i + 2 Sin[16 Pi j/#2], {1, #1}]},{i, 1., #1, di}]], {j, 1., #2, di}] &@@ Reverse[dim]; black = gr[{}, Background -> Black]; white = gr[{}, Background -> White]; Next we need to create images from these graphics corresponding to 7 shades from black to white. The darkest shade is pure black. The next lightest shade after black is cross-hatching (both vertical and horizontal lines) plus dots, the next is just cross hatching without the dots, then just horizontal lines, then just dots, then the pale (gray) dots and finally pure white. Note that for the the "cross-hatching plus dots", we need to translate the dots by half a dot interval in both x and y, to make the dots appear in the gaps between the lines rather than on top of them. shades = Image /@ {black, Show[hlines, vlines, dots /. Disk[x_, r_] :> Disk[x + di/2, r]], Show[hlines, vlines], hlines, dots, paledots, white}; Close up, the shades look like this: Zoomed out, we can see that these shading styles approximate a sequence of gray levels from black to white : The key step in the routine comes next. We use ColorQuantize to compress the image into 7 gray levels. The idea is that each of these 7 gray levels will be replaced with the 7 shades we have built. qimg = ColorQuantize[img, Length@shades, Dithering -> False]; The quantized image looks like this : Next we split the quantized image into 7 separate "region" images. Each region image picks out the parts of the quantized image with the corresponding gray levels. levels = Cases[ImageLevels[qimg], {val_, _?Positive} :> val]; regions = Table[ImageApply[1 - Unitize[# - x, 0.01] &, qimg], {x, levels}]; The region images look like this: A bit of tinkering is needed here. The first region image, which corresponds to solid black, should not have any large blocks in it or there will be large blocks of solid black in the final picture, which isn't very hedcut-like. In this example the jacket is going to come out as a solid block of black. The solution is to move these large areas into the second region image, so they will come out shaded with "cross-hatching plus dots". Note that we don't want to remove all the black areas, as they are especially useful for the eyes. We can use DeleteSmallComponents to isolate the large blocks from the first region image: bigblackareas = DeleteSmallComponents[regions[[1]]]; Now we can subtract this from the first region image and add it to the second: regions[[1]] = ImageSubtract[regions[[1]], bigblackareas]; regions[[2]] = ImageAdd[regions[[2]], bigblackareas]; The first two region images now look like this. The jacket and tie have will now be shaded using "cross-hatching plus dots" instead of solid black. We are nearly there now. The next step is to multiply each region image by its corresponding shade image and add them all together: combined = Fold[ImageAdd, First[#], Rest[#]] &@ MapThread[ImageMultiply, {regions,shades}]; The last step is to add some outlines. These can be obtained by binarizing the result of a GradientFilter : outlines = Binarize @ ColorNegate @ GradientFilter[img, 2]; To get the final image the outlines are combined with the shaded image, and Gaussian filter applied to soften everything slightly. GaussianFilter[ImageMultiply[combined, outlines], 1] Another couple of examples using the same procedure : Thanks to R.M, Jagra, DGrady and Szabolcs for code, comments and ideas.
{ "source": [ "https://mathematica.stackexchange.com/questions/8716", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/12/" ] }
8,753
I have 3D clustered data: Is there any other way to get the concave hull of 3D data points?
Here's a possible approach. First use TetGen to tetrahedralize the data: Needs["TetGenLink`"] {pts, tetrahedra} = TetGenDelaunay[data3D]; Next define a function to compute the radius of the circumsphere of a tetrahedron (formula from Wikipedia ) csr[{aa_, bb_, cc_, dd_}] := With[{a = aa - dd, b = bb - dd, c = cc - dd}, Norm[a.a Cross[b, c] + b.b Cross[c, a] + c.c Cross[a, b]]/(2 Norm[a.Cross[b, c]])] Now calculate the radius of each tetrahedron in your data, and define a function to pick out only those tetrahedra with radius below a given threshold: radii = csr[pts[[#]]] & /@ tetrahedra; alphashape[rmax_] := Pick[tetrahedra, radii, r_ /; r < rmax] This function converts a tetrahedron into a list of 4 triangular faces: faces[tetras_] := Flatten[tetras /. {a_, b_, c_, d_} :> {{a, b, c}, {a, b, d}, {a, c, d}, {b, c, d}}, 1] We also need to remove internal polygons. Internal polygons appear twice, since they belong to two tetrahedra, so we simply need to prune the list of faces to those which only appear once in the list. externalfaces[faces_] := Cases[Tally[Sort /@ faces], {face_, 1} :> face] Now we can generate the graphics for a particular value of rmax polys = externalfaces@faces@alphashape[2.0]; Graphics3D[GraphicsComplex[pts, Polygon@polys], Boxed -> False] Here's an animation showing the effect of different values of rmax
{ "source": [ "https://mathematica.stackexchange.com/questions/8753", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/-1/" ] }
8,829
I have a problem with defining a function and most of time I get confused by Set or = and SetDelayed or := . I read the help section but I didn't find out what the difference is between defining a function as y[x_] := ... and y[x_] = ...
References and intro First, let me point out that = is shorthand for Set and := for SetDelayed ; this facilitates searching the docs. Also, as Simon Woods points out in a comment to the question, there is a tutorial on this. Explanation The basic distinction is this: y[x_]=expr means evaluate expr , then whenever you see y[something] evaluate evaluate what resulted. On the other hand, y[x_]:=expr means "whenever you see y[something] , evaluate expr anew". Here's how to see it: a = 5; y[x_] = a*x y[3] a = 10 y[3] (* 15 10 15 *) That is, when you define y , it evaluates the right hand side to 5*x and assigns that; if you change a later, it never sees it. On the other hand, a = 5; f[x_] := a*x f[3] a = 10 f[3] (* 15 10 30 *) Compare also: ?? y So, the value of a at the time of definition has been "baked in", while with SetDelayed , we get ??f that is, the value of a at execution time is what will be used. Pitfalls Here is an example where using SetDelayed results in a calculation being unnecessarily performed multiple times: fsd[x_] := Integrate[z, {z, 0, x}] gs[x_] = Integrate[z, {z, 0, x}]; If I try with a number, they give the same answer. But look at the DownValues : ??fsd ??gs So, in gs , the integration has already been done, while in fsd it is performed anew every time fsd is evaluted. Observe: t1 = Table[fsd[x], {x, 0, 1, .05}]; // AbsoluteTiming t2 = Table[gs[x], {x, 0, 1, .05}]; // AbsoluteTiming (* {0.061729, Null} {0.000061, Null} *) and t1 == t2 evaluates to True . The reason for the timing differences is precisely that the symbolic integration is done every time for one, only once for the other. Another possible pitfall is using an already-defined symbold for the right hand side. For instance, consider the difference between these: ClearAll[f, g]; x = 5; f[x_] := Sin[x]; g[x_] = Sin[x]; f[1] g[1] (* Sin[1] Sin[5] *) A simple way to avoid this is to simply use a formal symbol : h[\[FormalX]_] = Sin[\[FormalX]] which looks like this in the FrontEnd: Memoization As a final note, one may combine Set and SetDelayed to implement memoization . Here is how to calculate a Fibonacci number recursively, with ClearAll[fib]; fib[1] = 1; fib[2] = 1; fib[n_Integer] := fib[n] = fib[n - 1] + fib[n - 2] and without ClearAll[fibnaive]; fibnaive[1] = 1; fibnaive[2] = 1; fibnaive[n_Integer] := fibnaive[n - 1] + fibnaive[n - 2] memoization. The idea behind this is explained, for instance, here or here . You can also find some elaborations here .
{ "source": [ "https://mathematica.stackexchange.com/questions/8829", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1810/" ] }
8,841
I'd like to plot the graph of the direction field for a differential equation, to get a feel for it. I'm a novice, right now, when it comes to plotting in Mathematica, so I'm hoping that someone can provide a fairly easy to understand and thorough explanation. My hope is that I will become fairly proficient at understanding plotting in Mathematica, as well as differential equations. I'm a little more familiar with differential equations, but very far from what I'd consider to be an expert. I do have an equation in mind, taken from this question from Math.SE: $$y'=\dfrac{y+e^x}{x+e^y}$$ I ran DSolve on it, and after a minute it was unable to evaluate the function. So perhaps this could make for an interesting exploration for others as well. I'm wondering what experience in Mathematica has taught others about what can be done in Mathematica - I'm hoping someone can offer some useful tips and demonstrations. I'm really interested in learning about what can be done with differential equations, so I think that other equations will suffice if they serve as a better example.
For a first sketch of the direction field you might use StreamPlot : f[x_, y_] = (y + E^x)/(x + E^y) StreamPlot[{1, f[x, y]}, {x, 1, 6}, {y, -20, 5}, Frame -> False, Axes -> True, AspectRatio -> 1/GoldenRatio]
{ "source": [ "https://mathematica.stackexchange.com/questions/8841", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1735/" ] }
8,865
I can write either Integrate[x^2, {x,0,3}] or f[x_] = x^2 Integrate[f[x],{x,0,3}] and get the same computation. Suppose I wanted to define a function like that for myself - that is, a function into which I can pass either a defined function (like f[x] in the second example) or an expression (like x^2 in the first example), so I can do whatever I want to the function on some interval. For example, I can say SetAttributes[i,HoldAll]; i[fn_,intvl_] := Block[{var = intvl[[1]], ii = Function[Evaluate[var],fn]}, p1 = Plot[ii[Evaluate[var]],intvl]; p2 = Plot[ii[Evaluate[var]]^2,intvl]; GraphicsRow[{p1,p2}] ]; Then either i[x^2,{x,1,2}] or f[x_] = x^2 i[f[t],{t,1,2}] will produce side-by-side plots of x^2 and x^4 . Is this the right (or even a right) way to do this?
To define your own function with the same properties that (e.g.) Plot has, there are several ingredients which I'll try to develop step by step: Start by trying the simplest thing: i0[fn_, intvl_] := Module[{}, p1 = Plot[fn, intvl]; p2 = Plot[fn^2, intvl]; GraphicsRow[{p1, p2}]]; Clear[x]; i0[x^2, {x, 0, 2}] Why HoldAll is needed But now we immediately get in trouble when we do x = 1; i0[x^2, {x, 1, 2}] Plot::itraw: Raw object 1 cannot be used as an iterator. This never happens if you just call Plot[x^2, {x,1,2}] . The reason is that Plot has attribute Holdall , and you correctly implemented that already: SetAttributes[i, HoldAll]; i[fn_, intvl_] := Module[{}, p1 = Plot[fn, intvl]; p2 = Plot[fn^2, intvl]; GraphicsRow[{p1, p2}]]; x = 1; i[x^2, {x, 0, 2}] Using SyntaxInformation and declaring local variables The next thing you'd want to do is to give the user some feedback when the syntax is entered incorrectly: SyntaxInformation[i] = {"LocalVariables" -> {"Plot", {2, 2}}, "ArgumentsPattern" -> {_, _, OptionsPattern[]} }; This causes the variable x to be highlighted in turquois when it appears as the function variable, telling us visually that the global definition x = 1 should have no effect locally. The OptionsPattern is in there just in case you decide to implement it later. But how does one really ensure that the x is local? In the function so far, we're lucky because we pass all arguments on to Plot which also has attribute HoldAll , so that we don't have to worry about the global value of x = 1 creeping in before we give control to the plotting functions. Where your approach fails Things are not so easy in general, though. This is where your construction fails, because as soon as you write intvl[[1]] the evaluator kicks in and replaces x by 1 . To see this, just try to add axis labels x , y to the second plot, and modify the first plot to show the passed-in function plus x : i[fn_, intvl_] := Block[{var = intvl[[1]]}, p1 = Plot[fn + var, intvl]; p2 = Plot[fn^2, intvl, AxesLabel -> {var, "y"}]; GraphicsRow[{p1, p2}]]; x = 1; i[x^2, {x, 0, 2}] The first plot should show x^2 + x but shows x^2 + 1 , and the second plot has horizontal label 1 instead of x . This happens because I've declared the global variable x = 1 and didn't prevent it from being used inside the function i . It's a somewhat artificial example, but I wanted to address the case where the independent variable really is needed by itself inside the function. When it appears as the first element of the second argument in i , a variable is supposed to be a dummy variable for local use only (that's how Plot treats it). In the example above, I used Block instead of Module because this was supposed to mirror the code in the question. However, I will now continue to use Module , because Block should generally be avoided if you want to make sure that only the variables spelled out in the function body are treated as local. See the documentation for the difference. Wrapping arguments in Hold and its relatives So we have to really make use of the HoldAll attribute of our function now, to prevent the variable from being evaluated. Here is a way to do this for the argument pattern of the above example. The main thing is that it always keeps the external variable and function wrapped in Hold , HoldPattern or HoldForm so it never gets evaluated. If you look at the Plot commands in the function i below, you'll see that I'm now using local variables: ii is the function, and localVar is the independent variable. This means I needed to replace the externally given symbol (say, x as above) by a new locally defined symbol localVar . To do that, I first need to identify the external variable symbol, called externalSymbol , from the first entry in the range intvl passed to the function. I chose to do this with a replacement rule that acts on Hold[intvl] and returns a held pattern that can be used later to replace the external variable in the given function fn by using the rule externalSymbol :> localVar . The result is the local function ii which I then plot using the minimum and maximum limits from Rest[intvl] . So here is how the function looks if I want it to do the same as in the last failed attempt (trying to plot x^2 + x when the given function is x^2 ): i[fn_, intvl_] := Module[{ ii, p1, p2, externalSymbol, localVar, min, max }, externalSymbol = ReleaseHold[ Hold[intvl] /. {x_, y__} :> HoldPattern[x] ]; ii = ReleaseHold[ Hold[fn] /. externalSymbol :> localVar]; {min, max} = Rest[intvl]; p1 = Plot[ii + localVar, {localVar, min, max}]; p2 = Plot[ii^2, {localVar, min, max}, AxesLabel -> {HoldForm @@ externalSymbol, "y"}]; GraphicsRow[{p1, p2}]]; z = 1; i[z^2, {z, 0, 2}] So the symbol z that I used here has been handled properly as a local variable even though it had a global value. Edit: using Unevaluated In the previous example, the line externalSymbol = ReleaseHold[Hold[intvl] /. {x_, y__} :> HoldPattern[x]] extracts the variable name from Hold[intvl] , and wraps it in HoldPattern so that it can be fed into the next replacement rule defining ii . Here, ReleaseHold only serves to strip off the original Hold surrounding intvl , but it leaves the HoldPattern intact. Once you understand the need for holding arguments this way, the next step is to simplify the complicated sequence of steps by introducing the function Unevaluated . It's special because it temporarily "disables" the normal operation of Mathematica 's evaluation process which caused me to use Hold in the first place. So I'll now write Unevaluated[intvl] instead of Hold[intvl] , making the additional ReleaseHold unnecessary: externalSymbol=Unevaluated[intvl]/.{x_,y__} :> HoldPattern[x]; Comparing this to the lengthier form above, you may ask how the result can possibly be the same, because the ReplaceAll operation /. in both cases is performed on a wrapped version of intvl , and the rule {x_,y__} :> HoldPattern[x] doesn't affect that wrapper. This is because Unevaluated disappears all by itself, right after it (and its contents) enter the function surrounding it. The only effect of Unevaluated is to prevent evaluation at the point where Mathematica would normally examine the arguments of the surrounding function and evaluate them. In our case, the "surrounding function" is /. ( ReplaceAll ). With this, a simpler version of the function that no longer uses ReleaseHold would be this: i[fn_, intvl_] := Module[{ii, p1, p2, externalSymbol, localVar, min, max}, externalSymbol = Unevaluated[intvl] /. {x_, y__} :> HoldPattern[x]; ii = Unevaluated[fn] /. externalSymbol :> localVar; {min, max} = Rest[intvl]; p1 = Plot[ii + localVar, {localVar, min, max}]; p2 = Plot[ii^2, {localVar, min, max}, AxesLabel -> {HoldForm @@ externalSymbol, "y"}]; GraphicsRow[{p1, p2}]];
{ "source": [ "https://mathematica.stackexchange.com/questions/8865", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/790/" ] }
8,885
How can I draw the 5 interlocking Olympic rings with Mathematica ? ( SVG version ) Edit Hard choice, but some pretty cool answers here. I didn't have 3D answers in mind when I posted the question, but without a doubt, they look much better than the 2D. Very subjective choice for the selected answer, but I do like @cormullion's answer.
A rather crude way of accomplishing this is just to draw multiple shapes layered such that the rings interlock. ringSegment[mid_, deg_, color_] := { Thickness[0.05],CapForm["Butt"], White, Circle[mid, 1, deg], Thickness[0.03], RGBColor @@ (color/255), Circle[mid, 1, deg + {-0.1, 0.1}]} olblue = {0, 129, 188}; olyellow = {255, 177, 49}; olBlack = {35, 34, 35}; olGreen = {0, 157, 87}; olRed = {238, 50, 78}; Graphics @ GraphicsComplex[ {{2.5, 0}, {1.3, -1}, {0, 0}, {5, 0}, {3.8, -1}}, ringSegment @@@ {{1, {0, 5/4 π}, olBlack}, {2, {0, π}, olyellow}, {3, {0, 2 π}, olblue}, {2, {-π 9/8, 1/4 π}, olyellow}, {4, {0, 5/4 π}, olRed}, {5, {0, 7/8 π}, olGreen}, {1, {5/4 π, 5/2 π}, olBlack}, {5, {7/8 π, 2 π}, olGreen}, {4, {-3/4 π, 1/4 π}, olRed}} ]
{ "source": [ "https://mathematica.stackexchange.com/questions/8885", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/77/" ] }
8,895
I am seeking a convenient and effective way to calculate such geometric quantities. I've used packages like TensoriaCalc , but they don't work at all time. Sometimes, I run into the following error: Symbol Tensor is Protected. Symbol TensorType is Protected. Symbol TensorName is Protected. Here is the code I'm using: Clear [i, j, φ, τ, σ] q["case"] = Metric[ SubMinus[i], SubMinus[j], E^(2 φ[σ]) (\[DifferentialD]τ^2 + \[DifferentialD] σ^2), CoordinateSystem -> {τ, σ}, TensorName -> "T", StartIndex -> 1 ] I think the above is correct, since I merely modified the example from the package manual. It gives me the correct answer sometimes (if I only use one notebook). Also, I ran the codes from the chapter "General Relativity" in the book " Mathmatica for theoretical physics" by Gerd Baumann, but none of them work Is there more efficient way to calculate them? Please give me some suggestions about this.
General remarks In General Relativity we work in a 4-dimentional Lorentzian manifold i.e. there is a metric tensor $g$ of signature $(+,-,-,-)$ or $(-,+,+,+)$. Theses signatures are mathematically equivalent and we choose the latter because of certain quite formal aspects even though there are some physically relevant reasons for choosing the former one. In a neighbourhood of any point we choose a local chart $xx = (x^{1},x^{2},x^{3},x^{4})$ where the metric tensor is represented by real functions $g_{\alpha\beta}(x^{\mu})$ i.e. $g = g_{\alpha\beta}(x^{\mu}) dx^{\alpha}\otimes dx^{\beta}$ (We enumerate indices by $1,2,3,4$ unlike traditionally $0,1,2,3$ for representing tensors in Mathematica by Table s and accessing their entries by Part e.g. [[1,1]] ). Now assuming the Einstein notation we need the following objects : inverse metric $g^{\mu \nu}$ : (i.e. $g^{\mu \nu} g_{\nu\alpha} = \delta^{\mu}_{\alpha} )\quad$ ( InverseMetric[g][[μ, ν]] ) Christoffel symbols (of the second kind) $\Gamma^{\mu}_{\phantom{\mu}\nu\sigma}=\frac{1}{2}g^{\mu\alpha}\left\{\frac{\partial g_{\alpha\nu}}{\partial x^{\sigma}}+\frac{\partial g_{\alpha\sigma}}{\partial x^{\nu}}-\frac{\partial g_{\nu\sigma}}{\partial x^{\alpha}}\right\}\quad$ ( ChristoffelSymbol[g, xx][[μ, ν, σ]] ) Riemann tensor $R^{\mu}_{\phantom{\mu}\nu\lambda\sigma}=\partial_{\lambda}\Gamma^{\mu}_{\phantom{\mu}\nu\sigma}-\partial_{\sigma} \Gamma^{\mu}_{\phantom{\mu}\nu\lambda}+\Gamma^{\mu}_{\phantom{\mu}\rho\lambda}\Gamma^{\rho}_{\phantom{\mu}\nu\sigma}-\Gamma^{\mu}_{\phantom{\mu}\rho\sigma}\Gamma^{\rho}_{\phantom{\mu}\nu\lambda}\quad$ ( RiemannTensor[g, xx][[μ, ν, λ, σ]] ) Ricci tensor $R_{\mu\nu}=R^{\lambda}_{\phantom{\lambda}\mu\lambda\nu}\quad$ ( RicciTensor[g, xx][[μ, ν]] ) Ricci scalar $R = R^{\mu}_{\phantom{\lambda}\mu}\quad$ ( RicciScalar[g, xx] ) A straightforward implementation It will be convenient to define geometrical objects in the following order (this may become a frame for developing a package): InverseMetric[ g_] := Simplify[ Inverse[g] ] ChristoffelSymbol[g_, xx_] := Block[{n, ig, res}, n = 4; ig = InverseMetric[ g]; res = Table[(1/2)*Sum[ ig[[i,s]]*(-D[ g[[j,k]], xx[[s]]] + D[ g[[j,s]], xx[[k]]] + D[ g[[s,k]], xx[[j]]]), {s, 1, n}], {i, 1, n}, {j, 1, n}, {k, 1, n}]; Simplify[ res] ] RiemannTensor[g_, xx_] := Block[{n, Chr, res}, n = 4; Chr = ChristoffelSymbol[ g, xx]; res = Table[ D[ Chr[[i,k,m]], xx[[l]]] - D[ Chr[[i,k,l]], xx[[m]]] + Sum[ Chr[[i,s,l]]*Chr[[s,k,m]], {s, 1, n}] - Sum[ Chr[[i,s,m]]*Chr[[s,k,l]], {s, 1, n}], {i, 1, n}, {k, 1, n}, {l, 1, n}, {m, 1, n}]; Simplify[ res] ] RicciTensor[g_, xx_] := Block[{Rie, res, n}, n = 4; Rie = RiemannTensor[ g, xx]; res = Table[ Sum[ Rie[[ s,i,s,j]], {s, 1, n}], {i, 1, n}, {j, 1, n}]; Simplify[ res] ] RicciScalar[g_, xx_] := Block[{Ricc,ig, res, n}, n = 4; Ricc = RicciTensor[ g, xx]; ig = InverseMetric[ g]; res = Sum[ ig[[s,i]] Ricc[[s,i]], {s, 1, n}, {i, 1, n}]; Simplify[res] ] Following this way one could define another interesting geometrical objects e.g. the Weyl tensor $ C_{\mu\nu\lambda\sigma}=R_{\mu\nu\lambda\sigma}-\left(g_{\mu[\lambda}R_{\nu]\sigma}-g_{\nu[\lambda}R_{\sigma]\mu}\right)+\frac{1}{3}R g_{\mu[\lambda}g_{\nu]\sigma}$ Schwarzschild-like ansatz for a static spherically symmetric spacetime In order to start with a concrete example let's define coordinates and a metric tensor of 4-dimensional static spherically symmetric Lorentzian spacetime : xx = {t, x, θ, ϕ}; g = { {-E^(2 ν[x]), 0 , 0, 0}, { 0, E^(2 λ[x]), 0, 0}, { 0, 0, x^2, 0}, { 0, 0, 0, x^2 Sin[θ]^2}}; Now let's compute RicciScalar : RicciScalar[g, xx] If you want to solve Einstein equations of a vacuum spacetime (e.g. the Schwarzschild spacetime) you should solve equations : RicciTensor[g, xx] == 0 . RicciTensor[g, xx] Now you have to choose two independent equations, e.g. eqs={ λ'[x] ( 2 + x ν'[x]) -x ( ν'[x]^2+ ν''[x]), -1 + E^(2 λ[x]) + x ( λ'[x] - ν'[x])}; and solve this system of ordinary differential equations : eqs[[1]] == 0; eqs[[2]] == 0; with appropriate boundary conditions. In case of the Schwarzschild solution that should be g -> g0 at infinity, where g0 is the Minkowski metric. de-Sitter spacetime Let's find e.g. scalar curvature of de-Sitter spacetime ( a is a constant): Clear[g] g = {{-(1 - x^2/a^2), 0, 0, 0}, { 0, 1/(1 - x^2/a^2), 0, 0}, { 0, 0, x^2, 0}, { 0, 0, 0, x^2 Sin[θ]^2}}; RicciScalar[g, xx] 12/a^2 Thus we have shown that de-Sitter spacetime has a constant scalar curvature.
{ "source": [ "https://mathematica.stackexchange.com/questions/8895", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1713/" ] }
8,945
It seems that DeleteCases is not compatible with string patterns, at least directly (see, for example, this question ). Is this true? If so, why is this the case? It seems that the earlier question did not really address this. For example, suppose that I have a list of strings and I want to delete all strings which contain the letter "X" : DeleteCases[{"ab", "aXb"}, ___ ~~ "X" ~~ ___] gives undesired output: {"ab", "aXb"} One workaround is Select[{"ab", "aXb"}, ! StringMatchQ[#, ___ ~~ "X" ~~ ___] &] which gives the correct output: {"ab"} But why doesn't DeleteCases[{"ab", "aXb"}, ___ ~~ "X" ~~ ___] work?
My guess is that WRI made an explicit design decision to separate general patterns and string patterns in order to manage ambiguities where the two syntaxes overlap. As a simple example, consider the pattern (_~~"x").. . When we draw no distinction between general patterns and string patterns, then this expression is ambiguous. If interpreted as a general pattern then it matches a sequence of two-character strings, each of which ends with "x". If interpreted as a string pattern then it matches a single string where every second character is an "x". Which did the user intend? If Mathematica arbitrarily chooses one, how can the user express the other? I think that WRI wisely decided to side-step issues like this by keeping the two syntaxes separate. We are given the tools to change that decision if it is convenient for us. For example, we could define a wrapper function that promotes a string pattern to a general pattern: s[pat_] := _String?(StringMatchQ[#, pat]&) Cases[{"ab", "ax", "xa"}, s[_~~"x"]] (* {"ax"} *) This function gives us a means to disambiguate the example from above: MatchQ[{"ax", "bx", "cx"}, {s[(_~~"x")..]}] (* False *) MatchQ[{"axbxcx"}, {s[(_~~"x")..]}] (* True *) MatchQ[{"ax", "bx", "cx"}, {s[(_~~"x")]..}] (* True *) MatchQ[{"axbxcx"}, {s[(_~~"x")]..}] (* False *) Alternatively, we could define a lifting operator that can convert a general pattern-matching function into one that interprets any string pattern that manifestly references StringExpression in the requested fashion: lift[f_][a___] := f @@ Replace[{a}, p_StringExpression :> s@p, {1}] myCases = lift[Cases]; myCases[{"ab", "ax", "xa"}, _~~"x"] (* {"ax"} *) lift[DeleteCases][{"ab", "ax", "xa"}, _~~"x"] (* {"ab", "xa"} *) Note that the definition of lift exploits Mathematica's interpretation of _~~"x" as a general pattern -- it wouldn't work if it were interpreted as a string pattern instead. s and lift are intended as simple illustrations rather than robust functionality. lift , for example, does not handle replacement rules and it runs into the very ambiguity under discussion. Both are also likely to have other subtle and unintended behaviours that may arise in general use. But they might be useful in controlled contexts (e.g. in an application where the patterns are known to be simple and occur in large enough numbers to justify the notational convenience).
{ "source": [ "https://mathematica.stackexchange.com/questions/8945", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1185/" ] }
8,997
I have a set of data points in two columns in a spreadsheet (OpenOffice Calc): I would like to get these into Mathematica in this format: data = {{1, 3.3}, {2, 5.6}, {3, 7.1}, {4, 11.4}, {5, 14.8}, {6, 18.3}} I have Googled for this, but what I find is about importing the entire document, which seems like overkill. Is there a way to kind of cut and paste those two columns into Mathematica ?
Here is a manual method using copy-and-paste that is suitable for small volumes of data on an ad hoc basis... 1) Enter the following expression into a notebook, but don't evaluate it: data = ImportString["", "TSV"] 2) Copy the cells from the source spreadsheet onto the clipboard. 3) Paste the contents of the clipboard between the empty pair of quotes in the expression from 1) . If Mathematica brings up a dialog asking whether you want "escapes inserted", select Yes . The result should look something like this: data = ImportString[" 1.0\t2.0\t3.0 0.4\t0.5\t0.6 7.0\t8.0\t9.0 ","TSV"] 4) Press SHIFT - ENTER to evaluate the expression. 5) data now contains the pasted cell data, interpreted as Tab-Separated Values (TSV). Alternate Approach Follows steps 1) through 3) as before, then... 4a) Triple-click on ImportString in the expression from 1) . 5a) Press CTRL - SHIFT - ENTER to evaluate the highlighted expression in place. 6a) The notebook now contains an expression that looks like this: data = {{1., 2., 3.}, {0.4, 0.5, 0.6}, {7., 8., 9.}} ... but that expression has not been evaluated yet.
{ "source": [ "https://mathematica.stackexchange.com/questions/8997", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1877/" ] }