pages tagged mathematica http://meng6net.localhost/tag/mathematica/ <p><small>Copyright © 2005-2020 by <code>Meng Lu &lt;lumeng3@gmail.com&gt;</code></small></p> Meng Lu's home page ikiwiki Mon, 22 May 2017 20:24:50 +0000 Wolfram http://meng6net.localhost/computing/programming/Wolfram/ http://meng6net.localhost/computing/programming/Wolfram/ Mathematica Wolfram computing note programming Sat, 20 May 2017 21:53:47 +0000 2017-05-21T06:06:00Z <h2>Programming idioms</h2> <h3>Caching the result of a time-comsuming computation in a symbol's <code>DownValue</code></h3> <pre><code>ClearAll[f] f[x_] := f[x] = (Pause[5]; Print["Time consuming definition run!"]; 1); In[31]:= DownValues[f] Out[31]= {HoldPattern[f[x_]]:&gt;(f[x]=(Pause[5];Print[Time consuming definition run!];1))} In[32]:= f[1]//AbsoluteTiming//Timing f[1]//AbsoluteTiming//Timing During evaluation of In[32]:= Time consuming definition run! Out[32]= {0.061456,{5.00291,1}} Out[33]= {7.*10^-6,{1.*10^-6,1}} In[34]:= DownValues[f] Out[34]= {HoldPattern[f[1]]:&gt;1,HoldPattern[f[x_]]:&gt;(f[x]=(Pause[5];Print[Time consuming definition run!];1))} </code></pre> Haskell and Wolfram Language syntax comparison http://meng6net.localhost/computing/programming/Haskell_and_Wolfram_Language_syntax_comparison/ http://meng6net.localhost/computing/programming/Haskell_and_Wolfram_Language_syntax_comparison/ Haskell Mathematica Wolfram computing note programming Fri, 19 May 2017 02:50:12 +0000 2017-05-22T20:24:50Z <table class="datatable"> <thead> <tr> <th>description</th> <th>Haskell</th> <th>Wolfram</th> <th colspan="2">comment</th> </tr> </thead> <tbody> <tr> <td>defining a named function with explicitly named arguments</td> <td> <pre> <code>incrementInteger :: Int -&gt; Int<br />incrementInteger n = n + 1</code></pre></td> <td> <pre><code>incrementInteger[n_Integer] := n + 1;</code></pre></td> <td colspan="2"></td> </tr> <tr> <td>defining a named function with lambda expression</td> <td> <pre> <code>incrementInteger :: Int -&gt; Int<br />incrementInteger = \n -&gt; n + 1</code></pre></td> <td> <pre> <code>incrementInteger = Function[{n}, n + 1];</code></pre></td> <td colspan="2"></td> </tr> <tr> <td>defining a function with a function name as one of the arguments</td> <td> <pre> <code>Prelude&gt; increment = \x -&gt; x+1<br />Prelude&gt; double = \x -&gt; 2*x<br />Prelude&gt; thenDouble someFunc = double . someFunc<br />Prelude&gt; thenDouble increment 3<br />8</code></pre></td> <td> <pre> <code>In[1]:= double = Function[x, 2<em>x];<br />increment = Function[x, x + 1];<br />thenDouble[someFunc_] := Composition[double, someFunc];<br /><br />In[4]:= thenDouble[increment]<br /><br />Out[4]= Function[x, 2 x]@</em>Function[x, x + 1]<br /><br />In[5]:= (thenDouble[increment])[3]<br /><br />Out[5]= 8<br /></code></pre></td> <td colspan="2"></td> </tr> <tr> <td>defining a function with locally definded intermediate functions</td> <td> <pre> <code>Prelude&gt; :{<br />Prelude&gt; myFunc1 x =<br />Prelude&gt; let y = sin x<br />Prelude&gt; in cos y<br />Prelude&gt; :}<br />Prelude&gt; myFunc1 pi<br />1.0<br /><br />Prelude&gt; :{<br />Prelude&gt; myFunc2 x =<br />Prelude&gt; cos y<br />Prelude&gt; where<br />Prelude&gt; y = sin x<br />Prelude&gt; :}<br />Prelude&gt; myFunc2 pi<br />1.0</code></pre></td> <td> <pre> <code>In[1]:= myFunc[x_]:=With[{f=Sin[x]},Cos[f]]<br />myFunc[Pi]<br />Out[2]= 1</code></pre></td> <td colspan="2">Alternatively, instead of using <code>With</code> (for symbolic replacement), <a href= "https://reference.wolfram.com/language/tutorial/BlocksComparedWithModules.html"> use <code>Module</code> (for lexical scoping) or <code>Block</code> (for dynamic scoping)</a>.</td> </tr> </tbody> </table> Wolfram Language (Mathematica) package structure http://meng6net.localhost/journal/Wolfram_Language_Mathematica_package_structure/ http://meng6net.localhost/journal/Wolfram_Language_Mathematica_package_structure/ Eclipse IDE IntelliJ IDEA Mathematica Wolfram Language computing note project Tue, 16 May 2017 23:59:39 +0000 2017-05-16T23:59:39Z <p>When creating a package in Wolfram Language (Mathematica), the typical structure looks like the following:</p> <p><code>path/to/MyPackage/</code>:</p> <pre><code>. ├── Documentation │ └── English │ ├── Guides │ │ └── MyPackage.nb │ ├── ReferencePages │ │ └── Symbols │ │ ├─── MySymbol1.nb │ │ └─── MySymbol2.nb │ └── Tutorials | ├── MyTutorial1.nb │ └── MyTutorial2.nb ├── FrontEnd │ ├── Palettes │ │ ├── MyPalette1.nb │ │ └── MyPalette2.nb │ └── SystemResources │ └── Bitmaps │ └── MyPackage │ ├── XXX.png │ └── YYY.png ├── Kernel │ ├── MyPackageFile1.wl │ ├── MyPackageFile2.wl │ ├── MyPackage.wl │ └── init.m ├── PacletInfo.m └── PacletInfoTemplate.m </code></pre> Installing and configuring Mathematica http://meng6net.localhost/computing/installing_and_configuring/installing_and_configuring_mathematica/ http://meng6net.localhost/computing/installing_and_configuring/installing_and_configuring_mathematica/ computing configuration documentation installation mathematica note software tool Tue, 16 May 2017 23:59:39 +0000 2017-05-16T23:59:39Z <h2><code>$UserBaseDirectory/Kernel/init.m</code></h2> <p>Make a symbolic link from a version controlled <code>init.m</code> to <code>$UserBaseDirectory/Kernel/init.m</code>. It 1) defines some environment variables such as</p> <pre> <code>SetEnvironment["$DropboxDirectory" -&gt; FileNameJoin[{$HomeDirectory, "Dropbox"}]] </code></pre> <p>and 2) loads some packages that I use frequently enough that loading them every time is convenient:</p> <pre><code>&lt;&lt; meng` </code></pre> <h2> <code>$UserBaseDirectory/SystemFiles/FrondEnd/Stylesheets</code></h2> <p>Make a symbolic link from a version controlled directory of stylesheets <code>path/to/Stylesheets/</code> to <code>$UserBaseDirectory/SystemFiles/FrondEnd/Stylesheets</code> so your own stylesheets is readily accessible from menu Format &gt; Stylesheets and you can keep them update-to-date with its version control repository.</p> <h2>Install SSL certificates</h2> <p>Sometimes, in order to operate with some Web sites with functions like <code>URLFetch</code>, additional SSL certificates associated with the site needs to be appended in</p> <pre> <code>FileNameJoin[{$InstallationDirectory, "SystemFiles", "Links", "HTTPClient", "SSL", "cacert.pem"}] </code></pre> <p>This will allow HTTPClient to use the SSL certificate for authentication.</p> <h2><code>FrequentlyRunCommands.nb</code></h2> <p>I have a notebook where I record all the frequently run commands for quick reuse. It can be set to automatically open when Mathematica starts.</p> <ul> <li>Format → Option Inspector</li> <li>choose "Global Preference"</li> <li>Global Options → File Locations → AutoOpenNotebooks</li> <li>Set value to <code>"/path/to/notebook.nb"</code>; separate notebooks by linebreaks</li> </ul> <h2>Preferences</h2> <h3>Mail server</h3> <ul> <li>Preferences &gt; Internet Connectivity &gt; Mail Settings.</li> </ul> <h3>Interface</h3> <ul> <li>Preferences &gt; Interface &gt; Show open/close icon for cell groups</li> </ul> <h2>Uninstalling</h2> <p>See <a href="http://support.wolfram.com/kb/12473">Wolfram documentation</a>.</p> <p>When having multiple versions installed, to uninstall one of them, delete</p> <ul> <li><code>/usr/local/Wolfram/Mathematica/VERSION</code></li> </ul> <p>Replace <code>VERSION</code> with the version number you would like to delete.</p> Munging style for Mathematica code layout http://meng6net.localhost/computing/munging_style_for_mathematica_code_layout/ http://meng6net.localhost/computing/munging_style_for_mathematica_code_layout/ computing mathematica note programming tip Tue, 16 May 2017 23:59:39 +0000 2017-05-16T23:59:39Z <p>This is a description to a programming and code formatting style for Mathematica programs that I call "munging style code layout".</p> <p>Any self-contained part of a Mathematica program is a Mathematica expression. As the oft-mentioned idiom said, in Mathematica, "everything is an expression". The appearance of a Mathematica expression is <code>function[arg1, arg2, ...]</code> ("functions", composite expressions) or simply <code>foobar</code> ("symbols", atomic expressions). This is true for any part of a Mathematica program at any depth.</p> <p>Any Mathematica function is essentially a nested structure of the above building blocks. Complex Mathematica program tends to have deeply nested expressions like</p> <pre> <code>f4[arg41, f3[arg31, arg32, f2[arg21, f1[input], ...], ...], arg43, ...] (* comment explaining what f1, f2, f3, f4 does *) </code></pre> <p>Imagine a complex Mathematica program having hundreds of above expressions, sometimes nesting each other. It is hard to read or understand code formatted this way because one needs to constantly jumping out and back into the brackets <code>[ ... ]</code>. This is a <a href= "https://en.wikipedia.org/wiki/Stack_(abstract_data_type">stack</a>) data structure stored in one's brain that one has to frequently navigate.</p> <p>Over the time I have gradually established a particular formatting style for complex Mathematica functions with such deep nested structure. I think it helps writing and understanding my Mathematica programs. I call it <strong>munging style code layout</strong>. It's nothing but putting small parts of the code onto separate lines and use <a href= "http://reference.wolfram.com/mathematica/ref/Composition.html"><code> Composition</code></a> to chain them up:</p> <pre><code>Composition[ f4[arg41, #, arg43, ...]&amp;, (* comment for what f4 does *) f3[arg31, arg32, #, ...]&amp;, (* comment for what f3 does *) f2[arg21, #, ...]&amp;, (* comment for what f2 does *) f1 (* comment for what f1 does *) ][input] </code></pre> <p>I call it <a href= "http://en.wikipedia.org/wiki/Mung_(computer_term)"><em>munging</em></a> because it overall operates on a compact initial input argument, typically represented by a Mathematica symbol, and process it step by step and little by little, for multiple steps before returning a final desired output.</p> <p>This way of laying out the code has a few advantages:</p> <ol> <li> <p>The program body will spread out to multiple lines naturally according to each step's logic. The code is still logically nested, but not visually nested.</p> </li> <li> <p>Each munging step can be commented at the end of line, so it's easier to write and read the comment. One line of code is structurally and logically simple, so each line's comment will be short too. As a result, the comments for the complete program should also be easier to read and understand.</p> </li> <li> <p>It is easier to write and debug code. A typical scenario is</p> </li> </ol> <p>Write the first simple step</p> <pre><code>Composition[ f1[arg11, #, arg13]&amp; (* comment for what f1 does *) ][input] </code></pre> <p>Run it and verify the first step does what it should do, then add a second step, and comment as you code:</p> <pre><code>Composition[ f2[arg21, #, ...]&amp;, (* comment for what f2 does *) f1[arg11, #, arg13]&amp; (* comment for what f1 does *) ][input] </code></pre> <p>Notice, when writing the body of <code>f2[...]</code>, one needs <em>not</em> to edit <em>around</em> <code>f1[....]</code>, but on a separate new line. This may not sound like a big deal, but, according to my personal experience, it eliminates a lot of chances of messing up with <code>f1[...]</code> when typing <code>f2[...]</code>. If one decides the <code>f2</code> just typed down shouldn't stay, he can just simply select the whole line of of <code>f2</code> -- typically a keyboard-only operation or a mouse-only operation depending on the programmer's habit and the editor -- and delete it without worrying about messing up any part of <code>f1[...]</code> or needing to copy <code>f1[...]</code> out safely. So there is an ergonomic advantage to separate <code>f1[...]</code> and <code>f2[...]</code> into different lines. You write your code in small chunks, and manage the chunks as compositing terms of the entire logic.</p> <p>In addition, one can easily print out the intermediate value in-between two steps by simply inserting a NOP step:</p> <pre><code>Composition[ f2[arg21, #, ...]&amp;, (* comment for what f2 does *) (Print@#; #)&amp;, (* NOP step to print out intermediate value for debugging *) f1 (* comment for what f1 does *) ][input] </code></pre> <p>When you have more steps added, you might find the first few steps aren't perfect, now you can insert NOP step to print out more intermediate values:</p> <pre><code>Composition[ ..., f4[arg41, #, arg43, ...]&amp;, (* comment for what f4 does *) (Print@#; #)&amp;, f3[arg31, arg32, #, ...]&amp;, (* comment for what f3 does *) (Print@#; #)&amp;, f2[arg21, #, ...]&amp;, (* comment for what f2 does *) f1 (* comment for what f1 does *) ][input] </code></pre> <p>Notice inserting these NOP steps again doesn't require editing at lines of the actual code (<code>f1[...]&amp;</code>, <code>f2[...]&amp;</code>, ...). So there is natural and convenient separation of debugging code and real code.</p> <p>All of this may appear to be too trivial a matter to document. But I found Mathematica code is harder to format than most other programming languages, partially because the character of Mathematica language (functional and symbolic) and partially because neither Mathematica notebook nor Wolfram Workbench provides sophisticated and robust automatic code formatting/indentation. This little formatting rule seems to help me writing better Mathematica code, sometimes also faster and easier in doing so.</p> <p><big>Related:</big></p> <ul> <li><a href= "http://meng6net.localhost/tag/blog/munging_data_streams_with_functional_programming_and_lambda_expressions_in_java/"> Munging data streams with functional programming and lambda expressions in Java 8</a></li> </ul> use cheaper functions when possible http://meng6net.localhost/use_cheaper_functions_when_possible/ http://meng6net.localhost/use_cheaper_functions_when_possible/ computing mathematica programming stub tip Tue, 16 May 2017 23:59:39 +0000 2017-05-16T23:59:39Z <p>Mathematica is functional and has high code density. It tends to lead one to use more powerful function than the task really necessarily requires. Because high code density typically means it needs to check many things to figure out default (or <code>Automatic</code>) values, it slows down the program unnecessarily sometimes.</p> <h2><code>Join</code> vs. <code>Flatten</code></h2> <p>Use <code>Join</code> to join lists, not Flatten, if you know it's safe. <code>Join</code> is faster and uses less memory.</p> <pre><code>In[6]:= Quit[] In[1]:= data=Table[RandomVariate[NormalDistribution[],100],{20}]; In[2]:= m1=MemoryInUse[]; Do[t=Flatten[data,1],{10000}]//AbsoluteTiming m2=MemoryInUse[]; m2-m1 Out[3]= {3.9662268,Null} Out[5]= 74704 </code></pre> <p>Compare it to</p> <pre><code>Join@@list In[2]:= m1=MemoryInUse[]; Do[t=Join@@data,{10000}]//AbsoluteTiming m2=MemoryInUse[]; m2-m1 Out[3]= {0.1730099,Null} Out[5]= 36240 </code></pre> White space characters in Wolfram Language / Mathematica http://meng6net.localhost/blog/white_space_characters_in_wolfram_language/ http://meng6net.localhost/blog/white_space_characters_in_wolfram_language/ journal mathematica note to-do white space wolfram language Tue, 17 Mar 2015 06:50:27 +0000 2017-05-16T21:18:29Z <p>In Wolfram Language / Mathematica, there are the following escaped characters that end with <code>Space</code>:</p> <pre><code>$WhiteSpaceCharacters = { "\[AutoSpace]", "\[COMPATIBILITYKanjiSpace]", "\[InvisibleSpace]", "\[LetterSpace]", "\[MediumSpace]", "\[NegativeMediumSpace]", "\[NegativeThickSpace]", "\[NegativeThinSpace]", "\[NegativeVeryThinSpace]", "\[NonBreakingSpace]", "\[RawSpace]", "\[ThickSpace]", "\[ThinSpace]", "\[VeryThinSpace]" } </code></pre> <p>These can be found by evaluating <code>?\[*Space]</code> in a Mathematica notebook.</p> <p>To actually obtain these in copiable text was not straightforward for me as I did not find a programmable way to generate the above list. Instead, I copied the cell expression out (by selecting the output cell, pressing <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>E</kbd>, and copying out the text), and then run <code>ack</code> to extract any strings that start is sandwiched with <code>\[</code> and <code>]</code>:</p> <pre> <code>17:09:43 meng@meng2maclap:~/Temp$ ack -o "\\\\\\\\\[.*Space\]" cellexpr.txt | sort | uniq AutoSpace COMPATIBILITYKanjiSpace InvisibleSpace LetterSpace MediumSpace NegativeMediumSpace NegativeThickSpace NegativeThinSpace NegativeVeryThinSpace NonBreakingSpace RawSpace ThickSpace ThinSpace VeryThinSpace </code></pre> <p>Curiously, only <code>\[AutoSpace]</code>, <code>\[NonBreakingSpace]</code>, <code>\[RawSpace]</code> satisfy <code>StringMatchQ[#, RegularExpression["[[:whitespace:]]"]]&amp;</code>.</p> <p>See the <a href= "http://meng6net.localhost/tag/mathematica/white_space_characters_in_wolfram_language.cdf">CDF file</a> for details.</p> /blog/white_space_characters_in_wolfram_language/#comments Wolfram-related Twitter accounts and the alike http://meng6net.localhost/blog/wolfram-related_twitter_accounts_and_the_alike/ http://meng6net.localhost/blog/wolfram-related_twitter_accounts_and_the_alike/ blog mathematica note twitter weibo wolfram Sat, 07 Mar 2015 02:37:38 +0000 2017-05-16T23:59:39Z <ul> <li>news, blogs, comprehensive <ul> <li>Wolfram: <a href= "https://twitter.com/WolframResearch">@WolframResearch</a></li> <li>Wolfram Japan: <a href= "https://twitter.com/WolframJapan">@WolframJapan</a></li> <li>Wolfram China: <a href= "http://www.weibo.com/wolframchina">@WolframChina</a></li> <li>Wolfram Education: <a href= "https://twitter.com/WolframEdu">@WolframEdu</a></li> <li>Wolfram Careers: <a href= "https://twitter.com/WolframCareers">@WolframCareers</a></li> <li>Stephen Wolfram: <a href= "https://twitter.com/stephen_wolfram">@stephen_wolfram</a></li> <li>Conrad Wolfram: <a href= "https://twitter.com/conradwolfram">@conradwolfram</a></li> <li>Wolfram NKS: <a href= "https://twitter.com/WolframNKS">@WolframNKS</a></li> <li><a href="https://blog.wolfram.com">Wolfram Blog</a></li> <li><a href="http://blog.stephenwolfram.com/">Stephen Wolfram Blog</a></li> </ul> </li> <li>Wolfram Language / Mathematica <ul> <li>MathematicaTip: <a href= "https://twitter.com/MathematicaTip">@MathematicaTip</a></li> <li>Mathematica SE: <a href= "https://twitter.com/StackMma">@StackMma</a></li> <li>Tweet-a-Program: <a href= "https://twitter.com/wolframtap">@wolframtap</a>, <a href= "http://wolframtap.tumblr.com/archive">archive on Tumblr</a></li> <li>Mathematica Cookbook: <a href= "https://twitter.com/salmangano">@salmangano</a></li> <li>Wolfram Tip: <a href= "https://twitter.com/WolframTip">@WolframTip</a></li> <li>Sina Weibo: <ul> <li>面向教育的Mathematica: <a href= "http://www.weibo.com/u/5377153058">@面向教育的Mathematica</a></li> <li>Mathematica_李想: <a href= "http://www.weibo.com/u/1682600994">@Mathematica_李想</a></li> <li>Mathematica 中文使用者: <a href= "http://weibo.com/mmachineseusers">@Mathematica中文使用者</a></li> <li>Wolfram 语言编程珠玑: <a href= "http://www.weibo.com/wolframtip">@WolframTip</a></li> </ul> </li> <li><a href="http://mathematica.blogoverflow.com/">Mathematica StackExchange community blog</a></li> </ul> </li> <li>Wolfram|Alpha <ul> <li>Wolfram|Alpha: <a href= "https://twitter.com/Wolfram_Alpha">@Wolfram_Alpha</a></li> <li>Wolfram Fun Facts: <a href= "https://twitter.com/WolframFunFacts">@WolframFunFacts</a></li> <li>Wolfram|Alpha Can't: <a href= "https://twitter.com/wacnt">@wacnt</a></li> <li>WolframAlpha queries: <a href= "https://twitter.com/WA_queries">@WA_queries</a></li> <li>Wolfram_Alpha: <a href= "http://www.weibo.com/wolpha">@Wolfram_Alpha</a></li> <li><a href="http://wolframalpha.tumblr.com/">Wolfram|Alpha Tumblr</a></li> <li><a href="http://blog.wolframalpha.com/">Wolfram|Alpha blog</a></li> </ul> </li> </ul> /blog/wolfram-related_twitter_accounts_and_the_alike/#comments