We all know that Mathematica is great, but it also often lacks critical functionality. What kind of external packages / tools / resources do you use with Mathematica?
I'll edit (and invite anyone else to do so too) this main post to include resources which are focused on general applicability in scientific research and which as many people as possible will find useful. Feel free to contribute anything, even small code snippets (as I did below for a timing routine).
Also, undocumented and useful features in Mathematica 7 and beyond you found yourself, or dug up from some paper/site are most welcome.
Please include a short description or comment on why something is great or what utility it provides. If you link to books on Amazon with affiliate links please mention it, e.g., by putting your name after the link.
Packages:
LevelScheme
is a package that greatly expands Mathematica's capability to produce good looking plots. I use it if not for anything else then for the much, much improved control over frame/axes ticks. Its newest version is called SciDraw, and it will be released sometime this year.- David Park's
Presentation Package
(US$50 - no charge for updates) - Jeremy Michelson's
grassmannOps
package provides resources for doing algebra and calculus with Grassmann variables and operators that have non trivial commutation relations. - John Brown's
GrassmannAlgebra
package and book for working with Grassmann and Clifford algebras. - RISC (Research Institute for Symbolic Computation) has a variety of packages for Mathematica (and other languages) available for download. In particular, there is Theorema for automated theorem proving, and the multitude of packages for symbolic summation, difference equations, etc. at the Algorithmic Combinatorics group's software page.
Tools:
MASH
is Daniel Reeves's excellent Perl script essentially providing scripting support for Mathematica v7. (Now built in as of Mathematica 8 with the-script
option.)- An
alternate Mathematica shell
with a GNU readline input (using python, *nix only) - ColourMaths package allows you to visually select parts of an expression and manipulate them. http://www.dbaileyconsultancy.co.uk/colour_maths/colour_maths.html
Resources:
Wolfram's own repository
MathSource
has a lot of useful if narrow notebooks for various applications. Also check out the other sections such asCurrent Documentation
,Courseware
for lectures,- and
Demos
for, well, demos.
The Mathematica Wikibook.
Books:
- Mathematica programming: an advanced introduction by Leonid Shifrin (
web
,pdf
) is a must read if you want to do anything more than For loops in Mathematica. We have the pleasure of havingLeonid
himself answering questions here. - Quantum Methods with Mathematica by James F. Feagin (amazon)
- The Mathematica Book by Stephen Wolfram (amazon) (
web
) - Schaum's Outline (amazon)
- Mathematica in Action by Stan Wagon (amazon) - 600 pages of neat examples and goes up to Mathematica version 7. Visualization techniques are especially good, you can see some of them on the author's
Demonstrations Page
. - Mathematica Programming Fundamentals by Richard Gaylord (
pdf
) - A good concise introduction to most of what you need to know about Mathematica programming. - Mathematica Cookbook by Sal Mangano published by O'Reilly 2010 832 pages. - Written in the well known O'Reilly Cookbook style: Problem - Solution. For intermediates.
- Differential Equations with Mathematica, 3rd Ed. Elsevier 2004 Amsterdam by Martha L. Abell, James P. Braselton - 893 pages For beginners, learn solving DEs and Mathematica at the same time.
Undocumented (or scarcely documented) features:
- How to customize Mathematica keyboard shortcuts. See
this question
. - How to inspect patterns and functions used by Mathematica's own functions. See
this answer
- How to achieve consistent size for GraphPlots in Mathematica? See
this question
. - How to produce documents and presentations with Mathematica. See
this question
.
By popular demand, the code to generate the top-10 SO answerers plot (except annotations) using the SO API.
Recursive pure functions (
#0
) seem to be one of the darker corners of the language. Here are a couple of non-trivial examples of their use , where this is really useful (not that they can not be done without it). The following is a pretty concise and reasonably fast function to find connected components in a graph, given a list of edges specified as pairs of vertices:What happens here is that we first map a dummy symbol on each of the vertex numbers, and then set up a way that, given a pair of vertices
{f[5],f[10]}
, say, thenf[5]
would evaluate tof[10]
. The recursive pure function is used as a path compressor (to set up memoization in such a way that instead of long chains likef[1]=f[3],f[3]=f[4],f[4]=f[2], ...
, memoized values get corrected whenever a new "root" of the component is discovered. This gives a significant speed-up. Because we use assignment, we need it to be HoldAll, which makes this construct even more obscure and more attractive ). This function is a result of on and off-line Mathgroup discussion involving Fred Simons, Szabolcs Horvat, DrMajorBob and yours truly. Example:It is certainly much slower than a built-in, but for the size of code, quite fast still IMO.
Another example: here is a recursive realization of
Select
, based on linked lists and recursive pure functions:For example,
It is however not properly tail recursive, and will blow the stack (crash the kernel) for larger lists. Here is the tail-recursive version:
For example,
I find it really useful when developing packages to add this keyboard shortcut to my
SystemFiles/FrontEnd/TextResources/Windows/KeyEventTranslations.tr
file.Next for every
Packagename.m
I make aPackagenameTest.nb
notebook for testing and the first 2 cells of the test notebook are set as initialization cells. In the first cell I putto load the very useful PackageManipulations library which was written by Leonid. The second cell contains
which all do the actual package reloading. Note the first two lines are there only to
Remove
all symbols as I like to keep the contexts as clean as possible.Then the workflow for writing and testing a package becomes something like this.
Packagename.m
.PackagenameTest.nb
and doCTRL + ALT + i
.This causes the initialization cells to reload the package, which makes testing real simple.
One trick I've used, which allows you to emulate the way most built-in functions work with bad arguments (by sending a message and then returning the whole form unevaluated) exploits a quirk of the way
Condition
works when used in a defintion. Iffoo
should only work with one argument:If you have more complex needs, it's easy to factor out the argument validation and message generation as an independent function. You can do more elaborate things by using side effects in
Condition
beyond just generating messages, but in my opinion most of them fall into the "sleazy hack" category and should be avoided if possible.Also, in the "metaprogramming" category, if you have a Mathematica package (
.m
) file, you can use the"HeldExpressions"
element to get all the expressions in the file wrapped inHoldComplete
. This makes tracking things down much easier than using text-based searches. Unfortunately, there's no easy way to do the same thing with a notebook, but you can get all the input expressions using something like the following:Lastly, you can use the fact that
Module
emulates lexical closures to create the equivalent of reference types. Here's a simple stack (which uses a variation theCondition
trick for error handling as a bonus):Now you can print the elements of a list in reverse order in a needlessly convoluted way!
Internal`InheritedBlock
I have learned recently the existence of such useful function as
Internal`InheritedBlock
, from this message of Daniel Lichtblau in the official newsgroup.As I understand,
Internal`InheritedBlock
allows to pass a copy of an outbound function inside theBlock
scope:I think this function can be very useful for everyone who need to modify built-in functions temporarily!
Comparison with Block
Let us define some function:
Now we wish to pass a copy of this function into the
Block
scope. The naive trial does not give what we want:Now trying to use delayed definition in the first argument of
Block
(it is an undocumented feature too):We see that in this case
a
works but we have not got a copy of the originala
inside of theBlock
scope.Now let us try
Internal`InheritedBlock
:We have got a copy of the original definition for
a
inside of theBlock
scope and we may modify it in the way we want without affecting the global definition fora
!Mathematica is a sharp tool, but it can cut you with its somewhat untyped behaviour and avalanches of cryptic diagnostic messages. One way to deal with this is to define functions following this idiom:
That is a lot of boilerplate, which I'm frequently tempted to skip. Especially when prototyping, which happens a lot in Mathematica. So, I use a macro called
define
that allows me to stay disciplined, with much less boilerplate.A basic usage of
define
is like this:It doesn't look like much at first, but there are some hidden benefits. The first service that
define
provides is that it automatically appliesClearAll
to the symbol being defined. This ensures that there are no leftover definitions -- a common occurrence during the initial development of a function.The second service is that the function being defined is automatically "closed". By this I mean that the function will issue a message and abort if it is invoked with an argument list that is not matched by one of the definitions:
This is the primary value of
define
, which catches a very common class of error.Another convenience is a concise way to specify attributes on the function being defined. Let's make the function
Listable
:In addition to all of the normal attributes,
define
accepts an additional attribute calledOpen
. This preventsdefine
from adding the catch-all error definition to the function:Multiple attributes may be defined for a function:
Without further ado, here is the definition of
define
:The exhibited implementation supports neither up-values nor currying, nor patterns more general than simple function definition. It remains useful, however.