How to Make Interactive Apps with CDF
April 18, 2012 — Vitaliy Kaurov, Technical Communication & Strategy
A number of you have written us asking about interface design, Dynamic structures, and general starting tips for creating Wolfram Computable Document Format (CDF) files. I will present three examples of CDF files that will provide some insight into good practices. You should also read the recent Mathematica Q&A Series blog post about delivering CDF to your websites and blogs with the help of the CDF Web Deployment Wizard. This enables users to showcase their Mathematica projects online and share them with the global community. Let’s have a look at some features that make CDF great, rising well above other platforms. For a more extensive list, please see the CDF comparison table.
We will start with a short program that numerically solves the challenging problem of constrained global optimization by finding the minimum on a limited surface region. Think of finding the lowest point of an area of a mountain range. Dragging the 2D slider on the interface below automatically changes the surface geometry, and the CDF engine quickly recomputes the new minimum. This is reflected in the updated positions of the red dot. Drag and rotate the 3D graphics with the mouse to get a different view. Hold Ctrl while dragging to zoom (Command on a Mac) or hold Shift and drag to pan.
The code is compact because Mathematica‘s extensive library provides thousands of built-in functions that target a wide scope of tasks. The code is also easily readable because of consistent syntax and meaningful function names. Even a novice user would be able to come up with a similar program in a fairly short time using our extensive documentation full of typical examples. Note that I did not have to program the numerical optimization algorithms packed in the function NMinimize or the interface automatically constructed by Manipulate. While NMinimize is highly automated, I also had the freedom to specify the numerical method I prefer, using the option Method → "RandomSearch". Most of the styling, such as meshes, ranges, ticks, and so on, is also done automatically. Mathematica‘s interactive 2D and 3D graphics are far superior to what most current publishing platforms can offer. As you change the surface, Manipulate forces dynamic updates, constantly running the algorithms of NMinimize. All that in just few lines of code.
Next we will see how the ideas behind CDF scale up when the complexity of our goals grows and many parts need to come together in a single, perfectly working whole. As a case study, consider the Game of Life, which, in addition to its recreational fame, is a powerful scientific example of complex behavior rising from simple rules. (For a deeper insight into this and other simple programs, read Stephen Wolfram’s book A New Kind of Science and apply for the 10th Annual Wolfram Science Summer School.)
Scroll down and click “run” to start the simulation.
If you are familiar with the Game of Life, you probably recognize immediately that this is not its typical implementation. Only black cells represent the usual evolution, while the colorful background is the 2D Fourier power spectrum computed in real time on the changing patterns of black cells. Notice the dramatic change in the Fourier plot when two moving black configurations come close together. Such signatures in the Fourier space can be used for the detection of collisions and close proximity between structures, leading to significant computational speedup compared to the blunt search in original data space. We may gain many other insights into properties of the driving rules and emerging patterns by using built-in Mathematica signal processing tools. This instructive, simultaneous visualization is possible thanks to the function Overlay, a useful construct able to overlap all types of expressions and even preserve interactivity by overlaying controls.
At the end of the code above, there is a nested list of integers representing well-known Game of Life patterns. Simulate them by clicking one of the “preset” buttons followed by “run.” Using SparseArray, I was able to compress the data in these patterns to one third of the original ByteCount. The uncompressing function is included at the beginning of the numbers list. This inclusion of custom data in CDF was done with Manipulate‘s Initialization option. Another way to add data to your CDF document is to use built-in Mathematica data and calls to the WolframAlpha function to access more than 10 trillion pieces of data in our constantly updating curated database.
In addition to automated interfaces with the standard arsenal of sliders, buttons, menus, and numerous other controls, custom interactivity and dynamics are also supported. This gives a lot of room for improvisation, but does not really require much effort. In the code above, it is achieved with the built-in function EventHandler, which manages inputs from the keyboard, mouse, and other devices. It is clear from the code that the MouseClicked event is tracked. Go ahead and color in some cells with mouse clicks. Use the button “random” to fill many cells together.
The Game of Life evolves according to simple mathematical rules packed in the function CellularAutomaton. But what makes it run here? There are no “Do” or “For” loops. The answer is that Manipulate is a dynamic function. It automatically updates if any of its tracked variables change. Therefore, if changing x causes x to change (a recursive definition of the type x=F[x]), Manipulate will continuously update until x settles to a stationary point. This is exactly the case here, as can be seen from the first few lines of code. The stationary point is reached (updating stops) when x=F[x] is satisfied. We took advantage of this in the first argument of Switch (literally, x=x), allowing us to “pause.” This technique of using simple recursive definitions inside dynamic functions comes in quite handy for long-running simulations and animations when you do not want to store all the history of variable values. There are a few other neat tricks in this CDF file. For example, the “size” slider is disabled in “pause”/”run” modes to protect currently evolving configurations. This is reflected with a slightly different visual appearance of the slider, a nice interface element that, again, was not explicitly coded, but purely automated by the option Enabled.
This app has plenty of potential for further development. With slight syntax changes to the function CellularAutomaton, it is possible to produce the evolution of a huge number of other interesting algorithms different from the Game of Life and easy to generalize to spaces other than 2D grids. The same holds for many other built-in Mathematica functions. And what requires a slight change of syntax in Mathematica typically requires writing many more lines of code from scratch in other languages.
Our last example will demonstrate the reusability of Mathematica code. More than 7,800 CDFs available at the Wolfram Demonstrations Project show the diversity of approaches to authoring ideas with interactive interfaces. The Demonstrations Project is the largest free online electronic publishing system dedicated solely to open-source code, interactive in-browser documents, and illustrations of scientific concepts. It continues to grow with submissions from users like you, providing freely downloadable code for learning and reusing. Below is my version of the elegant “Tree Bender” by Theodore Gray. By injecting randomness into the original, purely deterministic fractal and adding just a touch of styling, we can get quite close to producing artistic illustrations. Download the CDF version of this post below to see the minimal code changes I made to the original. The main difference compared to the original code comes from quite a few RandomReal functions in my version. They are pseudorandom number generators and change the appearance of the original regular shapes to random, more natural-looking trees. One million basic random tree samples are controlled by the “environment” slider, which uses SeedRandom to reset the pseudorandom generators. Basic trees are further customizable with the rest of the controls, including the small, green, movable circles on the plot. The interface was meant to be self-explanatory, so go ahead and explore. There are more than 300 quintillion trees in one small CDF file!
CDF documents run the same computational engine as Mathematica, installed on multitudes of computers in universities, companies, and organizations around the world, the engine that has powered scientific research for more than 20 years.
To learn about the full scope of CDF possibilities from our leading experts and authors, register for the Wolfram CDF Virtual Workshop.